CGDeclCXX.cpp 23 KB

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