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