CGDecl.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. //===--- CGDecl.cpp - Emit LLVM Code for 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 to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGBlocks.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCleanup.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenCLRuntime.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclOpenMP.h"
  26. #include "clang/Basic/SourceManager.h"
  27. #include "clang/Basic/TargetInfo.h"
  28. #include "clang/CodeGen/CGFunctionInfo.h"
  29. #include "clang/Frontend/CodeGenOptions.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/Type.h"
  34. using namespace clang;
  35. using namespace CodeGen;
  36. void CodeGenFunction::EmitDecl(const Decl &D) {
  37. switch (D.getKind()) {
  38. case Decl::BuiltinTemplate:
  39. case Decl::TranslationUnit:
  40. case Decl::ExternCContext:
  41. case Decl::Namespace:
  42. case Decl::UnresolvedUsingTypename:
  43. case Decl::ClassTemplateSpecialization:
  44. case Decl::ClassTemplatePartialSpecialization:
  45. case Decl::VarTemplateSpecialization:
  46. case Decl::VarTemplatePartialSpecialization:
  47. case Decl::TemplateTypeParm:
  48. case Decl::UnresolvedUsingValue:
  49. case Decl::NonTypeTemplateParm:
  50. case Decl::CXXDeductionGuide:
  51. case Decl::CXXMethod:
  52. case Decl::CXXConstructor:
  53. case Decl::CXXDestructor:
  54. case Decl::CXXConversion:
  55. case Decl::Field:
  56. case Decl::MSProperty:
  57. case Decl::IndirectField:
  58. case Decl::ObjCIvar:
  59. case Decl::ObjCAtDefsField:
  60. case Decl::ParmVar:
  61. case Decl::ImplicitParam:
  62. case Decl::ClassTemplate:
  63. case Decl::VarTemplate:
  64. case Decl::FunctionTemplate:
  65. case Decl::TypeAliasTemplate:
  66. case Decl::TemplateTemplateParm:
  67. case Decl::ObjCMethod:
  68. case Decl::ObjCCategory:
  69. case Decl::ObjCProtocol:
  70. case Decl::ObjCInterface:
  71. case Decl::ObjCCategoryImpl:
  72. case Decl::ObjCImplementation:
  73. case Decl::ObjCProperty:
  74. case Decl::ObjCCompatibleAlias:
  75. case Decl::PragmaComment:
  76. case Decl::PragmaDetectMismatch:
  77. case Decl::AccessSpec:
  78. case Decl::LinkageSpec:
  79. case Decl::Export:
  80. case Decl::ObjCPropertyImpl:
  81. case Decl::FileScopeAsm:
  82. case Decl::Friend:
  83. case Decl::FriendTemplate:
  84. case Decl::Block:
  85. case Decl::Captured:
  86. case Decl::ClassScopeFunctionSpecialization:
  87. case Decl::UsingShadow:
  88. case Decl::ConstructorUsingShadow:
  89. case Decl::ObjCTypeParam:
  90. case Decl::Binding:
  91. llvm_unreachable("Declaration should not be in declstmts!");
  92. case Decl::Function: // void X();
  93. case Decl::Record: // struct/union/class X;
  94. case Decl::Enum: // enum X;
  95. case Decl::EnumConstant: // enum ? { X = ? }
  96. case Decl::CXXRecord: // struct/union/class X; [C++]
  97. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  98. case Decl::Label: // __label__ x;
  99. case Decl::Import:
  100. case Decl::OMPThreadPrivate:
  101. case Decl::OMPCapturedExpr:
  102. case Decl::Empty:
  103. // None of these decls require codegen support.
  104. return;
  105. case Decl::NamespaceAlias:
  106. if (CGDebugInfo *DI = getDebugInfo())
  107. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  108. return;
  109. case Decl::Using: // using X; [C++]
  110. if (CGDebugInfo *DI = getDebugInfo())
  111. DI->EmitUsingDecl(cast<UsingDecl>(D));
  112. return;
  113. case Decl::UsingPack:
  114. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  115. EmitDecl(*Using);
  116. return;
  117. case Decl::UsingDirective: // using namespace X; [C++]
  118. if (CGDebugInfo *DI = getDebugInfo())
  119. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  120. return;
  121. case Decl::Var:
  122. case Decl::Decomposition: {
  123. const VarDecl &VD = cast<VarDecl>(D);
  124. assert(VD.isLocalVarDecl() &&
  125. "Should not see file-scope variables inside a function!");
  126. EmitVarDecl(VD);
  127. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  128. for (auto *B : DD->bindings())
  129. if (auto *HD = B->getHoldingVar())
  130. EmitVarDecl(*HD);
  131. return;
  132. }
  133. case Decl::OMPDeclareReduction:
  134. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  135. case Decl::Typedef: // typedef int X;
  136. case Decl::TypeAlias: { // using X = int; [C++0x]
  137. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  138. QualType Ty = TD.getUnderlyingType();
  139. if (Ty->isVariablyModifiedType())
  140. EmitVariablyModifiedType(Ty);
  141. }
  142. }
  143. }
  144. /// EmitVarDecl - This method handles emission of any variable declaration
  145. /// inside a function, including static vars etc.
  146. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  147. if (D.isStaticLocal()) {
  148. llvm::GlobalValue::LinkageTypes Linkage =
  149. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  150. // FIXME: We need to force the emission/use of a guard variable for
  151. // some variables even if we can constant-evaluate them because
  152. // we can't guarantee every translation unit will constant-evaluate them.
  153. return EmitStaticVarDecl(D, Linkage);
  154. }
  155. if (D.hasExternalStorage())
  156. // Don't emit it now, allow it to be emitted lazily on its first use.
  157. return;
  158. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  159. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  160. assert(D.hasLocalStorage());
  161. return EmitAutoVarDecl(D);
  162. }
  163. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  164. if (CGM.getLangOpts().CPlusPlus)
  165. return CGM.getMangledName(&D).str();
  166. // If this isn't C++, we don't need a mangled name, just a pretty one.
  167. assert(!D.isExternallyVisible() && "name shouldn't matter");
  168. std::string ContextName;
  169. const DeclContext *DC = D.getDeclContext();
  170. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  171. DC = cast<DeclContext>(CD->getNonClosureContext());
  172. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  173. ContextName = CGM.getMangledName(FD);
  174. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  175. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  176. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  177. ContextName = OMD->getSelector().getAsString();
  178. else
  179. llvm_unreachable("Unknown context for static var decl");
  180. ContextName += "." + D.getNameAsString();
  181. return ContextName;
  182. }
  183. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  184. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  185. // In general, we don't always emit static var decls once before we reference
  186. // them. It is possible to reference them before emitting the function that
  187. // contains them, and it is possible to emit the containing function multiple
  188. // times.
  189. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  190. return ExistingGV;
  191. QualType Ty = D.getType();
  192. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  193. // Use the label if the variable is renamed with the asm-label extension.
  194. std::string Name;
  195. if (D.hasAttr<AsmLabelAttr>())
  196. Name = getMangledName(&D);
  197. else
  198. Name = getStaticDeclName(*this, D);
  199. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  200. unsigned AddrSpace =
  201. GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
  202. // Local address space cannot have an initializer.
  203. llvm::Constant *Init = nullptr;
  204. if (Ty.getAddressSpace() != LangAS::opencl_local)
  205. Init = EmitNullConstant(Ty);
  206. else
  207. Init = llvm::UndefValue::get(LTy);
  208. llvm::GlobalVariable *GV =
  209. new llvm::GlobalVariable(getModule(), LTy,
  210. Ty.isConstant(getContext()), Linkage,
  211. Init, Name, nullptr,
  212. llvm::GlobalVariable::NotThreadLocal,
  213. AddrSpace);
  214. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  215. setGlobalVisibility(GV, &D);
  216. if (supportsCOMDAT() && GV->isWeakForLinker())
  217. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  218. if (D.getTLSKind())
  219. setTLSMode(GV, D);
  220. if (D.isExternallyVisible()) {
  221. if (D.hasAttr<DLLImportAttr>())
  222. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  223. else if (D.hasAttr<DLLExportAttr>())
  224. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  225. }
  226. // Make sure the result is of the correct type.
  227. unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
  228. llvm::Constant *Addr = GV;
  229. if (AddrSpace != ExpectedAddrSpace) {
  230. llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
  231. Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
  232. }
  233. setStaticLocalDeclAddress(&D, Addr);
  234. // Ensure that the static local gets initialized by making sure the parent
  235. // function gets emitted eventually.
  236. const Decl *DC = cast<Decl>(D.getDeclContext());
  237. // We can't name blocks or captured statements directly, so try to emit their
  238. // parents.
  239. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  240. DC = DC->getNonClosureContext();
  241. // FIXME: Ensure that global blocks get emitted.
  242. if (!DC)
  243. return Addr;
  244. }
  245. GlobalDecl GD;
  246. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  247. GD = GlobalDecl(CD, Ctor_Base);
  248. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  249. GD = GlobalDecl(DD, Dtor_Base);
  250. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  251. GD = GlobalDecl(FD);
  252. else {
  253. // Don't do anything for Obj-C method decls or global closures. We should
  254. // never defer them.
  255. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  256. }
  257. if (GD.getDecl())
  258. (void)GetAddrOfGlobal(GD);
  259. return Addr;
  260. }
  261. /// hasNontrivialDestruction - Determine whether a type's destruction is
  262. /// non-trivial. If so, and the variable uses static initialization, we must
  263. /// register its destructor to run on exit.
  264. static bool hasNontrivialDestruction(QualType T) {
  265. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  266. return RD && !RD->hasTrivialDestructor();
  267. }
  268. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  269. /// global variable that has already been created for it. If the initializer
  270. /// has a different type than GV does, this may free GV and return a different
  271. /// one. Otherwise it just returns GV.
  272. llvm::GlobalVariable *
  273. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  274. llvm::GlobalVariable *GV) {
  275. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  276. // If constant emission failed, then this should be a C++ static
  277. // initializer.
  278. if (!Init) {
  279. if (!getLangOpts().CPlusPlus)
  280. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  281. else if (HaveInsertPoint()) {
  282. // Since we have a static initializer, this global variable can't
  283. // be constant.
  284. GV->setConstant(false);
  285. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  286. }
  287. return GV;
  288. }
  289. // The initializer may differ in type from the global. Rewrite
  290. // the global to match the initializer. (We have to do this
  291. // because some types, like unions, can't be completely represented
  292. // in the LLVM type system.)
  293. if (GV->getType()->getElementType() != Init->getType()) {
  294. llvm::GlobalVariable *OldGV = GV;
  295. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  296. OldGV->isConstant(),
  297. OldGV->getLinkage(), Init, "",
  298. /*InsertBefore*/ OldGV,
  299. OldGV->getThreadLocalMode(),
  300. CGM.getContext().getTargetAddressSpace(D.getType()));
  301. GV->setVisibility(OldGV->getVisibility());
  302. GV->setComdat(OldGV->getComdat());
  303. // Steal the name of the old global
  304. GV->takeName(OldGV);
  305. // Replace all uses of the old global with the new global
  306. llvm::Constant *NewPtrForOldDecl =
  307. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  308. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  309. // Erase the old global, since it is no longer used.
  310. OldGV->eraseFromParent();
  311. }
  312. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  313. GV->setInitializer(Init);
  314. if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
  315. // We have a constant initializer, but a nontrivial destructor. We still
  316. // need to perform a guarded "initialization" in order to register the
  317. // destructor.
  318. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  319. }
  320. return GV;
  321. }
  322. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  323. llvm::GlobalValue::LinkageTypes Linkage) {
  324. // Check to see if we already have a global variable for this
  325. // declaration. This can happen when double-emitting function
  326. // bodies, e.g. with complete and base constructors.
  327. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  328. CharUnits alignment = getContext().getDeclAlign(&D);
  329. // Store into LocalDeclMap before generating initializer to handle
  330. // circular references.
  331. setAddrOfLocalVar(&D, Address(addr, alignment));
  332. // We can't have a VLA here, but we can have a pointer to a VLA,
  333. // even though that doesn't really make any sense.
  334. // Make sure to evaluate VLA bounds now so that we have them for later.
  335. if (D.getType()->isVariablyModifiedType())
  336. EmitVariablyModifiedType(D.getType());
  337. // Save the type in case adding the initializer forces a type change.
  338. llvm::Type *expectedType = addr->getType();
  339. llvm::GlobalVariable *var =
  340. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  341. // CUDA's local and local static __shared__ variables should not
  342. // have any non-empty initializers. This is ensured by Sema.
  343. // Whatever initializer such variable may have when it gets here is
  344. // a no-op and should not be emitted.
  345. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  346. D.hasAttr<CUDASharedAttr>();
  347. // If this value has an initializer, emit it.
  348. if (D.getInit() && !isCudaSharedVar)
  349. var = AddInitializerToStaticVarDecl(D, var);
  350. var->setAlignment(alignment.getQuantity());
  351. if (D.hasAttr<AnnotateAttr>())
  352. CGM.AddGlobalAnnotations(&D, var);
  353. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  354. var->setSection(SA->getName());
  355. if (D.hasAttr<UsedAttr>())
  356. CGM.addUsedGlobal(var);
  357. // We may have to cast the constant because of the initializer
  358. // mismatch above.
  359. //
  360. // FIXME: It is really dangerous to store this in the map; if anyone
  361. // RAUW's the GV uses of this constant will be invalid.
  362. llvm::Constant *castedAddr =
  363. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  364. if (var != castedAddr)
  365. LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
  366. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  367. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  368. // Emit global variable debug descriptor for static vars.
  369. CGDebugInfo *DI = getDebugInfo();
  370. if (DI &&
  371. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  372. DI->setLocation(D.getLocation());
  373. DI->EmitGlobalVariable(var, &D);
  374. }
  375. }
  376. namespace {
  377. struct DestroyObject final : EHScopeStack::Cleanup {
  378. DestroyObject(Address addr, QualType type,
  379. CodeGenFunction::Destroyer *destroyer,
  380. bool useEHCleanupForArray)
  381. : addr(addr), type(type), destroyer(destroyer),
  382. useEHCleanupForArray(useEHCleanupForArray) {}
  383. Address addr;
  384. QualType type;
  385. CodeGenFunction::Destroyer *destroyer;
  386. bool useEHCleanupForArray;
  387. void Emit(CodeGenFunction &CGF, Flags flags) override {
  388. // Don't use an EH cleanup recursively from an EH cleanup.
  389. bool useEHCleanupForArray =
  390. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  391. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  392. }
  393. };
  394. struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
  395. DestroyNRVOVariable(Address addr,
  396. const CXXDestructorDecl *Dtor,
  397. llvm::Value *NRVOFlag)
  398. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  399. const CXXDestructorDecl *Dtor;
  400. llvm::Value *NRVOFlag;
  401. Address Loc;
  402. void Emit(CodeGenFunction &CGF, Flags flags) override {
  403. // Along the exceptions path we always execute the dtor.
  404. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  405. llvm::BasicBlock *SkipDtorBB = nullptr;
  406. if (NRVO) {
  407. // If we exited via NRVO, we skip the destructor call.
  408. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  409. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  410. llvm::Value *DidNRVO =
  411. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  412. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  413. CGF.EmitBlock(RunDtorBB);
  414. }
  415. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  416. /*ForVirtualBase=*/false,
  417. /*Delegating=*/false,
  418. Loc);
  419. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  420. }
  421. };
  422. struct CallStackRestore final : EHScopeStack::Cleanup {
  423. Address Stack;
  424. CallStackRestore(Address Stack) : Stack(Stack) {}
  425. void Emit(CodeGenFunction &CGF, Flags flags) override {
  426. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  427. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  428. CGF.Builder.CreateCall(F, V);
  429. }
  430. };
  431. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  432. const VarDecl &Var;
  433. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  434. void Emit(CodeGenFunction &CGF, Flags flags) override {
  435. // Compute the address of the local variable, in case it's a
  436. // byref or something.
  437. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  438. Var.getType(), VK_LValue, SourceLocation());
  439. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  440. SourceLocation());
  441. CGF.EmitExtendGCLifetime(value);
  442. }
  443. };
  444. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  445. llvm::Constant *CleanupFn;
  446. const CGFunctionInfo &FnInfo;
  447. const VarDecl &Var;
  448. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  449. const VarDecl *Var)
  450. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  451. void Emit(CodeGenFunction &CGF, Flags flags) override {
  452. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  453. Var.getType(), VK_LValue, SourceLocation());
  454. // Compute the address of the local variable, in case it's a byref
  455. // or something.
  456. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
  457. // In some cases, the type of the function argument will be different from
  458. // the type of the pointer. An example of this is
  459. // void f(void* arg);
  460. // __attribute__((cleanup(f))) void *g;
  461. //
  462. // To fix this we insert a bitcast here.
  463. QualType ArgTy = FnInfo.arg_begin()->type;
  464. llvm::Value *Arg =
  465. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  466. CallArgList Args;
  467. Args.add(RValue::get(Arg),
  468. CGF.getContext().getPointerType(Var.getType()));
  469. auto Callee = CGCallee::forDirect(CleanupFn);
  470. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  471. }
  472. };
  473. } // end anonymous namespace
  474. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  475. /// variable with lifetime.
  476. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  477. Address addr,
  478. Qualifiers::ObjCLifetime lifetime) {
  479. switch (lifetime) {
  480. case Qualifiers::OCL_None:
  481. llvm_unreachable("present but none");
  482. case Qualifiers::OCL_ExplicitNone:
  483. // nothing to do
  484. break;
  485. case Qualifiers::OCL_Strong: {
  486. CodeGenFunction::Destroyer *destroyer =
  487. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  488. ? CodeGenFunction::destroyARCStrongPrecise
  489. : CodeGenFunction::destroyARCStrongImprecise);
  490. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  491. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  492. cleanupKind & EHCleanup);
  493. break;
  494. }
  495. case Qualifiers::OCL_Autoreleasing:
  496. // nothing to do
  497. break;
  498. case Qualifiers::OCL_Weak:
  499. // __weak objects always get EH cleanups; otherwise, exceptions
  500. // could cause really nasty crashes instead of mere leaks.
  501. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  502. CodeGenFunction::destroyARCWeak,
  503. /*useEHCleanup*/ true);
  504. break;
  505. }
  506. }
  507. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  508. if (const Expr *e = dyn_cast<Expr>(s)) {
  509. // Skip the most common kinds of expressions that make
  510. // hierarchy-walking expensive.
  511. s = e = e->IgnoreParenCasts();
  512. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  513. return (ref->getDecl() == &var);
  514. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  515. const BlockDecl *block = be->getBlockDecl();
  516. for (const auto &I : block->captures()) {
  517. if (I.getVariable() == &var)
  518. return true;
  519. }
  520. }
  521. }
  522. for (const Stmt *SubStmt : s->children())
  523. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  524. if (SubStmt && isAccessedBy(var, SubStmt))
  525. return true;
  526. return false;
  527. }
  528. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  529. if (!decl) return false;
  530. if (!isa<VarDecl>(decl)) return false;
  531. const VarDecl *var = cast<VarDecl>(decl);
  532. return isAccessedBy(*var, e);
  533. }
  534. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  535. const LValue &destLV, const Expr *init) {
  536. bool needsCast = false;
  537. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  538. switch (castExpr->getCastKind()) {
  539. // Look through casts that don't require representation changes.
  540. case CK_NoOp:
  541. case CK_BitCast:
  542. case CK_BlockPointerToObjCPointerCast:
  543. needsCast = true;
  544. break;
  545. // If we find an l-value to r-value cast from a __weak variable,
  546. // emit this operation as a copy or move.
  547. case CK_LValueToRValue: {
  548. const Expr *srcExpr = castExpr->getSubExpr();
  549. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  550. return false;
  551. // Emit the source l-value.
  552. LValue srcLV = CGF.EmitLValue(srcExpr);
  553. // Handle a formal type change to avoid asserting.
  554. auto srcAddr = srcLV.getAddress();
  555. if (needsCast) {
  556. srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
  557. destLV.getAddress().getElementType());
  558. }
  559. // If it was an l-value, use objc_copyWeak.
  560. if (srcExpr->getValueKind() == VK_LValue) {
  561. CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
  562. } else {
  563. assert(srcExpr->getValueKind() == VK_XValue);
  564. CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
  565. }
  566. return true;
  567. }
  568. // Stop at anything else.
  569. default:
  570. return false;
  571. }
  572. init = castExpr->getSubExpr();
  573. }
  574. return false;
  575. }
  576. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  577. LValue &lvalue,
  578. const VarDecl *var) {
  579. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
  580. }
  581. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  582. LValue lvalue, bool capturedByInit) {
  583. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  584. if (!lifetime) {
  585. llvm::Value *value = EmitScalarExpr(init);
  586. if (capturedByInit)
  587. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  588. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  589. return;
  590. }
  591. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  592. init = DIE->getExpr();
  593. // If we're emitting a value with lifetime, we have to do the
  594. // initialization *before* we leave the cleanup scopes.
  595. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  596. enterFullExpression(ewc);
  597. init = ewc->getSubExpr();
  598. }
  599. CodeGenFunction::RunCleanupsScope Scope(*this);
  600. // We have to maintain the illusion that the variable is
  601. // zero-initialized. If the variable might be accessed in its
  602. // initializer, zero-initialize before running the initializer, then
  603. // actually perform the initialization with an assign.
  604. bool accessedByInit = false;
  605. if (lifetime != Qualifiers::OCL_ExplicitNone)
  606. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  607. if (accessedByInit) {
  608. LValue tempLV = lvalue;
  609. // Drill down to the __block object if necessary.
  610. if (capturedByInit) {
  611. // We can use a simple GEP for this because it can't have been
  612. // moved yet.
  613. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
  614. cast<VarDecl>(D),
  615. /*follow*/ false));
  616. }
  617. auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
  618. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  619. // If __weak, we want to use a barrier under certain conditions.
  620. if (lifetime == Qualifiers::OCL_Weak)
  621. EmitARCInitWeak(tempLV.getAddress(), zero);
  622. // Otherwise just do a simple store.
  623. else
  624. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  625. }
  626. // Emit the initializer.
  627. llvm::Value *value = nullptr;
  628. switch (lifetime) {
  629. case Qualifiers::OCL_None:
  630. llvm_unreachable("present but none");
  631. case Qualifiers::OCL_ExplicitNone:
  632. value = EmitARCUnsafeUnretainedScalarExpr(init);
  633. break;
  634. case Qualifiers::OCL_Strong: {
  635. value = EmitARCRetainScalarExpr(init);
  636. break;
  637. }
  638. case Qualifiers::OCL_Weak: {
  639. // If it's not accessed by the initializer, try to emit the
  640. // initialization with a copy or move.
  641. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  642. return;
  643. }
  644. // No way to optimize a producing initializer into this. It's not
  645. // worth optimizing for, because the value will immediately
  646. // disappear in the common case.
  647. value = EmitScalarExpr(init);
  648. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  649. if (accessedByInit)
  650. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  651. else
  652. EmitARCInitWeak(lvalue.getAddress(), value);
  653. return;
  654. }
  655. case Qualifiers::OCL_Autoreleasing:
  656. value = EmitARCRetainAutoreleaseScalarExpr(init);
  657. break;
  658. }
  659. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  660. // If the variable might have been accessed by its initializer, we
  661. // might have to initialize with a barrier. We have to do this for
  662. // both __weak and __strong, but __weak got filtered out above.
  663. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  664. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  665. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  666. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  667. return;
  668. }
  669. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  670. }
  671. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  672. /// non-zero parts of the specified initializer with equal or fewer than
  673. /// NumStores scalar stores.
  674. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  675. unsigned &NumStores) {
  676. // Zero and Undef never requires any extra stores.
  677. if (isa<llvm::ConstantAggregateZero>(Init) ||
  678. isa<llvm::ConstantPointerNull>(Init) ||
  679. isa<llvm::UndefValue>(Init))
  680. return true;
  681. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  682. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  683. isa<llvm::ConstantExpr>(Init))
  684. return Init->isNullValue() || NumStores--;
  685. // See if we can emit each element.
  686. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  687. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  688. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  689. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  690. return false;
  691. }
  692. return true;
  693. }
  694. if (llvm::ConstantDataSequential *CDS =
  695. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  696. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  697. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  698. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  699. return false;
  700. }
  701. return true;
  702. }
  703. // Anything else is hard and scary.
  704. return false;
  705. }
  706. /// emitStoresForInitAfterMemset - For inits that
  707. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  708. /// stores that would be required.
  709. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  710. bool isVolatile, CGBuilderTy &Builder) {
  711. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  712. "called emitStoresForInitAfterMemset for zero or undef value.");
  713. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  714. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  715. isa<llvm::ConstantExpr>(Init)) {
  716. Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
  717. return;
  718. }
  719. if (llvm::ConstantDataSequential *CDS =
  720. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  721. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  722. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  723. // If necessary, get a pointer to the element and emit it.
  724. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  725. emitStoresForInitAfterMemset(
  726. Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
  727. isVolatile, Builder);
  728. }
  729. return;
  730. }
  731. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  732. "Unknown value type!");
  733. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  734. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  735. // If necessary, get a pointer to the element and emit it.
  736. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  737. emitStoresForInitAfterMemset(
  738. Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
  739. isVolatile, Builder);
  740. }
  741. }
  742. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  743. /// plus some stores to initialize a local variable instead of using a memcpy
  744. /// from a constant global. It is beneficial to use memset if the global is all
  745. /// zeros, or mostly zeros and large.
  746. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  747. uint64_t GlobalSize) {
  748. // If a global is all zeros, always use a memset.
  749. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  750. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  751. // do it if it will require 6 or fewer scalar stores.
  752. // TODO: Should budget depends on the size? Avoiding a large global warrants
  753. // plopping in more stores.
  754. unsigned StoreBudget = 6;
  755. uint64_t SizeLimit = 32;
  756. return GlobalSize > SizeLimit &&
  757. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  758. }
  759. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  760. /// variable declaration with auto, register, or no storage class specifier.
  761. /// These turn into simple stack objects, or GlobalValues depending on target.
  762. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  763. AutoVarEmission emission = EmitAutoVarAlloca(D);
  764. EmitAutoVarInit(emission);
  765. EmitAutoVarCleanups(emission);
  766. }
  767. /// Emit a lifetime.begin marker if some criteria are satisfied.
  768. /// \return a pointer to the temporary size Value if a marker was emitted, null
  769. /// otherwise
  770. llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
  771. llvm::Value *Addr) {
  772. if (!ShouldEmitLifetimeMarkers)
  773. return nullptr;
  774. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  775. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  776. llvm::CallInst *C =
  777. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  778. C->setDoesNotThrow();
  779. return SizeV;
  780. }
  781. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  782. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  783. llvm::CallInst *C =
  784. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  785. C->setDoesNotThrow();
  786. }
  787. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  788. /// local variable. Does not emit initialization or destruction.
  789. CodeGenFunction::AutoVarEmission
  790. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  791. QualType Ty = D.getType();
  792. AutoVarEmission emission(D);
  793. bool isByRef = D.hasAttr<BlocksAttr>();
  794. emission.IsByRef = isByRef;
  795. CharUnits alignment = getContext().getDeclAlign(&D);
  796. // If the type is variably-modified, emit all the VLA sizes for it.
  797. if (Ty->isVariablyModifiedType())
  798. EmitVariablyModifiedType(Ty);
  799. Address address = Address::invalid();
  800. if (Ty->isConstantSizeType()) {
  801. bool NRVO = getLangOpts().ElideConstructors &&
  802. D.isNRVOVariable();
  803. // If this value is an array or struct with a statically determinable
  804. // constant initializer, there are optimizations we can do.
  805. //
  806. // TODO: We should constant-evaluate the initializer of any variable,
  807. // as long as it is initialized by a constant expression. Currently,
  808. // isConstantInitializer produces wrong answers for structs with
  809. // reference or bitfield members, and a few other cases, and checking
  810. // for POD-ness protects us from some of these.
  811. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  812. (D.isConstexpr() ||
  813. ((Ty.isPODType(getContext()) ||
  814. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  815. D.getInit()->isConstantInitializer(getContext(), false)))) {
  816. // If the variable's a const type, and it's neither an NRVO
  817. // candidate nor a __block variable and has no mutable members,
  818. // emit it as a global instead.
  819. // Exception is if a variable is located in non-constant address space
  820. // in OpenCL.
  821. if ((!getLangOpts().OpenCL ||
  822. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  823. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  824. CGM.isTypeConstant(Ty, true))) {
  825. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  826. // Signal this condition to later callbacks.
  827. emission.Addr = Address::invalid();
  828. assert(emission.wasEmittedAsGlobal());
  829. return emission;
  830. }
  831. // Otherwise, tell the initialization code that we're in this case.
  832. emission.IsConstantAggregate = true;
  833. }
  834. // A normal fixed sized variable becomes an alloca in the entry block,
  835. // unless it's an NRVO variable.
  836. if (NRVO) {
  837. // The named return value optimization: allocate this variable in the
  838. // return slot, so that we can elide the copy when returning this
  839. // variable (C++0x [class.copy]p34).
  840. address = ReturnValue;
  841. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  842. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  843. // Create a flag that is used to indicate when the NRVO was applied
  844. // to this variable. Set it to zero to indicate that NRVO was not
  845. // applied.
  846. llvm::Value *Zero = Builder.getFalse();
  847. Address NRVOFlag =
  848. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
  849. EnsureInsertPoint();
  850. Builder.CreateStore(Zero, NRVOFlag);
  851. // Record the NRVO flag for this variable.
  852. NRVOFlags[&D] = NRVOFlag.getPointer();
  853. emission.NRVOFlag = NRVOFlag.getPointer();
  854. }
  855. }
  856. } else {
  857. CharUnits allocaAlignment;
  858. llvm::Type *allocaTy;
  859. if (isByRef) {
  860. auto &byrefInfo = getBlockByrefInfo(&D);
  861. allocaTy = byrefInfo.Type;
  862. allocaAlignment = byrefInfo.ByrefAlignment;
  863. } else {
  864. allocaTy = ConvertTypeForMem(Ty);
  865. allocaAlignment = alignment;
  866. }
  867. // Create the alloca. Note that we set the name separately from
  868. // building the instruction so that it's there even in no-asserts
  869. // builds.
  870. address = CreateTempAlloca(allocaTy, allocaAlignment);
  871. address.getPointer()->setName(D.getName());
  872. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  873. // the catch parameter starts in the catchpad instruction, and we can't
  874. // insert code in those basic blocks.
  875. bool IsMSCatchParam =
  876. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  877. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  878. // if we don't have a valid insertion point (?).
  879. if (HaveInsertPoint() && !IsMSCatchParam) {
  880. // If there's a jump into the lifetime of this variable, its lifetime
  881. // gets broken up into several regions in IR, which requires more work
  882. // to handle correctly. For now, just omit the intrinsics; this is a
  883. // rare case, and it's better to just be conservatively correct.
  884. // PR28267.
  885. //
  886. // We have to do this in all language modes if there's a jump past the
  887. // declaration. We also have to do it in C if there's a jump to an
  888. // earlier point in the current block because non-VLA lifetimes begin as
  889. // soon as the containing block is entered, not when its variables
  890. // actually come into scope; suppressing the lifetime annotations
  891. // completely in this case is unnecessarily pessimistic, but again, this
  892. // is rare.
  893. if (!Bypasses.IsBypassed(&D) &&
  894. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  895. uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  896. emission.SizeForLifetimeMarkers =
  897. EmitLifetimeStart(size, address.getPointer());
  898. }
  899. } else {
  900. assert(!emission.useLifetimeMarkers());
  901. }
  902. }
  903. } else {
  904. EnsureInsertPoint();
  905. if (!DidCallStackSave) {
  906. // Save the stack.
  907. Address Stack =
  908. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  909. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  910. llvm::Value *V = Builder.CreateCall(F);
  911. Builder.CreateStore(V, Stack);
  912. DidCallStackSave = true;
  913. // Push a cleanup block and restore the stack there.
  914. // FIXME: in general circumstances, this should be an EH cleanup.
  915. pushStackRestore(NormalCleanup, Stack);
  916. }
  917. llvm::Value *elementCount;
  918. QualType elementType;
  919. std::tie(elementCount, elementType) = getVLASize(Ty);
  920. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  921. // Allocate memory for the array.
  922. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  923. vla->setAlignment(alignment.getQuantity());
  924. address = Address(vla, alignment);
  925. }
  926. setAddrOfLocalVar(&D, address);
  927. emission.Addr = address;
  928. // Emit debug info for local var declaration.
  929. if (HaveInsertPoint())
  930. if (CGDebugInfo *DI = getDebugInfo()) {
  931. if (CGM.getCodeGenOpts().getDebugInfo() >=
  932. codegenoptions::LimitedDebugInfo) {
  933. DI->setLocation(D.getLocation());
  934. DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
  935. }
  936. }
  937. if (D.hasAttr<AnnotateAttr>())
  938. EmitVarAnnotations(&D, address.getPointer());
  939. return emission;
  940. }
  941. /// Determines whether the given __block variable is potentially
  942. /// captured by the given expression.
  943. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  944. // Skip the most common kinds of expressions that make
  945. // hierarchy-walking expensive.
  946. e = e->IgnoreParenCasts();
  947. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  948. const BlockDecl *block = be->getBlockDecl();
  949. for (const auto &I : block->captures()) {
  950. if (I.getVariable() == &var)
  951. return true;
  952. }
  953. // No need to walk into the subexpressions.
  954. return false;
  955. }
  956. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  957. const CompoundStmt *CS = SE->getSubStmt();
  958. for (const auto *BI : CS->body())
  959. if (const auto *E = dyn_cast<Expr>(BI)) {
  960. if (isCapturedBy(var, E))
  961. return true;
  962. }
  963. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  964. // special case declarations
  965. for (const auto *I : DS->decls()) {
  966. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  967. const Expr *Init = VD->getInit();
  968. if (Init && isCapturedBy(var, Init))
  969. return true;
  970. }
  971. }
  972. }
  973. else
  974. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  975. // Later, provide code to poke into statements for capture analysis.
  976. return true;
  977. return false;
  978. }
  979. for (const Stmt *SubStmt : e->children())
  980. if (isCapturedBy(var, cast<Expr>(SubStmt)))
  981. return true;
  982. return false;
  983. }
  984. /// \brief Determine whether the given initializer is trivial in the sense
  985. /// that it requires no code to be generated.
  986. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  987. if (!Init)
  988. return true;
  989. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  990. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  991. if (Constructor->isTrivial() &&
  992. Constructor->isDefaultConstructor() &&
  993. !Construct->requiresZeroInitialization())
  994. return true;
  995. return false;
  996. }
  997. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  998. assert(emission.Variable && "emission was not valid!");
  999. // If this was emitted as a global constant, we're done.
  1000. if (emission.wasEmittedAsGlobal()) return;
  1001. const VarDecl &D = *emission.Variable;
  1002. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1003. QualType type = D.getType();
  1004. // If this local has an initializer, emit it now.
  1005. const Expr *Init = D.getInit();
  1006. // If we are at an unreachable point, we don't need to emit the initializer
  1007. // unless it contains a label.
  1008. if (!HaveInsertPoint()) {
  1009. if (!Init || !ContainsLabel(Init)) return;
  1010. EnsureInsertPoint();
  1011. }
  1012. // Initialize the structure of a __block variable.
  1013. if (emission.IsByRef)
  1014. emitByrefStructureInit(emission);
  1015. if (isTrivialInitializer(Init))
  1016. return;
  1017. // Check whether this is a byref variable that's potentially
  1018. // captured and moved by its own initializer. If so, we'll need to
  1019. // emit the initializer first, then copy into the variable.
  1020. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  1021. Address Loc =
  1022. capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
  1023. llvm::Constant *constant = nullptr;
  1024. if (emission.IsConstantAggregate || D.isConstexpr()) {
  1025. assert(!capturedByInit && "constant init contains a capturing block?");
  1026. constant = CGM.EmitConstantInit(D, this);
  1027. }
  1028. if (!constant) {
  1029. LValue lv = MakeAddrLValue(Loc, type);
  1030. lv.setNonGC(true);
  1031. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1032. }
  1033. if (!emission.IsConstantAggregate) {
  1034. // For simple scalar/complex initialization, store the value directly.
  1035. LValue lv = MakeAddrLValue(Loc, type);
  1036. lv.setNonGC(true);
  1037. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1038. }
  1039. // If this is a simple aggregate initialization, we can optimize it
  1040. // in various ways.
  1041. bool isVolatile = type.isVolatileQualified();
  1042. llvm::Value *SizeVal =
  1043. llvm::ConstantInt::get(IntPtrTy,
  1044. getContext().getTypeSizeInChars(type).getQuantity());
  1045. llvm::Type *BP = Int8PtrTy;
  1046. if (Loc.getType() != BP)
  1047. Loc = Builder.CreateBitCast(Loc, BP);
  1048. // If the initializer is all or mostly zeros, codegen with memset then do
  1049. // a few stores afterward.
  1050. if (shouldUseMemSetPlusStoresToInitialize(constant,
  1051. CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
  1052. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1053. isVolatile);
  1054. // Zero and undef don't require a stores.
  1055. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  1056. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  1057. emitStoresForInitAfterMemset(constant, Loc.getPointer(),
  1058. isVolatile, Builder);
  1059. }
  1060. } else {
  1061. // Otherwise, create a temporary global with the initializer then
  1062. // memcpy from the global to the alloca.
  1063. std::string Name = getStaticDeclName(CGM, D);
  1064. unsigned AS = 0;
  1065. if (getLangOpts().OpenCL) {
  1066. AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  1067. BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
  1068. }
  1069. llvm::GlobalVariable *GV =
  1070. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  1071. llvm::GlobalValue::PrivateLinkage,
  1072. constant, Name, nullptr,
  1073. llvm::GlobalValue::NotThreadLocal, AS);
  1074. GV->setAlignment(Loc.getAlignment().getQuantity());
  1075. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1076. Address SrcPtr = Address(GV, Loc.getAlignment());
  1077. if (SrcPtr.getType() != BP)
  1078. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  1079. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
  1080. }
  1081. }
  1082. /// Emit an expression as an initializer for a variable at the given
  1083. /// location. The expression is not necessarily the normal
  1084. /// initializer for the variable, and the address is not necessarily
  1085. /// its normal location.
  1086. ///
  1087. /// \param init the initializing expression
  1088. /// \param var the variable to act as if we're initializing
  1089. /// \param loc the address to initialize; its type is a pointer
  1090. /// to the LLVM mapping of the variable's type
  1091. /// \param alignment the alignment of the address
  1092. /// \param capturedByInit true if the variable is a __block variable
  1093. /// whose address is potentially changed by the initializer
  1094. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1095. LValue lvalue, bool capturedByInit) {
  1096. QualType type = D->getType();
  1097. if (type->isReferenceType()) {
  1098. RValue rvalue = EmitReferenceBindingToExpr(init);
  1099. if (capturedByInit)
  1100. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1101. EmitStoreThroughLValue(rvalue, lvalue, true);
  1102. return;
  1103. }
  1104. switch (getEvaluationKind(type)) {
  1105. case TEK_Scalar:
  1106. EmitScalarInit(init, D, lvalue, capturedByInit);
  1107. return;
  1108. case TEK_Complex: {
  1109. ComplexPairTy complex = EmitComplexExpr(init);
  1110. if (capturedByInit)
  1111. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1112. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1113. return;
  1114. }
  1115. case TEK_Aggregate:
  1116. if (type->isAtomicType()) {
  1117. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1118. } else {
  1119. // TODO: how can we delay here if D is captured by its initializer?
  1120. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1121. AggValueSlot::IsDestructed,
  1122. AggValueSlot::DoesNotNeedGCBarriers,
  1123. AggValueSlot::IsNotAliased));
  1124. }
  1125. return;
  1126. }
  1127. llvm_unreachable("bad evaluation kind");
  1128. }
  1129. /// Enter a destroy cleanup for the given local variable.
  1130. void CodeGenFunction::emitAutoVarTypeCleanup(
  1131. const CodeGenFunction::AutoVarEmission &emission,
  1132. QualType::DestructionKind dtorKind) {
  1133. assert(dtorKind != QualType::DK_none);
  1134. // Note that for __block variables, we want to destroy the
  1135. // original stack object, not the possibly forwarded object.
  1136. Address addr = emission.getObjectAddress(*this);
  1137. const VarDecl *var = emission.Variable;
  1138. QualType type = var->getType();
  1139. CleanupKind cleanupKind = NormalAndEHCleanup;
  1140. CodeGenFunction::Destroyer *destroyer = nullptr;
  1141. switch (dtorKind) {
  1142. case QualType::DK_none:
  1143. llvm_unreachable("no cleanup for trivially-destructible variable");
  1144. case QualType::DK_cxx_destructor:
  1145. // If there's an NRVO flag on the emission, we need a different
  1146. // cleanup.
  1147. if (emission.NRVOFlag) {
  1148. assert(!type->isArrayType());
  1149. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1150. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
  1151. dtor, emission.NRVOFlag);
  1152. return;
  1153. }
  1154. break;
  1155. case QualType::DK_objc_strong_lifetime:
  1156. // Suppress cleanups for pseudo-strong variables.
  1157. if (var->isARCPseudoStrong()) return;
  1158. // Otherwise, consider whether to use an EH cleanup or not.
  1159. cleanupKind = getARCCleanupKind();
  1160. // Use the imprecise destroyer by default.
  1161. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1162. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1163. break;
  1164. case QualType::DK_objc_weak_lifetime:
  1165. break;
  1166. }
  1167. // If we haven't chosen a more specific destroyer, use the default.
  1168. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1169. // Use an EH cleanup in array destructors iff the destructor itself
  1170. // is being pushed as an EH cleanup.
  1171. bool useEHCleanup = (cleanupKind & EHCleanup);
  1172. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1173. useEHCleanup);
  1174. }
  1175. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1176. assert(emission.Variable && "emission was not valid!");
  1177. // If this was emitted as a global constant, we're done.
  1178. if (emission.wasEmittedAsGlobal()) return;
  1179. // If we don't have an insertion point, we're done. Sema prevents
  1180. // us from jumping into any of these scopes anyway.
  1181. if (!HaveInsertPoint()) return;
  1182. const VarDecl &D = *emission.Variable;
  1183. // Make sure we call @llvm.lifetime.end. This needs to happen
  1184. // *last*, so the cleanup needs to be pushed *first*.
  1185. if (emission.useLifetimeMarkers())
  1186. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1187. emission.getAllocatedAddress(),
  1188. emission.getSizeForLifetimeMarkers());
  1189. // Check the type for a cleanup.
  1190. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1191. emitAutoVarTypeCleanup(emission, dtorKind);
  1192. // In GC mode, honor objc_precise_lifetime.
  1193. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1194. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1195. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1196. }
  1197. // Handle the cleanup attribute.
  1198. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1199. const FunctionDecl *FD = CA->getFunctionDecl();
  1200. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1201. assert(F && "Could not find function!");
  1202. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1203. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1204. }
  1205. // If this is a block variable, call _Block_object_destroy
  1206. // (on the unforwarded address).
  1207. if (emission.IsByRef)
  1208. enterByrefCleanup(emission);
  1209. }
  1210. CodeGenFunction::Destroyer *
  1211. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1212. switch (kind) {
  1213. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1214. case QualType::DK_cxx_destructor:
  1215. return destroyCXXObject;
  1216. case QualType::DK_objc_strong_lifetime:
  1217. return destroyARCStrongPrecise;
  1218. case QualType::DK_objc_weak_lifetime:
  1219. return destroyARCWeak;
  1220. }
  1221. llvm_unreachable("Unknown DestructionKind");
  1222. }
  1223. /// pushEHDestroy - Push the standard destructor for the given type as
  1224. /// an EH-only cleanup.
  1225. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1226. Address addr, QualType type) {
  1227. assert(dtorKind && "cannot push destructor for trivial type");
  1228. assert(needsEHCleanup(dtorKind));
  1229. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1230. }
  1231. /// pushDestroy - Push the standard destructor for the given type as
  1232. /// at least a normal cleanup.
  1233. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1234. Address addr, QualType type) {
  1235. assert(dtorKind && "cannot push destructor for trivial type");
  1236. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1237. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1238. cleanupKind & EHCleanup);
  1239. }
  1240. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1241. QualType type, Destroyer *destroyer,
  1242. bool useEHCleanupForArray) {
  1243. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1244. destroyer, useEHCleanupForArray);
  1245. }
  1246. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1247. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1248. }
  1249. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1250. CleanupKind cleanupKind, Address addr, QualType type,
  1251. Destroyer *destroyer, bool useEHCleanupForArray) {
  1252. assert(!isInConditionalBranch() &&
  1253. "performing lifetime extension from within conditional");
  1254. // Push an EH-only cleanup for the object now.
  1255. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1256. // around in case a temporary's destructor throws an exception.
  1257. if (cleanupKind & EHCleanup)
  1258. EHStack.pushCleanup<DestroyObject>(
  1259. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1260. destroyer, useEHCleanupForArray);
  1261. // Remember that we need to push a full cleanup for the object at the
  1262. // end of the full-expression.
  1263. pushCleanupAfterFullExpr<DestroyObject>(
  1264. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1265. }
  1266. /// emitDestroy - Immediately perform the destruction of the given
  1267. /// object.
  1268. ///
  1269. /// \param addr - the address of the object; a type*
  1270. /// \param type - the type of the object; if an array type, all
  1271. /// objects are destroyed in reverse order
  1272. /// \param destroyer - the function to call to destroy individual
  1273. /// elements
  1274. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1275. /// used when destroying array elements, in case one of the
  1276. /// destructions throws an exception
  1277. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1278. Destroyer *destroyer,
  1279. bool useEHCleanupForArray) {
  1280. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1281. if (!arrayType)
  1282. return destroyer(*this, addr, type);
  1283. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1284. CharUnits elementAlign =
  1285. addr.getAlignment()
  1286. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1287. // Normally we have to check whether the array is zero-length.
  1288. bool checkZeroLength = true;
  1289. // But if the array length is constant, we can suppress that.
  1290. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1291. // ...and if it's constant zero, we can just skip the entire thing.
  1292. if (constLength->isZero()) return;
  1293. checkZeroLength = false;
  1294. }
  1295. llvm::Value *begin = addr.getPointer();
  1296. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1297. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1298. checkZeroLength, useEHCleanupForArray);
  1299. }
  1300. /// emitArrayDestroy - Destroys all the elements of the given array,
  1301. /// beginning from last to first. The array cannot be zero-length.
  1302. ///
  1303. /// \param begin - a type* denoting the first element of the array
  1304. /// \param end - a type* denoting one past the end of the array
  1305. /// \param elementType - the element type of the array
  1306. /// \param destroyer - the function to call to destroy elements
  1307. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1308. /// the remaining elements in case the destruction of a single
  1309. /// element throws
  1310. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1311. llvm::Value *end,
  1312. QualType elementType,
  1313. CharUnits elementAlign,
  1314. Destroyer *destroyer,
  1315. bool checkZeroLength,
  1316. bool useEHCleanup) {
  1317. assert(!elementType->isArrayType());
  1318. // The basic structure here is a do-while loop, because we don't
  1319. // need to check for the zero-element case.
  1320. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1321. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1322. if (checkZeroLength) {
  1323. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1324. "arraydestroy.isempty");
  1325. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1326. }
  1327. // Enter the loop body, making that address the current address.
  1328. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1329. EmitBlock(bodyBB);
  1330. llvm::PHINode *elementPast =
  1331. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1332. elementPast->addIncoming(end, entryBB);
  1333. // Shift the address back by one element.
  1334. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1335. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1336. "arraydestroy.element");
  1337. if (useEHCleanup)
  1338. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1339. destroyer);
  1340. // Perform the actual destruction there.
  1341. destroyer(*this, Address(element, elementAlign), elementType);
  1342. if (useEHCleanup)
  1343. PopCleanupBlock();
  1344. // Check whether we've reached the end.
  1345. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1346. Builder.CreateCondBr(done, doneBB, bodyBB);
  1347. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1348. // Done.
  1349. EmitBlock(doneBB);
  1350. }
  1351. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1352. /// emitArrayDestroy, the element type here may still be an array type.
  1353. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1354. llvm::Value *begin, llvm::Value *end,
  1355. QualType type, CharUnits elementAlign,
  1356. CodeGenFunction::Destroyer *destroyer) {
  1357. // If the element type is itself an array, drill down.
  1358. unsigned arrayDepth = 0;
  1359. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1360. // VLAs don't require a GEP index to walk into.
  1361. if (!isa<VariableArrayType>(arrayType))
  1362. arrayDepth++;
  1363. type = arrayType->getElementType();
  1364. }
  1365. if (arrayDepth) {
  1366. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1367. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  1368. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1369. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1370. }
  1371. // Destroy the array. We don't ever need an EH cleanup because we
  1372. // assume that we're in an EH cleanup ourselves, so a throwing
  1373. // destructor causes an immediate terminate.
  1374. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1375. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1376. }
  1377. namespace {
  1378. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1379. /// array destroy where the end pointer is regularly determined and
  1380. /// does not need to be loaded from a local.
  1381. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1382. llvm::Value *ArrayBegin;
  1383. llvm::Value *ArrayEnd;
  1384. QualType ElementType;
  1385. CodeGenFunction::Destroyer *Destroyer;
  1386. CharUnits ElementAlign;
  1387. public:
  1388. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1389. QualType elementType, CharUnits elementAlign,
  1390. CodeGenFunction::Destroyer *destroyer)
  1391. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1392. ElementType(elementType), Destroyer(destroyer),
  1393. ElementAlign(elementAlign) {}
  1394. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1395. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1396. ElementType, ElementAlign, Destroyer);
  1397. }
  1398. };
  1399. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1400. /// partial array destroy where the end pointer is irregularly
  1401. /// determined and must be loaded from a local.
  1402. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1403. llvm::Value *ArrayBegin;
  1404. Address ArrayEndPointer;
  1405. QualType ElementType;
  1406. CodeGenFunction::Destroyer *Destroyer;
  1407. CharUnits ElementAlign;
  1408. public:
  1409. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1410. Address arrayEndPointer,
  1411. QualType elementType,
  1412. CharUnits elementAlign,
  1413. CodeGenFunction::Destroyer *destroyer)
  1414. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1415. ElementType(elementType), Destroyer(destroyer),
  1416. ElementAlign(elementAlign) {}
  1417. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1418. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1419. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1420. ElementType, ElementAlign, Destroyer);
  1421. }
  1422. };
  1423. } // end anonymous namespace
  1424. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1425. /// already-constructed elements of the given array. The cleanup
  1426. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1427. ///
  1428. /// \param elementType - the immediate element type of the array;
  1429. /// possibly still an array type
  1430. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1431. Address arrayEndPointer,
  1432. QualType elementType,
  1433. CharUnits elementAlign,
  1434. Destroyer *destroyer) {
  1435. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1436. arrayBegin, arrayEndPointer,
  1437. elementType, elementAlign,
  1438. destroyer);
  1439. }
  1440. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1441. /// already-constructed elements of the given array. The cleanup
  1442. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1443. ///
  1444. /// \param elementType - the immediate element type of the array;
  1445. /// possibly still an array type
  1446. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1447. llvm::Value *arrayEnd,
  1448. QualType elementType,
  1449. CharUnits elementAlign,
  1450. Destroyer *destroyer) {
  1451. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1452. arrayBegin, arrayEnd,
  1453. elementType, elementAlign,
  1454. destroyer);
  1455. }
  1456. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1457. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1458. if (LifetimeStartFn) return LifetimeStartFn;
  1459. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1460. llvm::Intrinsic::lifetime_start);
  1461. return LifetimeStartFn;
  1462. }
  1463. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1464. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1465. if (LifetimeEndFn) return LifetimeEndFn;
  1466. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1467. llvm::Intrinsic::lifetime_end);
  1468. return LifetimeEndFn;
  1469. }
  1470. namespace {
  1471. /// A cleanup to perform a release of an object at the end of a
  1472. /// function. This is used to balance out the incoming +1 of a
  1473. /// ns_consumed argument when we can't reasonably do that just by
  1474. /// not doing the initial retain for a __block argument.
  1475. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  1476. ConsumeARCParameter(llvm::Value *param,
  1477. ARCPreciseLifetime_t precise)
  1478. : Param(param), Precise(precise) {}
  1479. llvm::Value *Param;
  1480. ARCPreciseLifetime_t Precise;
  1481. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1482. CGF.EmitARCRelease(Param, Precise);
  1483. }
  1484. };
  1485. } // end anonymous namespace
  1486. /// Emit an alloca (or GlobalValue depending on target)
  1487. /// for the specified parameter and set up LocalDeclMap.
  1488. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  1489. unsigned ArgNo) {
  1490. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1491. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1492. "Invalid argument to EmitParmDecl");
  1493. Arg.getAnyValue()->setName(D.getName());
  1494. QualType Ty = D.getType();
  1495. // Use better IR generation for certain implicit parameters.
  1496. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  1497. // The only implicit argument a block has is its literal.
  1498. // We assume this is always passed directly.
  1499. if (BlockInfo) {
  1500. setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
  1501. return;
  1502. }
  1503. // Apply any prologue 'this' adjustments required by the ABI. Be careful to
  1504. // handle the case where 'this' is passed indirectly as part of an inalloca
  1505. // struct.
  1506. if (const CXXMethodDecl *MD =
  1507. dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
  1508. if (MD->isVirtual() && IPD == CXXABIThisDecl) {
  1509. llvm::Value *This = Arg.isIndirect()
  1510. ? Builder.CreateLoad(Arg.getIndirectAddress())
  1511. : Arg.getDirectValue();
  1512. This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
  1513. *this, CurGD, This);
  1514. if (Arg.isIndirect())
  1515. Builder.CreateStore(This, Arg.getIndirectAddress());
  1516. else
  1517. Arg = ParamValue::forDirect(This);
  1518. }
  1519. }
  1520. }
  1521. Address DeclPtr = Address::invalid();
  1522. bool DoStore = false;
  1523. bool IsScalar = hasScalarEvaluationKind(Ty);
  1524. // If we already have a pointer to the argument, reuse the input pointer.
  1525. if (Arg.isIndirect()) {
  1526. DeclPtr = Arg.getIndirectAddress();
  1527. // If we have a prettier pointer type at this point, bitcast to that.
  1528. unsigned AS = DeclPtr.getType()->getAddressSpace();
  1529. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1530. if (DeclPtr.getType() != IRTy)
  1531. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  1532. // Push a destructor cleanup for this parameter if the ABI requires it.
  1533. // Don't push a cleanup in a thunk for a method that will also emit a
  1534. // cleanup.
  1535. if (!IsScalar && !CurFuncIsThunk &&
  1536. getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1537. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  1538. if (RD && RD->hasNonTrivialDestructor())
  1539. pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
  1540. }
  1541. } else {
  1542. // Otherwise, create a temporary to hold the value.
  1543. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  1544. D.getName() + ".addr");
  1545. DoStore = true;
  1546. }
  1547. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  1548. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  1549. if (IsScalar) {
  1550. Qualifiers qs = Ty.getQualifiers();
  1551. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1552. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1553. // For __strong, it's handled by just skipping the initial retain;
  1554. // otherwise we have to balance out the initial +1 with an extra
  1555. // cleanup to do the release at the end of the function.
  1556. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1557. // 'self' is always formally __strong, but if this is not an
  1558. // init method then we don't want to retain it.
  1559. if (D.isARCPseudoStrong()) {
  1560. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1561. assert(&D == method->getSelfDecl());
  1562. assert(lt == Qualifiers::OCL_Strong);
  1563. assert(qs.hasConst());
  1564. assert(method->getMethodFamily() != OMF_init);
  1565. (void) method;
  1566. lt = Qualifiers::OCL_ExplicitNone;
  1567. }
  1568. if (lt == Qualifiers::OCL_Strong) {
  1569. if (!isConsumed) {
  1570. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1571. // use objc_storeStrong(&dest, value) for retaining the
  1572. // object. But first, store a null into 'dest' because
  1573. // objc_storeStrong attempts to release its old value.
  1574. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1575. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1576. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  1577. DoStore = false;
  1578. }
  1579. else
  1580. // Don't use objc_retainBlock for block pointers, because we
  1581. // don't want to Block_copy something just because we got it
  1582. // as a parameter.
  1583. ArgVal = EmitARCRetainNonBlock(ArgVal);
  1584. }
  1585. } else {
  1586. // Push the cleanup for a consumed parameter.
  1587. if (isConsumed) {
  1588. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1589. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1590. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  1591. precise);
  1592. }
  1593. if (lt == Qualifiers::OCL_Weak) {
  1594. EmitARCInitWeak(DeclPtr, ArgVal);
  1595. DoStore = false; // The weak init is a store, no need to do two.
  1596. }
  1597. }
  1598. // Enter the cleanup scope.
  1599. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1600. }
  1601. }
  1602. // Store the initial value into the alloca.
  1603. if (DoStore)
  1604. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  1605. setAddrOfLocalVar(&D, DeclPtr);
  1606. // Emit debug info for param declaration.
  1607. if (CGDebugInfo *DI = getDebugInfo()) {
  1608. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1609. codegenoptions::LimitedDebugInfo) {
  1610. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  1611. }
  1612. }
  1613. if (D.hasAttr<AnnotateAttr>())
  1614. EmitVarAnnotations(&D, DeclPtr.getPointer());
  1615. }
  1616. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1617. CodeGenFunction *CGF) {
  1618. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  1619. return;
  1620. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  1621. }