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