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