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 "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenMPRuntime.h"
18 #include "clang/Frontend/CodeGenOptions.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/Support/Path.h"
22 
23 using namespace clang;
24 using namespace CodeGen;
25 
26 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
27                          ConstantAddress DeclPtr) {
28   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
29   assert(!D.getType()->isReferenceType() &&
30          "Should not call EmitDeclInit on a reference!");
31 
32   QualType type = D.getType();
33   LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
34 
35   const Expr *Init = D.getInit();
36   switch (CGF.getEvaluationKind(type)) {
37   case TEK_Scalar: {
38     CodeGenModule &CGM = CGF.CGM;
39     if (lv.isObjCStrong())
40       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
41                                                 DeclPtr, D.getTLSKind());
42     else if (lv.isObjCWeak())
43       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
44                                               DeclPtr);
45     else
46       CGF.EmitScalarInit(Init, &D, lv, false);
47     return;
48   }
49   case TEK_Complex:
50     CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
51     return;
52   case TEK_Aggregate:
53     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
54                                           AggValueSlot::DoesNotNeedGCBarriers,
55                                                   AggValueSlot::IsNotAliased));
56     return;
57   }
58   llvm_unreachable("bad evaluation kind");
59 }
60 
61 /// Emit code to cause the destruction of the given variable with
62 /// static storage duration.
63 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
64                             ConstantAddress addr) {
65   CodeGenModule &CGM = CGF.CGM;
66 
67   // FIXME:  __attribute__((cleanup)) ?
68 
69   QualType type = D.getType();
70   QualType::DestructionKind dtorKind = type.isDestructedType();
71 
72   switch (dtorKind) {
73   case QualType::DK_none:
74     return;
75 
76   case QualType::DK_cxx_destructor:
77     break;
78 
79   case QualType::DK_objc_strong_lifetime:
80   case QualType::DK_objc_weak_lifetime:
81     // We don't care about releasing objects during process teardown.
82     assert(!D.getTLSKind() && "should have rejected this");
83     return;
84   }
85 
86   llvm::Constant *function;
87   llvm::Constant *argument;
88 
89   // Special-case non-array C++ destructors, if they have the right signature.
90   // Under some ABIs, destructors return this instead of void, and cannot be
91   // passed directly to __cxa_atexit if the target does not allow this mismatch.
92   const CXXRecordDecl *Record = type->getAsCXXRecordDecl();
93   bool CanRegisterDestructor =
94       Record && (!CGM.getCXXABI().HasThisReturn(
95                      GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
96                  CGM.getCXXABI().canCallMismatchedFunctionType());
97   // If __cxa_atexit is disabled via a flag, a different helper function is
98   // generated elsewhere which uses atexit instead, and it takes the destructor
99   // directly.
100   bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
101   if (Record && (CanRegisterDestructor || UsingExternalHelper)) {
102     assert(!Record->hasTrivialDestructor());
103     CXXDestructorDecl *dtor = Record->getDestructor();
104 
105     function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
106     argument = llvm::ConstantExpr::getBitCast(
107         addr.getPointer(), CGF.getTypes().ConvertType(type)->getPointerTo());
108 
109   // Otherwise, the standard logic requires a helper function.
110   } else {
111     function = CodeGenFunction(CGM)
112         .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
113                                CGF.needsEHCleanup(dtorKind), &D);
114     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
115   }
116 
117   CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
118 }
119 
120 /// Emit code to cause the variable at the given address to be considered as
121 /// constant from this point onwards.
122 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
123                               llvm::Constant *Addr) {
124   // Do not emit the intrinsic if we're not optimizing.
125   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
126     return;
127 
128   // Grab the llvm.invariant.start intrinsic.
129   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
130   // Overloaded address space type.
131   llvm::Type *ObjectPtr[1] = {CGF.Int8PtrTy};
132   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID, ObjectPtr);
133 
134   // Emit a call with the size in bytes of the object.
135   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
136   uint64_t Width = WidthChars.getQuantity();
137   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
138                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
139   CGF.Builder.CreateCall(InvariantStart, Args);
140 }
141 
142 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
143                                                llvm::Constant *DeclPtr,
144                                                bool PerformInit) {
145 
146   const Expr *Init = D.getInit();
147   QualType T = D.getType();
148 
149   // The address space of a static local variable (DeclPtr) may be different
150   // from the address space of the "this" argument of the constructor. In that
151   // case, we need an addrspacecast before calling the constructor.
152   //
153   // struct StructWithCtor {
154   //   __device__ StructWithCtor() {...}
155   // };
156   // __device__ void foo() {
157   //   __shared__ StructWithCtor s;
158   //   ...
159   // }
160   //
161   // For example, in the above CUDA code, the static local variable s has a
162   // "shared" address space qualifier, but the constructor of StructWithCtor
163   // expects "this" in the "generic" address space.
164   unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
165   unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
166   if (ActualAddrSpace != ExpectedAddrSpace) {
167     llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
168     llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
169     DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
170   }
171 
172   ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
173 
174   if (!T->isReferenceType()) {
175     if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>())
176       (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
177           &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
178           PerformInit, this);
179     if (PerformInit)
180       EmitDeclInit(*this, D, DeclAddr);
181     if (CGM.isTypeConstant(D.getType(), true))
182       EmitDeclInvariant(*this, D, DeclPtr);
183     else
184       EmitDeclDestroy(*this, D, DeclAddr);
185     return;
186   }
187 
188   assert(PerformInit && "cannot have constant initializer which needs "
189          "destruction for reference");
190   RValue RV = EmitReferenceBindingToExpr(Init);
191   EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
192 }
193 
194 /// Create a stub function, suitable for being passed to atexit,
195 /// which passes the given address to the given destructor function.
196 llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
197                                                   llvm::Constant *dtor,
198                                                   llvm::Constant *addr) {
199   // Get the destructor function type, void(*)(void).
200   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
201   SmallString<256> FnName;
202   {
203     llvm::raw_svector_ostream Out(FnName);
204     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
205   }
206 
207   const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
208   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
209                                                               FI,
210                                                               VD.getLocation());
211 
212   CodeGenFunction CGF(CGM);
213 
214   CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn, FI, FunctionArgList());
215 
216   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
217 
218  // Make sure the call and the callee agree on calling convention.
219   if (llvm::Function *dtorFn =
220         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
221     call->setCallingConv(dtorFn->getCallingConv());
222 
223   CGF.FinishFunction();
224 
225   return fn;
226 }
227 
228 /// Register a global destructor using the C atexit runtime function.
229 void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
230                                                    llvm::Constant *dtor,
231                                                    llvm::Constant *addr) {
232   // Create a function which calls the destructor.
233   llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
234 
235   // extern "C" int atexit(void (*f)(void));
236   llvm::FunctionType *atexitTy =
237     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
238 
239   llvm::Constant *atexit =
240     CGM.CreateRuntimeFunction(atexitTy, "atexit");
241   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
242     atexitFn->setDoesNotThrow();
243 
244   EmitNounwindRuntimeCall(atexit, dtorStub);
245 }
246 
247 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
248                                          llvm::GlobalVariable *DeclPtr,
249                                          bool PerformInit) {
250   // If we've been asked to forbid guard variables, emit an error now.
251   // This diagnostic is hard-coded for Darwin's use case;  we can find
252   // better phrasing if someone else needs it.
253   if (CGM.getCodeGenOpts().ForbidGuardVariables)
254     CGM.Error(D.getLocation(),
255               "this initialization requires a guard variable, which "
256               "the kernel does not support");
257 
258   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
259 }
260 
261 llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
262     llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
263     SourceLocation Loc, bool TLS) {
264   llvm::Function *Fn =
265     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
266                            Name, &getModule());
267   if (!getLangOpts().AppleKext && !TLS) {
268     // Set the section if needed.
269     if (const char *Section = getTarget().getStaticInitSectionSpecifier())
270       Fn->setSection(Section);
271   }
272 
273   SetInternalFunctionAttributes(nullptr, Fn, FI);
274 
275   Fn->setCallingConv(getRuntimeCC());
276 
277   if (!getLangOpts().Exceptions)
278     Fn->setDoesNotThrow();
279 
280   if (!isInSanitizerBlacklist(Fn, Loc)) {
281     if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
282                                         SanitizerKind::KernelAddress))
283       Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
284     if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
285       Fn->addFnAttr(llvm::Attribute::SanitizeThread);
286     if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
287       Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
288     if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack))
289       Fn->addFnAttr(llvm::Attribute::SafeStack);
290   }
291 
292   return Fn;
293 }
294 
295 /// Create a global pointer to a function that will initialize a global
296 /// variable.  The user has requested that this pointer be emitted in a specific
297 /// section.
298 void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
299                                           llvm::GlobalVariable *GV,
300                                           llvm::Function *InitFunc,
301                                           InitSegAttr *ISA) {
302   llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
303       TheModule, InitFunc->getType(), /*isConstant=*/true,
304       llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
305   PtrArray->setSection(ISA->getSection());
306   addUsedGlobal(PtrArray);
307 
308   // If the GV is already in a comdat group, then we have to join it.
309   if (llvm::Comdat *C = GV->getComdat())
310     PtrArray->setComdat(C);
311 }
312 
313 void
314 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
315                                             llvm::GlobalVariable *Addr,
316                                             bool PerformInit) {
317 
318   // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
319   // __constant__ and __shared__ variables defined in namespace scope,
320   // that are of class type, cannot have a non-empty constructor. All
321   // the checks have been done in Sema by now. Whatever initializers
322   // are allowed are empty and we just need to ignore them here.
323   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
324       (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
325        D->hasAttr<CUDASharedAttr>()))
326     return;
327 
328   // Check if we've already initialized this decl.
329   auto I = DelayedCXXInitPosition.find(D);
330   if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
331     return;
332 
333   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
334   SmallString<256> FnName;
335   {
336     llvm::raw_svector_ostream Out(FnName);
337     getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
338   }
339 
340   // Create a variable initialization function.
341   llvm::Function *Fn =
342       CreateGlobalInitOrDestructFunction(FTy, FnName.str(),
343                                          getTypes().arrangeNullaryFunction(),
344                                          D->getLocation());
345 
346   auto *ISA = D->getAttr<InitSegAttr>();
347   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
348                                                           PerformInit);
349 
350   llvm::GlobalVariable *COMDATKey =
351       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
352 
353   if (D->getTLSKind()) {
354     // FIXME: Should we support init_priority for thread_local?
355     // FIXME: Ideally, initialization of instantiated thread_local static data
356     // members of class templates should not trigger initialization of other
357     // entities in the TU.
358     // FIXME: We only need to register one __cxa_thread_atexit function for the
359     // entire TU.
360     CXXThreadLocalInits.push_back(Fn);
361     CXXThreadLocalInitVars.push_back(D);
362   } else if (PerformInit && ISA) {
363     EmitPointerToInitFunc(D, Addr, Fn, ISA);
364   } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
365     OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
366     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
367   } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
368     // C++ [basic.start.init]p2:
369     //   Definitions of explicitly specialized class template static data
370     //   members have ordered initialization. Other class template static data
371     //   members (i.e., implicitly or explicitly instantiated specializations)
372     //   have unordered initialization.
373     //
374     // As a consequence, we can put them into their own llvm.global_ctors entry.
375     //
376     // If the global is externally visible, put the initializer into a COMDAT
377     // group with the global being initialized.  On most platforms, this is a
378     // minor startup time optimization.  In the MS C++ ABI, there are no guard
379     // variables, so this COMDAT key is required for correctness.
380     AddGlobalCtor(Fn, 65535, COMDATKey);
381   } else if (D->hasAttr<SelectAnyAttr>()) {
382     // SelectAny globals will be comdat-folded. Put the initializer into a
383     // COMDAT group associated with the global, so the initializers get folded
384     // too.
385     AddGlobalCtor(Fn, 65535, COMDATKey);
386   } else {
387     I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
388     if (I == DelayedCXXInitPosition.end()) {
389       CXXGlobalInits.push_back(Fn);
390     } else if (I->second != ~0U) {
391       assert(I->second < CXXGlobalInits.size() &&
392              CXXGlobalInits[I->second] == nullptr);
393       CXXGlobalInits[I->second] = Fn;
394     }
395   }
396 
397   // Remember that we already emitted the initializer for this global.
398   DelayedCXXInitPosition[D] = ~0U;
399 }
400 
401 void CodeGenModule::EmitCXXThreadLocalInitFunc() {
402   getCXXABI().EmitThreadLocalInitFuncs(
403       *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
404 
405   CXXThreadLocalInits.clear();
406   CXXThreadLocalInitVars.clear();
407   CXXThreadLocals.clear();
408 }
409 
410 void
411 CodeGenModule::EmitCXXGlobalInitFunc() {
412   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
413     CXXGlobalInits.pop_back();
414 
415   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
416     return;
417 
418   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
419   const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
420 
421   // Create our global initialization function.
422   if (!PrioritizedCXXGlobalInits.empty()) {
423     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
424     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
425                          PrioritizedCXXGlobalInits.end());
426     // Iterate over "chunks" of ctors with same priority and emit each chunk
427     // into separate function. Note - everything is sorted first by priority,
428     // second - by lex order, so we emit ctor functions in proper order.
429     for (SmallVectorImpl<GlobalInitData >::iterator
430            I = PrioritizedCXXGlobalInits.begin(),
431            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
432       SmallVectorImpl<GlobalInitData >::iterator
433         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
434 
435       LocalCXXGlobalInits.clear();
436       unsigned Priority = I->first.priority;
437       // Compute the function suffix from priority. Prepend with zeroes to make
438       // sure the function names are also ordered as priorities.
439       std::string PrioritySuffix = llvm::utostr(Priority);
440       // Priority is always <= 65535 (enforced by sema).
441       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
442       llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
443           FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
444 
445       for (; I < PrioE; ++I)
446         LocalCXXGlobalInits.push_back(I->second);
447 
448       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
449       AddGlobalCtor(Fn, Priority);
450     }
451     PrioritizedCXXGlobalInits.clear();
452   }
453 
454   SmallString<128> FileName;
455   SourceManager &SM = Context.getSourceManager();
456   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
457     // Include the filename in the symbol name. Including "sub_" matches gcc and
458     // makes sure these symbols appear lexicographically behind the symbols with
459     // priority emitted above.
460     FileName = llvm::sys::path::filename(MainFile->getName());
461   } else {
462     FileName = "<null>";
463   }
464 
465   for (size_t i = 0; i < FileName.size(); ++i) {
466     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
467     // to be the set of C preprocessing numbers.
468     if (!isPreprocessingNumberBody(FileName[i]))
469       FileName[i] = '_';
470   }
471 
472   llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
473       FTy, llvm::Twine("_GLOBAL__sub_I_", FileName), FI);
474 
475   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
476   AddGlobalCtor(Fn);
477 
478   CXXGlobalInits.clear();
479 }
480 
481 void CodeGenModule::EmitCXXGlobalDtorFunc() {
482   if (CXXGlobalDtors.empty())
483     return;
484 
485   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
486 
487   // Create our global destructor function.
488   const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
489   llvm::Function *Fn =
490       CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a", FI);
491 
492   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
493   AddGlobalDtor(Fn);
494 }
495 
496 /// Emit the code necessary to initialize the given global variable.
497 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
498                                                        const VarDecl *D,
499                                                  llvm::GlobalVariable *Addr,
500                                                        bool PerformInit) {
501   // Check if we need to emit debug info for variable initializer.
502   if (D->hasAttr<NoDebugAttr>())
503     DebugInfo = nullptr; // disable debug info indefinitely for this function
504 
505   CurEHLocation = D->getLocStart();
506 
507   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
508                 getTypes().arrangeNullaryFunction(),
509                 FunctionArgList(), D->getLocation(),
510                 D->getInit()->getExprLoc());
511 
512   // Use guarded initialization if the global variable is weak. This
513   // occurs for, e.g., instantiated static data members and
514   // definitions explicitly marked weak.
515   if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
516     EmitCXXGuardedInit(*D, Addr, PerformInit);
517   } else {
518     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
519   }
520 
521   FinishFunction();
522 }
523 
524 void
525 CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
526                                            ArrayRef<llvm::Function *> Decls,
527                                            Address Guard) {
528   {
529     auto NL = ApplyDebugLocation::CreateEmpty(*this);
530     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
531                   getTypes().arrangeNullaryFunction(), FunctionArgList());
532     // Emit an artificial location for this function.
533     auto AL = ApplyDebugLocation::CreateArtificial(*this);
534 
535     llvm::BasicBlock *ExitBlock = nullptr;
536     if (Guard.isValid()) {
537       // If we have a guard variable, check whether we've already performed
538       // these initializations. This happens for TLS initialization functions.
539       llvm::Value *GuardVal = Builder.CreateLoad(Guard);
540       llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
541                                                  "guard.uninitialized");
542       llvm::BasicBlock *InitBlock = createBasicBlock("init");
543       ExitBlock = createBasicBlock("exit");
544       Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
545       EmitBlock(InitBlock);
546       // Mark as initialized before initializing anything else. If the
547       // initializers use previously-initialized thread_local vars, that's
548       // probably supposed to be OK, but the standard doesn't say.
549       Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
550     }
551 
552     RunCleanupsScope Scope(*this);
553 
554     // When building in Objective-C++ ARC mode, create an autorelease pool
555     // around the global initializers.
556     if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
557       llvm::Value *token = EmitObjCAutoreleasePoolPush();
558       EmitObjCAutoreleasePoolCleanup(token);
559     }
560 
561     for (unsigned i = 0, e = Decls.size(); i != e; ++i)
562       if (Decls[i])
563         EmitRuntimeCall(Decls[i]);
564 
565     Scope.ForceCleanup();
566 
567     if (ExitBlock) {
568       Builder.CreateBr(ExitBlock);
569       EmitBlock(ExitBlock);
570     }
571   }
572 
573   FinishFunction();
574 }
575 
576 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
577                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
578                                                 &DtorsAndObjects) {
579   {
580     auto NL = ApplyDebugLocation::CreateEmpty(*this);
581     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
582                   getTypes().arrangeNullaryFunction(), FunctionArgList());
583     // Emit an artificial location for this function.
584     auto AL = ApplyDebugLocation::CreateArtificial(*this);
585 
586     // Emit the dtors, in reverse order from construction.
587     for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
588       llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
589       llvm::CallInst *CI = Builder.CreateCall(Callee,
590                                           DtorsAndObjects[e - i - 1].second);
591       // Make sure the call and the callee agree on calling convention.
592       if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
593         CI->setCallingConv(F->getCallingConv());
594     }
595   }
596 
597   FinishFunction();
598 }
599 
600 /// generateDestroyHelper - Generates a helper function which, when
601 /// invoked, destroys the given object.  The address of the object
602 /// should be in global memory.
603 llvm::Function *CodeGenFunction::generateDestroyHelper(
604     Address addr, QualType type, Destroyer *destroyer,
605     bool useEHCleanupForArray, const VarDecl *VD) {
606   FunctionArgList args;
607   ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
608                         getContext().VoidPtrTy);
609   args.push_back(&dst);
610 
611   const CGFunctionInfo &FI =
612     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
613   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
614   llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
615       FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
616 
617   CurEHLocation = VD->getLocStart();
618 
619   StartFunction(VD, getContext().VoidTy, fn, FI, args);
620 
621   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
622 
623   FinishFunction();
624 
625   return fn;
626 }
627