clang API Documentation

CGDeclCXX.cpp
Go to the documentation of this file.
00001 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This contains code dealing with code generation of C++ declarations
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CodeGenFunction.h"
00015 #include "CGObjCRuntime.h"
00016 #include "CGCXXABI.h"
00017 #include "clang/Frontend/CodeGenOptions.h"
00018 #include "llvm/Intrinsics.h"
00019 
00020 using namespace clang;
00021 using namespace CodeGen;
00022 
00023 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
00024                          llvm::Constant *DeclPtr) {
00025   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
00026   assert(!D.getType()->isReferenceType() && 
00027          "Should not call EmitDeclInit on a reference!");
00028   
00029   ASTContext &Context = CGF.getContext();
00030 
00031   CharUnits alignment = Context.getDeclAlign(&D);
00032   QualType type = D.getType();
00033   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
00034 
00035   const Expr *Init = D.getInit();
00036   if (!CGF.hasAggregateLLVMType(type)) {
00037     CodeGenModule &CGM = CGF.CGM;
00038     if (lv.isObjCStrong())
00039       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
00040                                                 DeclPtr, D.isThreadSpecified());
00041     else if (lv.isObjCWeak())
00042       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
00043                                               DeclPtr);
00044     else
00045       CGF.EmitScalarInit(Init, &D, lv, false);
00046   } else if (type->isAnyComplexType()) {
00047     CGF.EmitComplexExprIntoAddr(Init, DeclPtr, lv.isVolatile());
00048   } else {
00049     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
00050                                           AggValueSlot::DoesNotNeedGCBarriers,
00051                                                   AggValueSlot::IsNotAliased));
00052   }
00053 }
00054 
00055 /// Emit code to cause the destruction of the given variable with
00056 /// static storage duration.
00057 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
00058                             llvm::Constant *addr) {
00059   CodeGenModule &CGM = CGF.CGM;
00060 
00061   // FIXME:  __attribute__((cleanup)) ?
00062   
00063   QualType type = D.getType();
00064   QualType::DestructionKind dtorKind = type.isDestructedType();
00065 
00066   switch (dtorKind) {
00067   case QualType::DK_none:
00068     return;
00069 
00070   case QualType::DK_cxx_destructor:
00071     break;
00072 
00073   case QualType::DK_objc_strong_lifetime:
00074   case QualType::DK_objc_weak_lifetime:
00075     // We don't care about releasing objects during process teardown.
00076     return;
00077   }
00078 
00079   llvm::Constant *function;
00080   llvm::Constant *argument;
00081 
00082   // Special-case non-array C++ destructors, where there's a function
00083   // with the right signature that we can just call.
00084   const CXXRecordDecl *record = 0;
00085   if (dtorKind == QualType::DK_cxx_destructor &&
00086       (record = type->getAsCXXRecordDecl())) {
00087     assert(!record->hasTrivialDestructor());
00088     CXXDestructorDecl *dtor = record->getDestructor();
00089 
00090     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
00091     argument = addr;
00092 
00093   // Otherwise, the standard logic requires a helper function.
00094   } else {
00095     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
00096                                                   CGF.getDestroyer(dtorKind),
00097                                                   CGF.needsEHCleanup(dtorKind));
00098     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
00099   }
00100 
00101   CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
00102 }
00103 
00104 /// Emit code to cause the variable at the given address to be considered as
00105 /// constant from this point onwards.
00106 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
00107                               llvm::Constant *Addr) {
00108   // Don't emit the intrinsic if we're not optimizing.
00109   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
00110     return;
00111 
00112   // Grab the llvm.invariant.start intrinsic.
00113   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
00114   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
00115 
00116   // Emit a call with the size in bytes of the object.
00117   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
00118   uint64_t Width = WidthChars.getQuantity();
00119   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
00120                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
00121   CGF.Builder.CreateCall(InvariantStart, Args);
00122 }
00123 
00124 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
00125                                                llvm::Constant *DeclPtr,
00126                                                bool PerformInit) {
00127 
00128   const Expr *Init = D.getInit();
00129   QualType T = D.getType();
00130 
00131   if (!T->isReferenceType()) {
00132     if (PerformInit)
00133       EmitDeclInit(*this, D, DeclPtr);
00134     if (CGM.isTypeConstant(D.getType(), true))
00135       EmitDeclInvariant(*this, D, DeclPtr);
00136     else
00137       EmitDeclDestroy(*this, D, DeclPtr);
00138     return;
00139   }
00140 
00141   assert(PerformInit && "cannot have constant initializer which needs "
00142          "destruction for reference");
00143   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
00144   RValue RV = EmitReferenceBindingToExpr(Init, &D);
00145   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
00146 }
00147 
00148 static llvm::Function *
00149 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
00150                                    llvm::FunctionType *ty,
00151                                    const Twine &name);
00152 
00153 /// Create a stub function, suitable for being passed to atexit,
00154 /// which passes the given address to the given destructor function.
00155 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
00156                                         llvm::Constant *dtor,
00157                                         llvm::Constant *addr) {
00158   // Get the destructor function type, void(*)(void).
00159   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
00160   llvm::Function *fn =
00161     CreateGlobalInitOrDestructFunction(CGM, ty,
00162                                        Twine("__dtor_", addr->getName()));
00163 
00164   CodeGenFunction CGF(CGM);
00165 
00166   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
00167                     CGM.getTypes().arrangeNullaryFunction(),
00168                     FunctionArgList(), SourceLocation());
00169 
00170   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
00171  
00172  // Make sure the call and the callee agree on calling convention.
00173   if (llvm::Function *dtorFn =
00174         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
00175     call->setCallingConv(dtorFn->getCallingConv());
00176 
00177   CGF.FinishFunction();
00178 
00179   return fn;
00180 }
00181 
00182 /// Register a global destructor using the C atexit runtime function.
00183 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
00184                                                    llvm::Constant *addr) {
00185   // Create a function which calls the destructor.
00186   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
00187 
00188   // extern "C" int atexit(void (*f)(void));
00189   llvm::FunctionType *atexitTy =
00190     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
00191 
00192   llvm::Constant *atexit =
00193     CGM.CreateRuntimeFunction(atexitTy, "atexit");
00194   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
00195     atexitFn->setDoesNotThrow();
00196 
00197   Builder.CreateCall(atexit, dtorStub)->setDoesNotThrow();
00198 }
00199 
00200 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
00201                                          llvm::GlobalVariable *DeclPtr,
00202                                          bool PerformInit) {
00203   // If we've been asked to forbid guard variables, emit an error now.
00204   // This diagnostic is hard-coded for Darwin's use case;  we can find
00205   // better phrasing if someone else needs it.
00206   if (CGM.getCodeGenOpts().ForbidGuardVariables)
00207     CGM.Error(D.getLocation(),
00208               "this initialization requires a guard variable, which "
00209               "the kernel does not support");
00210 
00211   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
00212 }
00213 
00214 static llvm::Function *
00215 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
00216                                    llvm::FunctionType *FTy,
00217                                    const Twine &Name) {
00218   llvm::Function *Fn =
00219     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
00220                            Name, &CGM.getModule());
00221   if (!CGM.getContext().getLangOpts().AppleKext) {
00222     // Set the section if needed.
00223     if (const char *Section = 
00224           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
00225       Fn->setSection(Section);
00226   }
00227 
00228   if (!CGM.getLangOpts().Exceptions)
00229     Fn->setDoesNotThrow();
00230 
00231   return Fn;
00232 }
00233 
00234 void
00235 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
00236                                             llvm::GlobalVariable *Addr,
00237                                             bool PerformInit) {
00238   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00239 
00240   // Create a variable initialization function.
00241   llvm::Function *Fn =
00242     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
00243 
00244   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
00245                                                           PerformInit);
00246 
00247   if (D->hasAttr<InitPriorityAttr>()) {
00248     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
00249     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
00250     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
00251     DelayedCXXInitPosition.erase(D);
00252   }
00253   else {
00254     llvm::DenseMap<const Decl *, unsigned>::iterator I =
00255       DelayedCXXInitPosition.find(D);
00256     if (I == DelayedCXXInitPosition.end()) {
00257       CXXGlobalInits.push_back(Fn);
00258     } else {
00259       assert(CXXGlobalInits[I->second] == 0);
00260       CXXGlobalInits[I->second] = Fn;
00261       DelayedCXXInitPosition.erase(I);
00262     }
00263   }
00264 }
00265 
00266 void
00267 CodeGenModule::EmitCXXGlobalInitFunc() {
00268   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
00269     CXXGlobalInits.pop_back();
00270 
00271   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
00272     return;
00273 
00274   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00275 
00276   // Create our global initialization function.
00277   llvm::Function *Fn = 
00278     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
00279 
00280   if (!PrioritizedCXXGlobalInits.empty()) {
00281     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
00282     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), 
00283                          PrioritizedCXXGlobalInits.end()); 
00284     for (unsigned i = 0; i < PrioritizedCXXGlobalInits.size(); i++) {
00285       llvm::Function *Fn = PrioritizedCXXGlobalInits[i].second;
00286       LocalCXXGlobalInits.push_back(Fn);
00287     }
00288     LocalCXXGlobalInits.append(CXXGlobalInits.begin(), CXXGlobalInits.end());
00289     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
00290                                                     &LocalCXXGlobalInits[0],
00291                                                     LocalCXXGlobalInits.size());
00292   }
00293   else
00294     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
00295                                                      &CXXGlobalInits[0],
00296                                                      CXXGlobalInits.size());
00297   AddGlobalCtor(Fn);
00298   CXXGlobalInits.clear();
00299   PrioritizedCXXGlobalInits.clear();
00300 }
00301 
00302 void CodeGenModule::EmitCXXGlobalDtorFunc() {
00303   if (CXXGlobalDtors.empty())
00304     return;
00305 
00306   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00307 
00308   // Create our global destructor function.
00309   llvm::Function *Fn =
00310     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
00311 
00312   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
00313   AddGlobalDtor(Fn);
00314 }
00315 
00316 /// Emit the code necessary to initialize the given global variable.
00317 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
00318                                                        const VarDecl *D,
00319                                                  llvm::GlobalVariable *Addr,
00320                                                        bool PerformInit) {
00321   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
00322                 getTypes().arrangeNullaryFunction(),
00323                 FunctionArgList(), SourceLocation());
00324 
00325   // Use guarded initialization if the global variable is weak. This
00326   // occurs for, e.g., instantiated static data members and
00327   // definitions explicitly marked weak.
00328   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
00329       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
00330     EmitCXXGuardedInit(*D, Addr, PerformInit);
00331   } else {
00332     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
00333   }
00334 
00335   FinishFunction();
00336 }
00337 
00338 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
00339                                                 llvm::Constant **Decls,
00340                                                 unsigned NumDecls) {
00341   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
00342                 getTypes().arrangeNullaryFunction(),
00343                 FunctionArgList(), SourceLocation());
00344 
00345   RunCleanupsScope Scope(*this);
00346 
00347   // When building in Objective-C++ ARC mode, create an autorelease pool
00348   // around the global initializers.
00349   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {    
00350     llvm::Value *token = EmitObjCAutoreleasePoolPush();
00351     EmitObjCAutoreleasePoolCleanup(token);
00352   }
00353   
00354   for (unsigned i = 0; i != NumDecls; ++i)
00355     if (Decls[i])
00356       Builder.CreateCall(Decls[i]);    
00357 
00358   Scope.ForceCleanup();
00359   
00360   FinishFunction();
00361 }
00362 
00363 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
00364                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
00365                                                 &DtorsAndObjects) {
00366   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
00367                 getTypes().arrangeNullaryFunction(),
00368                 FunctionArgList(), SourceLocation());
00369 
00370   // Emit the dtors, in reverse order from construction.
00371   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
00372     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
00373     llvm::CallInst *CI = Builder.CreateCall(Callee,
00374                                             DtorsAndObjects[e - i - 1].second);
00375     // Make sure the call and the callee agree on calling convention.
00376     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
00377       CI->setCallingConv(F->getCallingConv());
00378   }
00379 
00380   FinishFunction();
00381 }
00382 
00383 /// generateDestroyHelper - Generates a helper function which, when
00384 /// invoked, destroys the given object.
00385 llvm::Function * 
00386 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
00387                                        QualType type,
00388                                        Destroyer *destroyer,
00389                                        bool useEHCleanupForArray) {
00390   FunctionArgList args;
00391   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
00392   args.push_back(&dst);
00393   
00394   const CGFunctionInfo &FI = 
00395     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
00396                                               FunctionType::ExtInfo(),
00397                                               /*variadic*/ false);
00398   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
00399   llvm::Function *fn = 
00400     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
00401 
00402   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
00403                 SourceLocation());
00404 
00405   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
00406   
00407   FinishFunction();
00408   
00409   return fn;
00410 }