Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This contains code dealing with code generation of C++ declarations
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenFunction.h"
     15 #include "CGObjCRuntime.h"
     16 #include "CGCXXABI.h"
     17 #include "clang/Frontend/CodeGenOptions.h"
     18 #include "llvm/Intrinsics.h"
     19 
     20 using namespace clang;
     21 using namespace CodeGen;
     22 
     23 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
     24                          llvm::Constant *DeclPtr) {
     25   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
     26   assert(!D.getType()->isReferenceType() &&
     27          "Should not call EmitDeclInit on a reference!");
     28 
     29   ASTContext &Context = CGF.getContext();
     30 
     31   CharUnits alignment = Context.getDeclAlign(&D);
     32   QualType type = D.getType();
     33   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
     34 
     35   const Expr *Init = D.getInit();
     36   if (!CGF.hasAggregateLLVMType(type)) {
     37     CodeGenModule &CGM = CGF.CGM;
     38     if (lv.isObjCStrong())
     39       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
     40                                                 DeclPtr, D.isThreadSpecified());
     41     else if (lv.isObjCWeak())
     42       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
     43                                               DeclPtr);
     44     else
     45       CGF.EmitScalarInit(Init, &D, lv, false);
     46   } else if (type->isAnyComplexType()) {
     47     CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
     48   } else {
     49     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
     50                                           AggValueSlot::DoesNotNeedGCBarriers,
     51                                                   AggValueSlot::IsNotAliased));
     52   }
     53 }
     54 
     55 /// Emit code to cause the destruction of the given variable with
     56 /// static storage duration.
     57 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
     58                             llvm::Constant *addr) {
     59   CodeGenModule &CGM = CGF.CGM;
     60 
     61   // FIXME:  __attribute__((cleanup)) ?
     62 
     63   QualType type = D.getType();
     64   QualType::DestructionKind dtorKind = type.isDestructedType();
     65 
     66   switch (dtorKind) {
     67   case QualType::DK_none:
     68     return;
     69 
     70   case QualType::DK_cxx_destructor:
     71     break;
     72 
     73   case QualType::DK_objc_strong_lifetime:
     74   case QualType::DK_objc_weak_lifetime:
     75     // We don't care about releasing objects during process teardown.
     76     return;
     77   }
     78 
     79   llvm::Constant *function;
     80   llvm::Constant *argument;
     81 
     82   // Special-case non-array C++ destructors, where there's a function
     83   // with the right signature that we can just call.
     84   const CXXRecordDecl *record = 0;
     85   if (dtorKind == QualType::DK_cxx_destructor &&
     86       (record = type->getAsCXXRecordDecl())) {
     87     assert(!record->hasTrivialDestructor());
     88     CXXDestructorDecl *dtor = record->getDestructor();
     89 
     90     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
     91     argument = addr;
     92 
     93   // Otherwise, the standard logic requires a helper function.
     94   } else {
     95     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
     96                                                   CGF.getDestroyer(dtorKind),
     97                                                   CGF.needsEHCleanup(dtorKind));
     98     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
     99   }
    100 
    101   CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
    102 }
    103 
    104 /// Emit code to cause the variable at the given address to be considered as
    105 /// constant from this point onwards.
    106 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
    107                               llvm::Constant *Addr) {
    108   // Don't emit the intrinsic if we're not optimizing.
    109   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
    110     return;
    111 
    112   // Grab the llvm.invariant.start intrinsic.
    113   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
    114   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
    115 
    116   // Emit a call with the size in bytes of the object.
    117   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
    118   uint64_t Width = WidthChars.getQuantity();
    119   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
    120                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
    121   CGF.Builder.CreateCall(InvariantStart, Args);
    122 }
    123 
    124 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
    125                                                llvm::Constant *DeclPtr,
    126                                                bool PerformInit) {
    127 
    128   const Expr *Init = D.getInit();
    129   QualType T = D.getType();
    130 
    131   if (!T->isReferenceType()) {
    132     if (PerformInit)
    133       EmitDeclInit(*this, D, DeclPtr);
    134     if (CGM.isTypeConstant(D.getType(), true))
    135       EmitDeclInvariant(*this, D, DeclPtr);
    136     else
    137       EmitDeclDestroy(*this, D, DeclPtr);
    138     return;
    139   }
    140 
    141   assert(PerformInit && "cannot have constant initializer which needs "
    142          "destruction for reference");
    143   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
    144   RValue RV = EmitReferenceBindingToExpr(Init, &D);
    145   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
    146 }
    147 
    148 static llvm::Function *
    149 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    150                                    llvm::FunctionType *ty,
    151                                    const Twine &name);
    152 
    153 /// Create a stub function, suitable for being passed to atexit,
    154 /// which passes the given address to the given destructor function.
    155 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
    156                                         llvm::Constant *dtor,
    157                                         llvm::Constant *addr) {
    158   // Get the destructor function type, void(*)(void).
    159   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
    160   llvm::Function *fn =
    161     CreateGlobalInitOrDestructFunction(CGM, ty,
    162                                        Twine("__dtor_", addr->getName()));
    163 
    164   CodeGenFunction CGF(CGM);
    165 
    166   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
    167                     CGM.getTypes().arrangeNullaryFunction(),
    168                     FunctionArgList(), SourceLocation());
    169 
    170   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
    171 
    172  // Make sure the call and the callee agree on calling convention.
    173   if (llvm::Function *dtorFn =
    174         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
    175     call->setCallingConv(dtorFn->getCallingConv());
    176 
    177   CGF.FinishFunction();
    178 
    179   return fn;
    180 }
    181 
    182 /// Register a global destructor using the C atexit runtime function.
    183 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
    184                                                    llvm::Constant *addr) {
    185   // Create a function which calls the destructor.
    186   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
    187 
    188   // extern "C" int atexit(void (*f)(void));
    189   llvm::FunctionType *atexitTy =
    190     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
    191 
    192   llvm::Constant *atexit =
    193     CGM.CreateRuntimeFunction(atexitTy, "atexit");
    194   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
    195     atexitFn->setDoesNotThrow();
    196 
    197   Builder.CreateCall(atexit, dtorStub)->setDoesNotThrow();
    198 }
    199 
    200 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
    201                                          llvm::GlobalVariable *DeclPtr,
    202                                          bool PerformInit) {
    203   // If we've been asked to forbid guard variables, emit an error now.
    204   // This diagnostic is hard-coded for Darwin's use case;  we can find
    205   // better phrasing if someone else needs it.
    206   if (CGM.getCodeGenOpts().ForbidGuardVariables)
    207     CGM.Error(D.getLocation(),
    208               "this initialization requires a guard variable, which "
    209               "the kernel does not support");
    210 
    211   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
    212 }
    213 
    214 static llvm::Function *
    215 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    216                                    llvm::FunctionType *FTy,
    217                                    const Twine &Name) {
    218   llvm::Function *Fn =
    219     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
    220                            Name, &CGM.getModule());
    221   if (!CGM.getContext().getLangOpts().AppleKext) {
    222     // Set the section if needed.
    223     if (const char *Section =
    224           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
    225       Fn->setSection(Section);
    226   }
    227 
    228   if (!CGM.getLangOpts().Exceptions)
    229     Fn->setDoesNotThrow();
    230 
    231   if (CGM.getLangOpts().AddressSanitizer)
    232     Fn->addFnAttr(llvm::Attribute::AddressSafety);
    233 
    234   return Fn;
    235 }
    236 
    237 void
    238 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
    239                                             llvm::GlobalVariable *Addr,
    240                                             bool PerformInit) {
    241   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    242 
    243   // Create a variable initialization function.
    244   llvm::Function *Fn =
    245     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
    246 
    247   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
    248                                                           PerformInit);
    249 
    250   if (D->hasAttr<InitPriorityAttr>()) {
    251     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
    252     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
    253     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
    254     DelayedCXXInitPosition.erase(D);
    255   }
    256   else {
    257     llvm::DenseMap<const Decl *, unsigned>::iterator I =
    258       DelayedCXXInitPosition.find(D);
    259     if (I == DelayedCXXInitPosition.end()) {
    260       CXXGlobalInits.push_back(Fn);
    261     } else {
    262       assert(CXXGlobalInits[I->second] == 0);
    263       CXXGlobalInits[I->second] = Fn;
    264       DelayedCXXInitPosition.erase(I);
    265     }
    266   }
    267 }
    268 
    269 void
    270 CodeGenModule::EmitCXXGlobalInitFunc() {
    271   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
    272     CXXGlobalInits.pop_back();
    273 
    274   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
    275     return;
    276 
    277   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    278 
    279   // Create our global initialization function.
    280   llvm::Function *Fn =
    281     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
    282 
    283   if (!PrioritizedCXXGlobalInits.empty()) {
    284     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
    285     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
    286                          PrioritizedCXXGlobalInits.end());
    287     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
    288       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
    289       LocalCXXGlobalInits.push_back(Fn);
    290     }
    291     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
    292     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
    293                                                     &LocalCXXGlobalInits[0],
    294                                                     LocalCXXGlobalInits.size());
    295   }
    296   else
    297     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
    298                                                      &CXXGlobalInits[0],
    299                                                      CXXGlobalInits.size());
    300   AddGlobalCtor(Fn);
    301   CXXGlobalInits.clear();
    302   PrioritizedCXXGlobalInits.clear();
    303 }
    304 
    305 void CodeGenModule::EmitCXXGlobalDtorFunc() {
    306   if (CXXGlobalDtors.empty())
    307     return;
    308 
    309   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    310 
    311   // Create our global destructor function.
    312   llvm::Function *Fn =
    313     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
    314 
    315   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
    316   AddGlobalDtor(Fn);
    317 }
    318 
    319 /// Emit the code necessary to initialize the given global variable.
    320 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
    321                                                        const VarDecl *D,
    322                                                  llvm::GlobalVariable *Addr,
    323                                                        bool PerformInit) {
    324   if (CGM.getModuleDebugInfo() && !D->hasAttr<NoDebugAttr>())
    325     DebugInfo = CGM.getModuleDebugInfo();
    326 
    327   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
    328                 getTypes().arrangeNullaryFunction(),
    329                 FunctionArgList(), D->getInit()->getExprLoc());
    330 
    331   // Use guarded initialization if the global variable is weak. This
    332   // occurs for, e.g., instantiated static data members and
    333   // definitions explicitly marked weak.
    334   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
    335       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
    336     EmitCXXGuardedInit(*D, Addr, PerformInit);
    337   } else {
    338     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
    339   }
    340 
    341   FinishFunction();
    342 }
    343 
    344 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
    345                                                 llvm::Constant **Decls,
    346                                                 unsigned NumDecls) {
    347   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    348                 getTypes().arrangeNullaryFunction(),
    349                 FunctionArgList(), SourceLocation());
    350 
    351   RunCleanupsScope Scope(*this);
    352 
    353   // When building in Objective-C++ ARC mode, create an autorelease pool
    354   // around the global initializers.
    355   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
    356     llvm::Value *token = EmitObjCAutoreleasePoolPush();
    357     EmitObjCAutoreleasePoolCleanup(token);
    358   }
    359 
    360   for (unsigned i = 0; i != NumDecls; ++i)
    361     if (Decls[i])
    362       Builder.CreateCall(Decls[i]);
    363 
    364   Scope.ForceCleanup();
    365 
    366   FinishFunction();
    367 }
    368 
    369 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
    370                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
    371                                                 &DtorsAndObjects) {
    372   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    373                 getTypes().arrangeNullaryFunction(),
    374                 FunctionArgList(), SourceLocation());
    375 
    376   // Emit the dtors, in reverse order from construction.
    377   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
    378     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
    379     llvm::CallInst *CI = Builder.CreateCall(Callee,
    380                                             DtorsAndObjects[e - i - 1].second);
    381     // Make sure the call and the callee agree on calling convention.
    382     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
    383       CI->setCallingConv(F->getCallingConv());
    384   }
    385 
    386   FinishFunction();
    387 }
    388 
    389 /// generateDestroyHelper - Generates a helper function which, when
    390 /// invoked, destroys the given object.
    391 llvm::Function *
    392 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
    393                                        QualType type,
    394                                        Destroyer *destroyer,
    395                                        bool useEHCleanupForArray) {
    396   FunctionArgList args;
    397   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
    398   args.push_back(&dst);
    399 
    400   const CGFunctionInfo &FI =
    401     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
    402                                               FunctionType::ExtInfo(),
    403                                               /*variadic*/ false);
    404   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
    405   llvm::Function *fn =
    406     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
    407 
    408   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
    409                 SourceLocation());
    410 
    411   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
    412 
    413   FinishFunction();
    414 
    415   return fn;
    416 }
    417