CGDeclCXX.cpp 37 KB

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