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 "CGCXXABI.h"
00016 #include "CGObjCRuntime.h"
00017 #include "CGOpenMPRuntime.h"
00018 #include "clang/Frontend/CodeGenOptions.h"
00019 #include "llvm/ADT/StringExtras.h"
00020 #include "llvm/IR/Intrinsics.h"
00021 #include "llvm/Support/Path.h"
00022 
00023 using namespace clang;
00024 using namespace CodeGen;
00025 
00026 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
00027                          llvm::Constant *DeclPtr) {
00028   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
00029   assert(!D.getType()->isReferenceType() && 
00030          "Should not call EmitDeclInit on a reference!");
00031   
00032   ASTContext &Context = CGF.getContext();
00033 
00034   CharUnits alignment = Context.getDeclAlign(&D);
00035   QualType type = D.getType();
00036   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
00037 
00038   const Expr *Init = D.getInit();
00039   switch (CGF.getEvaluationKind(type)) {
00040   case TEK_Scalar: {
00041     CodeGenModule &CGM = CGF.CGM;
00042     if (lv.isObjCStrong())
00043       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
00044                                                 DeclPtr, D.getTLSKind());
00045     else if (lv.isObjCWeak())
00046       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
00047                                               DeclPtr);
00048     else
00049       CGF.EmitScalarInit(Init, &D, lv, false);
00050     return;
00051   }
00052   case TEK_Complex:
00053     CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
00054     return;
00055   case TEK_Aggregate:
00056     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
00057                                           AggValueSlot::DoesNotNeedGCBarriers,
00058                                                   AggValueSlot::IsNotAliased));
00059     return;
00060   }
00061   llvm_unreachable("bad evaluation kind");
00062 }
00063 
00064 /// Emit code to cause the destruction of the given variable with
00065 /// static storage duration.
00066 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
00067                             llvm::Constant *addr) {
00068   CodeGenModule &CGM = CGF.CGM;
00069 
00070   // FIXME:  __attribute__((cleanup)) ?
00071   
00072   QualType type = D.getType();
00073   QualType::DestructionKind dtorKind = type.isDestructedType();
00074 
00075   switch (dtorKind) {
00076   case QualType::DK_none:
00077     return;
00078 
00079   case QualType::DK_cxx_destructor:
00080     break;
00081 
00082   case QualType::DK_objc_strong_lifetime:
00083   case QualType::DK_objc_weak_lifetime:
00084     // We don't care about releasing objects during process teardown.
00085     assert(!D.getTLSKind() && "should have rejected this");
00086     return;
00087   }
00088 
00089   llvm::Constant *function;
00090   llvm::Constant *argument;
00091 
00092   // Special-case non-array C++ destructors, where there's a function
00093   // with the right signature that we can just call.
00094   const CXXRecordDecl *record = nullptr;
00095   if (dtorKind == QualType::DK_cxx_destructor &&
00096       (record = type->getAsCXXRecordDecl())) {
00097     assert(!record->hasTrivialDestructor());
00098     CXXDestructorDecl *dtor = record->getDestructor();
00099 
00100     function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
00101     argument = llvm::ConstantExpr::getBitCast(
00102         addr, CGF.getTypes().ConvertType(type)->getPointerTo());
00103 
00104   // Otherwise, the standard logic requires a helper function.
00105   } else {
00106     function = CodeGenFunction(CGM)
00107         .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
00108                                CGF.needsEHCleanup(dtorKind), &D);
00109     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
00110   }
00111 
00112   CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
00113 }
00114 
00115 /// Emit code to cause the variable at the given address to be considered as
00116 /// constant from this point onwards.
00117 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
00118                               llvm::Constant *Addr) {
00119   // Don't emit the intrinsic if we're not optimizing.
00120   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
00121     return;
00122 
00123   // Grab the llvm.invariant.start intrinsic.
00124   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
00125   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
00126 
00127   // Emit a call with the size in bytes of the object.
00128   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
00129   uint64_t Width = WidthChars.getQuantity();
00130   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
00131                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
00132   CGF.Builder.CreateCall(InvariantStart, Args);
00133 }
00134 
00135 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
00136                                                llvm::Constant *DeclPtr,
00137                                                bool PerformInit) {
00138 
00139   const Expr *Init = D.getInit();
00140   QualType T = D.getType();
00141 
00142   if (!T->isReferenceType()) {
00143     if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
00144       (void)CGM.getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition(
00145           &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
00146           PerformInit, this);
00147     if (PerformInit)
00148       EmitDeclInit(*this, D, DeclPtr);
00149     if (CGM.isTypeConstant(D.getType(), true))
00150       EmitDeclInvariant(*this, D, DeclPtr);
00151     else
00152       EmitDeclDestroy(*this, D, DeclPtr);
00153     return;
00154   }
00155 
00156   assert(PerformInit && "cannot have constant initializer which needs "
00157          "destruction for reference");
00158   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
00159   RValue RV = EmitReferenceBindingToExpr(Init);
00160   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
00161 }
00162 
00163 /// Create a stub function, suitable for being passed to atexit,
00164 /// which passes the given address to the given destructor function.
00165 llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
00166                                                   llvm::Constant *dtor,
00167                                                   llvm::Constant *addr) {
00168   // Get the destructor function type, void(*)(void).
00169   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
00170   SmallString<256> FnName;
00171   {
00172     llvm::raw_svector_ostream Out(FnName);
00173     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
00174   }
00175   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
00176                                                               VD.getLocation());
00177 
00178   CodeGenFunction CGF(CGM);
00179 
00180   CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
00181                     CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
00182 
00183   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
00184  
00185  // Make sure the call and the callee agree on calling convention.
00186   if (llvm::Function *dtorFn =
00187         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
00188     call->setCallingConv(dtorFn->getCallingConv());
00189 
00190   CGF.FinishFunction();
00191 
00192   return fn;
00193 }
00194 
00195 /// Register a global destructor using the C atexit runtime function.
00196 void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
00197                                                    llvm::Constant *dtor,
00198                                                    llvm::Constant *addr) {
00199   // Create a function which calls the destructor.
00200   llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
00201 
00202   // extern "C" int atexit(void (*f)(void));
00203   llvm::FunctionType *atexitTy =
00204     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
00205 
00206   llvm::Constant *atexit =
00207     CGM.CreateRuntimeFunction(atexitTy, "atexit");
00208   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
00209     atexitFn->setDoesNotThrow();
00210 
00211   EmitNounwindRuntimeCall(atexit, dtorStub);
00212 }
00213 
00214 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
00215                                          llvm::GlobalVariable *DeclPtr,
00216                                          bool PerformInit) {
00217   // If we've been asked to forbid guard variables, emit an error now.
00218   // This diagnostic is hard-coded for Darwin's use case;  we can find
00219   // better phrasing if someone else needs it.
00220   if (CGM.getCodeGenOpts().ForbidGuardVariables)
00221     CGM.Error(D.getLocation(),
00222               "this initialization requires a guard variable, which "
00223               "the kernel does not support");
00224 
00225   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
00226 }
00227 
00228 llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
00229     llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
00230   llvm::Function *Fn =
00231     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
00232                            Name, &getModule());
00233   if (!getLangOpts().AppleKext && !TLS) {
00234     // Set the section if needed.
00235     if (const char *Section = getTarget().getStaticInitSectionSpecifier())
00236       Fn->setSection(Section);
00237   }
00238 
00239   Fn->setCallingConv(getRuntimeCC());
00240 
00241   if (!getLangOpts().Exceptions)
00242     Fn->setDoesNotThrow();
00243 
00244   if (!isInSanitizerBlacklist(Fn, Loc)) {
00245     if (getLangOpts().Sanitize.has(SanitizerKind::Address))
00246       Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
00247     if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
00248       Fn->addFnAttr(llvm::Attribute::SanitizeThread);
00249     if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
00250       Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
00251   }
00252 
00253   return Fn;
00254 }
00255 
00256 /// Create a global pointer to a function that will initialize a global
00257 /// variable.  The user has requested that this pointer be emitted in a specific
00258 /// section.
00259 void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
00260                                           llvm::GlobalVariable *GV,
00261                                           llvm::Function *InitFunc,
00262                                           InitSegAttr *ISA) {
00263   llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
00264       TheModule, InitFunc->getType(), /*isConstant=*/true,
00265       llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
00266   PtrArray->setSection(ISA->getSection());
00267   addUsedGlobal(PtrArray);
00268 
00269   // If the GV is already in a comdat group, then we have to join it.
00270   llvm::Comdat *C = GV->getComdat();
00271 
00272   // LinkOnce and Weak linkage are lowered down to a single-member comdat group.
00273   // Make an explicit group so we can join it.
00274   if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
00275     C = TheModule.getOrInsertComdat(GV->getName());
00276     GV->setComdat(C);
00277   }
00278   if (C)
00279     PtrArray->setComdat(C);
00280 }
00281 
00282 void
00283 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
00284                                             llvm::GlobalVariable *Addr,
00285                                             bool PerformInit) {
00286   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00287   SmallString<256> FnName;
00288   {
00289     llvm::raw_svector_ostream Out(FnName);
00290     getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
00291   }
00292 
00293   // Create a variable initialization function.
00294   llvm::Function *Fn =
00295       CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
00296 
00297   auto *ISA = D->getAttr<InitSegAttr>();
00298   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
00299                                                           PerformInit);
00300 
00301   llvm::GlobalVariable *COMDATKey =
00302       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
00303 
00304   if (D->getTLSKind()) {
00305     // FIXME: Should we support init_priority for thread_local?
00306     // FIXME: Ideally, initialization of instantiated thread_local static data
00307     // members of class templates should not trigger initialization of other
00308     // entities in the TU.
00309     // FIXME: We only need to register one __cxa_thread_atexit function for the
00310     // entire TU.
00311     CXXThreadLocalInits.push_back(Fn);
00312     CXXThreadLocalInitVars.push_back(Addr);
00313   } else if (PerformInit && ISA) {
00314     EmitPointerToInitFunc(D, Addr, Fn, ISA);
00315     DelayedCXXInitPosition.erase(D);
00316   } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
00317     OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
00318     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
00319     DelayedCXXInitPosition.erase(D);
00320   } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
00321     // C++ [basic.start.init]p2:
00322     //   Definitions of explicitly specialized class template static data
00323     //   members have ordered initialization. Other class template static data
00324     //   members (i.e., implicitly or explicitly instantiated specializations)
00325     //   have unordered initialization.
00326     //
00327     // As a consequence, we can put them into their own llvm.global_ctors entry.
00328     //
00329     // If the global is externally visible, put the initializer into a COMDAT
00330     // group with the global being initialized.  On most platforms, this is a
00331     // minor startup time optimization.  In the MS C++ ABI, there are no guard
00332     // variables, so this COMDAT key is required for correctness.
00333     AddGlobalCtor(Fn, 65535, COMDATKey);
00334     DelayedCXXInitPosition.erase(D);
00335   } else if (D->hasAttr<SelectAnyAttr>()) {
00336     // SelectAny globals will be comdat-folded. Put the initializer into a COMDAT
00337     // group associated with the global, so the initializers get folded too.
00338     AddGlobalCtor(Fn, 65535, COMDATKey);
00339     DelayedCXXInitPosition.erase(D);
00340   } else {
00341     llvm::DenseMap<const Decl *, unsigned>::iterator I =
00342       DelayedCXXInitPosition.find(D);
00343     if (I == DelayedCXXInitPosition.end()) {
00344       CXXGlobalInits.push_back(Fn);
00345     } else {
00346       assert(CXXGlobalInits[I->second] == nullptr);
00347       CXXGlobalInits[I->second] = Fn;
00348       DelayedCXXInitPosition.erase(I);
00349     }
00350   }
00351 }
00352 
00353 void CodeGenModule::EmitCXXThreadLocalInitFunc() {
00354   getCXXABI().EmitThreadLocalInitFuncs(
00355       *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
00356 
00357   CXXThreadLocalInits.clear();
00358   CXXThreadLocalInitVars.clear();
00359   CXXThreadLocals.clear();
00360 }
00361 
00362 void
00363 CodeGenModule::EmitCXXGlobalInitFunc() {
00364   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
00365     CXXGlobalInits.pop_back();
00366 
00367   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
00368     return;
00369 
00370   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00371 
00372 
00373   // Create our global initialization function.
00374   if (!PrioritizedCXXGlobalInits.empty()) {
00375     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
00376     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), 
00377                          PrioritizedCXXGlobalInits.end());
00378     // Iterate over "chunks" of ctors with same priority and emit each chunk
00379     // into separate function. Note - everything is sorted first by priority,
00380     // second - by lex order, so we emit ctor functions in proper order.
00381     for (SmallVectorImpl<GlobalInitData >::iterator
00382            I = PrioritizedCXXGlobalInits.begin(),
00383            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
00384       SmallVectorImpl<GlobalInitData >::iterator
00385         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
00386 
00387       LocalCXXGlobalInits.clear();
00388       unsigned Priority = I->first.priority;
00389       // Compute the function suffix from priority. Prepend with zeroes to make
00390       // sure the function names are also ordered as priorities.
00391       std::string PrioritySuffix = llvm::utostr(Priority);
00392       // Priority is always <= 65535 (enforced by sema).
00393       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
00394       llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
00395           FTy, "_GLOBAL__I_" + PrioritySuffix);
00396 
00397       for (; I < PrioE; ++I)
00398         LocalCXXGlobalInits.push_back(I->second);
00399 
00400       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
00401       AddGlobalCtor(Fn, Priority);
00402     }
00403   }
00404 
00405   SmallString<128> FileName;
00406   SourceManager &SM = Context.getSourceManager();
00407   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
00408     // Include the filename in the symbol name. Including "sub_" matches gcc and
00409     // makes sure these symbols appear lexicographically behind the symbols with
00410     // priority emitted above.
00411     FileName = llvm::sys::path::filename(MainFile->getName());
00412   } else {
00413     FileName = SmallString<128>("<null>");
00414   }
00415 
00416   for (size_t i = 0; i < FileName.size(); ++i) {
00417     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
00418     // to be the set of C preprocessing numbers.
00419     if (!isPreprocessingNumberBody(FileName[i]))
00420       FileName[i] = '_';
00421   }
00422 
00423   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
00424       FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
00425 
00426   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
00427   AddGlobalCtor(Fn);
00428 
00429   CXXGlobalInits.clear();
00430   PrioritizedCXXGlobalInits.clear();
00431 }
00432 
00433 void CodeGenModule::EmitCXXGlobalDtorFunc() {
00434   if (CXXGlobalDtors.empty())
00435     return;
00436 
00437   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
00438 
00439   // Create our global destructor function.
00440   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a");
00441 
00442   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
00443   AddGlobalDtor(Fn);
00444 }
00445 
00446 /// Emit the code necessary to initialize the given global variable.
00447 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
00448                                                        const VarDecl *D,
00449                                                  llvm::GlobalVariable *Addr,
00450                                                        bool PerformInit) {
00451   // Check if we need to emit debug info for variable initializer.
00452   if (D->hasAttr<NoDebugAttr>())
00453     DebugInfo = nullptr; // disable debug info indefinitely for this function
00454 
00455   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
00456                 getTypes().arrangeNullaryFunction(),
00457                 FunctionArgList(), D->getLocation(),
00458                 D->getInit()->getExprLoc());
00459 
00460   // Use guarded initialization if the global variable is weak. This
00461   // occurs for, e.g., instantiated static data members and
00462   // definitions explicitly marked weak.
00463   if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
00464     EmitCXXGuardedInit(*D, Addr, PerformInit);
00465   } else {
00466     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
00467   }
00468 
00469   FinishFunction();
00470 }
00471 
00472 void
00473 CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
00474                                            ArrayRef<llvm::Function *> Decls,
00475                                            llvm::GlobalVariable *Guard) {
00476   {
00477     ArtificialLocation AL(*this, Builder);
00478     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
00479                   getTypes().arrangeNullaryFunction(), FunctionArgList());
00480     // Emit an artificial location for this function.
00481     AL.Emit();
00482 
00483     llvm::BasicBlock *ExitBlock = nullptr;
00484     if (Guard) {
00485       // If we have a guard variable, check whether we've already performed
00486       // these initializations. This happens for TLS initialization functions.
00487       llvm::Value *GuardVal = Builder.CreateLoad(Guard);
00488       llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
00489                                                  "guard.uninitialized");
00490       // Mark as initialized before initializing anything else. If the
00491       // initializers use previously-initialized thread_local vars, that's
00492       // probably supposed to be OK, but the standard doesn't say.
00493       Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
00494       llvm::BasicBlock *InitBlock = createBasicBlock("init");
00495       ExitBlock = createBasicBlock("exit");
00496       Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
00497       EmitBlock(InitBlock);
00498     }
00499 
00500     RunCleanupsScope Scope(*this);
00501 
00502     // When building in Objective-C++ ARC mode, create an autorelease pool
00503     // around the global initializers.
00504     if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
00505       llvm::Value *token = EmitObjCAutoreleasePoolPush();
00506       EmitObjCAutoreleasePoolCleanup(token);
00507     }
00508 
00509     for (unsigned i = 0, e = Decls.size(); i != e; ++i)
00510       if (Decls[i])
00511         EmitRuntimeCall(Decls[i]);
00512 
00513     Scope.ForceCleanup();
00514 
00515     if (ExitBlock) {
00516       Builder.CreateBr(ExitBlock);
00517       EmitBlock(ExitBlock);
00518     }
00519   }
00520 
00521   FinishFunction();
00522 }
00523 
00524 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
00525                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
00526                                                 &DtorsAndObjects) {
00527   {
00528     ArtificialLocation AL(*this, Builder);
00529     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
00530                   getTypes().arrangeNullaryFunction(), FunctionArgList());
00531     // Emit an artificial location for this function.
00532     AL.Emit();
00533 
00534     // Emit the dtors, in reverse order from construction.
00535     for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
00536       llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
00537       llvm::CallInst *CI = Builder.CreateCall(Callee,
00538                                           DtorsAndObjects[e - i - 1].second);
00539       // Make sure the call and the callee agree on calling convention.
00540       if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
00541         CI->setCallingConv(F->getCallingConv());
00542     }
00543   }
00544 
00545   FinishFunction();
00546 }
00547 
00548 /// generateDestroyHelper - Generates a helper function which, when
00549 /// invoked, destroys the given object.
00550 llvm::Function *CodeGenFunction::generateDestroyHelper(
00551     llvm::Constant *addr, QualType type, Destroyer *destroyer,
00552     bool useEHCleanupForArray, const VarDecl *VD) {
00553   FunctionArgList args;
00554   ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
00555                         getContext().VoidPtrTy);
00556   args.push_back(&dst);
00557 
00558   const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
00559       getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
00560   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
00561   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
00562       FTy, "__cxx_global_array_dtor", VD->getLocation());
00563 
00564   StartFunction(VD, getContext().VoidTy, fn, FI, args);
00565 
00566   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
00567   
00568   FinishFunction();
00569   
00570   return fn;
00571 }