CGDecl.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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 "CGCleanup.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGOpenCLRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/CharUnits.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/DeclOpenMP.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "clang/Basic/TargetInfo.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "clang/Frontend/CodeGenOptions.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/GlobalVariable.h"
  31. #include "llvm/IR/Intrinsics.h"
  32. #include "llvm/IR/Type.h"
  33. using namespace clang;
  34. using namespace CodeGen;
  35. void CodeGenFunction::EmitDecl(const Decl &D) {
  36. switch (D.getKind()) {
  37. case Decl::BuiltinTemplate:
  38. case Decl::TranslationUnit:
  39. case Decl::ExternCContext:
  40. case Decl::Namespace:
  41. case Decl::UnresolvedUsingTypename:
  42. case Decl::ClassTemplateSpecialization:
  43. case Decl::ClassTemplatePartialSpecialization:
  44. case Decl::VarTemplateSpecialization:
  45. case Decl::VarTemplatePartialSpecialization:
  46. case Decl::TemplateTypeParm:
  47. case Decl::UnresolvedUsingValue:
  48. case Decl::NonTypeTemplateParm:
  49. case Decl::CXXMethod:
  50. case Decl::CXXConstructor:
  51. case Decl::CXXDestructor:
  52. case Decl::CXXConversion:
  53. case Decl::Field:
  54. case Decl::MSProperty:
  55. case Decl::IndirectField:
  56. case Decl::ObjCIvar:
  57. case Decl::ObjCAtDefsField:
  58. case Decl::ParmVar:
  59. case Decl::ImplicitParam:
  60. case Decl::ClassTemplate:
  61. case Decl::VarTemplate:
  62. case Decl::FunctionTemplate:
  63. case Decl::TypeAliasTemplate:
  64. case Decl::TemplateTemplateParm:
  65. case Decl::ObjCMethod:
  66. case Decl::ObjCCategory:
  67. case Decl::ObjCProtocol:
  68. case Decl::ObjCInterface:
  69. case Decl::ObjCCategoryImpl:
  70. case Decl::ObjCImplementation:
  71. case Decl::ObjCProperty:
  72. case Decl::ObjCCompatibleAlias:
  73. case Decl::PragmaComment:
  74. case Decl::PragmaDetectMismatch:
  75. case Decl::AccessSpec:
  76. case Decl::LinkageSpec:
  77. case Decl::ObjCPropertyImpl:
  78. case Decl::FileScopeAsm:
  79. case Decl::Friend:
  80. case Decl::FriendTemplate:
  81. case Decl::Block:
  82. case Decl::Captured:
  83. case Decl::ClassScopeFunctionSpecialization:
  84. case Decl::UsingShadow:
  85. case Decl::ConstructorUsingShadow:
  86. case Decl::ObjCTypeParam:
  87. llvm_unreachable("Declaration should not be in declstmts!");
  88. case Decl::Function: // void X();
  89. case Decl::Record: // struct/union/class X;
  90. case Decl::Enum: // enum X;
  91. case Decl::EnumConstant: // enum ? { X = ? }
  92. case Decl::CXXRecord: // struct/union/class X; [C++]
  93. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  94. case Decl::Label: // __label__ x;
  95. case Decl::Import:
  96. case Decl::OMPThreadPrivate:
  97. case Decl::OMPCapturedExpr:
  98. case Decl::Empty:
  99. // None of these decls require codegen support.
  100. return;
  101. case Decl::NamespaceAlias:
  102. if (CGDebugInfo *DI = getDebugInfo())
  103. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  104. return;
  105. case Decl::Using: // using X; [C++]
  106. if (CGDebugInfo *DI = getDebugInfo())
  107. DI->EmitUsingDecl(cast<UsingDecl>(D));
  108. return;
  109. case Decl::UsingDirective: // using namespace X; [C++]
  110. if (CGDebugInfo *DI = getDebugInfo())
  111. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  112. return;
  113. case Decl::Var:
  114. case Decl::Decomposition: {
  115. const VarDecl &VD = cast<VarDecl>(D);
  116. assert(VD.isLocalVarDecl() &&
  117. "Should not see file-scope variables inside a function!");
  118. return EmitVarDecl(VD);
  119. }
  120. case Decl::Binding:
  121. return CGM.ErrorUnsupported(&D, "structured binding");
  122. case Decl::OMPDeclareReduction:
  123. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  124. case Decl::Typedef: // typedef int X;
  125. case Decl::TypeAlias: { // using X = int; [C++0x]
  126. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  127. QualType Ty = TD.getUnderlyingType();
  128. if (Ty->isVariablyModifiedType())
  129. EmitVariablyModifiedType(Ty);
  130. }
  131. }
  132. }
  133. /// EmitVarDecl - This method handles emission of any variable declaration
  134. /// inside a function, including static vars etc.
  135. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  136. if (D.isStaticLocal()) {
  137. llvm::GlobalValue::LinkageTypes Linkage =
  138. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  139. // FIXME: We need to force the emission/use of a guard variable for
  140. // some variables even if we can constant-evaluate them because
  141. // we can't guarantee every translation unit will constant-evaluate them.
  142. return EmitStaticVarDecl(D, Linkage);
  143. }
  144. if (D.hasExternalStorage())
  145. // Don't emit it now, allow it to be emitted lazily on its first use.
  146. return;
  147. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  148. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  149. assert(D.hasLocalStorage());
  150. return EmitAutoVarDecl(D);
  151. }
  152. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  153. if (CGM.getLangOpts().CPlusPlus)
  154. return CGM.getMangledName(&D).str();
  155. // If this isn't C++, we don't need a mangled name, just a pretty one.
  156. assert(!D.isExternallyVisible() && "name shouldn't matter");
  157. std::string ContextName;
  158. const DeclContext *DC = D.getDeclContext();
  159. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  160. DC = cast<DeclContext>(CD->getNonClosureContext());
  161. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  162. ContextName = CGM.getMangledName(FD);
  163. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  164. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  165. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  166. ContextName = OMD->getSelector().getAsString();
  167. else
  168. llvm_unreachable("Unknown context for static var decl");
  169. ContextName += "." + D.getNameAsString();
  170. return ContextName;
  171. }
  172. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  173. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  174. // In general, we don't always emit static var decls once before we reference
  175. // them. It is possible to reference them before emitting the function that
  176. // contains them, and it is possible to emit the containing function multiple
  177. // times.
  178. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  179. return ExistingGV;
  180. QualType Ty = D.getType();
  181. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  182. // Use the label if the variable is renamed with the asm-label extension.
  183. std::string Name;
  184. if (D.hasAttr<AsmLabelAttr>())
  185. Name = getMangledName(&D);
  186. else
  187. Name = getStaticDeclName(*this, D);
  188. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  189. unsigned AddrSpace =
  190. GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
  191. // Local address space cannot have an initializer.
  192. llvm::Constant *Init = nullptr;
  193. if (Ty.getAddressSpace() != LangAS::opencl_local)
  194. Init = EmitNullConstant(Ty);
  195. else
  196. Init = llvm::UndefValue::get(LTy);
  197. llvm::GlobalVariable *GV =
  198. new llvm::GlobalVariable(getModule(), LTy,
  199. Ty.isConstant(getContext()), Linkage,
  200. Init, Name, nullptr,
  201. llvm::GlobalVariable::NotThreadLocal,
  202. AddrSpace);
  203. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  204. setGlobalVisibility(GV, &D);
  205. if (supportsCOMDAT() && GV->isWeakForLinker())
  206. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  207. if (D.getTLSKind())
  208. setTLSMode(GV, D);
  209. if (D.isExternallyVisible()) {
  210. if (D.hasAttr<DLLImportAttr>())
  211. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  212. else if (D.hasAttr<DLLExportAttr>())
  213. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  214. }
  215. // Make sure the result is of the correct type.
  216. unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
  217. llvm::Constant *Addr = GV;
  218. if (AddrSpace != ExpectedAddrSpace) {
  219. llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
  220. Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
  221. }
  222. setStaticLocalDeclAddress(&D, Addr);
  223. // Ensure that the static local gets initialized by making sure the parent
  224. // function gets emitted eventually.
  225. const Decl *DC = cast<Decl>(D.getDeclContext());
  226. // We can't name blocks or captured statements directly, so try to emit their
  227. // parents.
  228. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  229. DC = DC->getNonClosureContext();
  230. // FIXME: Ensure that global blocks get emitted.
  231. if (!DC)
  232. return Addr;
  233. }
  234. GlobalDecl GD;
  235. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  236. GD = GlobalDecl(CD, Ctor_Base);
  237. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  238. GD = GlobalDecl(DD, Dtor_Base);
  239. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  240. GD = GlobalDecl(FD);
  241. else {
  242. // Don't do anything for Obj-C method decls or global closures. We should
  243. // never defer them.
  244. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  245. }
  246. if (GD.getDecl())
  247. (void)GetAddrOfGlobal(GD);
  248. return Addr;
  249. }
  250. /// hasNontrivialDestruction - Determine whether a type's destruction is
  251. /// non-trivial. If so, and the variable uses static initialization, we must
  252. /// register its destructor to run on exit.
  253. static bool hasNontrivialDestruction(QualType T) {
  254. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  255. return RD && !RD->hasTrivialDestructor();
  256. }
  257. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  258. /// global variable that has already been created for it. If the initializer
  259. /// has a different type than GV does, this may free GV and return a different
  260. /// one. Otherwise it just returns GV.
  261. llvm::GlobalVariable *
  262. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  263. llvm::GlobalVariable *GV) {
  264. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  265. // If constant emission failed, then this should be a C++ static
  266. // initializer.
  267. if (!Init) {
  268. if (!getLangOpts().CPlusPlus)
  269. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  270. else if (Builder.GetInsertBlock()) {
  271. // Since we have a static initializer, this global variable can't
  272. // be constant.
  273. GV->setConstant(false);
  274. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  275. }
  276. return GV;
  277. }
  278. // The initializer may differ in type from the global. Rewrite
  279. // the global to match the initializer. (We have to do this
  280. // because some types, like unions, can't be completely represented
  281. // in the LLVM type system.)
  282. if (GV->getType()->getElementType() != Init->getType()) {
  283. llvm::GlobalVariable *OldGV = GV;
  284. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  285. OldGV->isConstant(),
  286. OldGV->getLinkage(), Init, "",
  287. /*InsertBefore*/ OldGV,
  288. OldGV->getThreadLocalMode(),
  289. CGM.getContext().getTargetAddressSpace(D.getType()));
  290. GV->setVisibility(OldGV->getVisibility());
  291. GV->setComdat(OldGV->getComdat());
  292. // Steal the name of the old global
  293. GV->takeName(OldGV);
  294. // Replace all uses of the old global with the new global
  295. llvm::Constant *NewPtrForOldDecl =
  296. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  297. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  298. // Erase the old global, since it is no longer used.
  299. OldGV->eraseFromParent();
  300. }
  301. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  302. GV->setInitializer(Init);
  303. if (hasNontrivialDestruction(D.getType())) {
  304. // We have a constant initializer, but a nontrivial destructor. We still
  305. // need to perform a guarded "initialization" in order to register the
  306. // destructor.
  307. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  308. }
  309. return GV;
  310. }
  311. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  312. llvm::GlobalValue::LinkageTypes Linkage) {
  313. // Check to see if we already have a global variable for this
  314. // declaration. This can happen when double-emitting function
  315. // bodies, e.g. with complete and base constructors.
  316. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  317. CharUnits alignment = getContext().getDeclAlign(&D);
  318. // Store into LocalDeclMap before generating initializer to handle
  319. // circular references.
  320. setAddrOfLocalVar(&D, Address(addr, alignment));
  321. // We can't have a VLA here, but we can have a pointer to a VLA,
  322. // even though that doesn't really make any sense.
  323. // Make sure to evaluate VLA bounds now so that we have them for later.
  324. if (D.getType()->isVariablyModifiedType())
  325. EmitVariablyModifiedType(D.getType());
  326. // Save the type in case adding the initializer forces a type change.
  327. llvm::Type *expectedType = addr->getType();
  328. llvm::GlobalVariable *var =
  329. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  330. // CUDA's local and local static __shared__ variables should not
  331. // have any non-empty initializers. This is ensured by Sema.
  332. // Whatever initializer such variable may have when it gets here is
  333. // a no-op and should not be emitted.
  334. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  335. D.hasAttr<CUDASharedAttr>();
  336. // If this value has an initializer, emit it.
  337. if (D.getInit() && !isCudaSharedVar)
  338. var = AddInitializerToStaticVarDecl(D, var);
  339. var->setAlignment(alignment.getQuantity());
  340. if (D.hasAttr<AnnotateAttr>())
  341. CGM.AddGlobalAnnotations(&D, var);
  342. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  343. var->setSection(SA->getName());
  344. if (D.hasAttr<UsedAttr>())
  345. CGM.addUsedGlobal(var);
  346. // We may have to cast the constant because of the initializer
  347. // mismatch above.
  348. //
  349. // FIXME: It is really dangerous to store this in the map; if anyone
  350. // RAUW's the GV uses of this constant will be invalid.
  351. llvm::Constant *castedAddr =
  352. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  353. if (var != castedAddr)
  354. LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
  355. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  356. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  357. // Emit global variable debug descriptor for static vars.
  358. CGDebugInfo *DI = getDebugInfo();
  359. if (DI &&
  360. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  361. DI->setLocation(D.getLocation());
  362. DI->EmitGlobalVariable(var, &D);
  363. }
  364. }
  365. namespace {
  366. struct DestroyObject final : EHScopeStack::Cleanup {
  367. DestroyObject(Address addr, QualType type,
  368. CodeGenFunction::Destroyer *destroyer,
  369. bool useEHCleanupForArray)
  370. : addr(addr), type(type), destroyer(destroyer),
  371. useEHCleanupForArray(useEHCleanupForArray) {}
  372. Address addr;
  373. QualType type;
  374. CodeGenFunction::Destroyer *destroyer;
  375. bool useEHCleanupForArray;
  376. void Emit(CodeGenFunction &CGF, Flags flags) override {
  377. // Don't use an EH cleanup recursively from an EH cleanup.
  378. bool useEHCleanupForArray =
  379. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  380. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  381. }
  382. };
  383. struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
  384. DestroyNRVOVariable(Address addr,
  385. const CXXDestructorDecl *Dtor,
  386. llvm::Value *NRVOFlag)
  387. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  388. const CXXDestructorDecl *Dtor;
  389. llvm::Value *NRVOFlag;
  390. Address Loc;
  391. void Emit(CodeGenFunction &CGF, Flags flags) override {
  392. // Along the exceptions path we always execute the dtor.
  393. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  394. llvm::BasicBlock *SkipDtorBB = nullptr;
  395. if (NRVO) {
  396. // If we exited via NRVO, we skip the destructor call.
  397. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  398. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  399. llvm::Value *DidNRVO =
  400. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  401. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  402. CGF.EmitBlock(RunDtorBB);
  403. }
  404. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  405. /*ForVirtualBase=*/false,
  406. /*Delegating=*/false,
  407. Loc);
  408. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  409. }
  410. };
  411. struct CallStackRestore final : EHScopeStack::Cleanup {
  412. Address Stack;
  413. CallStackRestore(Address Stack) : Stack(Stack) {}
  414. void Emit(CodeGenFunction &CGF, Flags flags) override {
  415. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  416. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  417. CGF.Builder.CreateCall(F, V);
  418. }
  419. };
  420. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  421. const VarDecl &Var;
  422. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  423. void Emit(CodeGenFunction &CGF, Flags flags) override {
  424. // Compute the address of the local variable, in case it's a
  425. // byref or something.
  426. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  427. Var.getType(), VK_LValue, SourceLocation());
  428. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  429. SourceLocation());
  430. CGF.EmitExtendGCLifetime(value);
  431. }
  432. };
  433. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  434. llvm::Constant *CleanupFn;
  435. const CGFunctionInfo &FnInfo;
  436. const VarDecl &Var;
  437. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  438. const VarDecl *Var)
  439. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  440. void Emit(CodeGenFunction &CGF, Flags flags) override {
  441. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  442. Var.getType(), VK_LValue, SourceLocation());
  443. // Compute the address of the local variable, in case it's a byref
  444. // or something.
  445. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
  446. // In some cases, the type of the function argument will be different from
  447. // the type of the pointer. An example of this is
  448. // void f(void* arg);
  449. // __attribute__((cleanup(f))) void *g;
  450. //
  451. // To fix this we insert a bitcast here.
  452. QualType ArgTy = FnInfo.arg_begin()->type;
  453. llvm::Value *Arg =
  454. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  455. CallArgList Args;
  456. Args.add(RValue::get(Arg),
  457. CGF.getContext().getPointerType(Var.getType()));
  458. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  459. }
  460. };
  461. } // end anonymous namespace
  462. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  463. /// variable with lifetime.
  464. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  465. Address addr,
  466. Qualifiers::ObjCLifetime lifetime) {
  467. switch (lifetime) {
  468. case Qualifiers::OCL_None:
  469. llvm_unreachable("present but none");
  470. case Qualifiers::OCL_ExplicitNone:
  471. // nothing to do
  472. break;
  473. case Qualifiers::OCL_Strong: {
  474. CodeGenFunction::Destroyer *destroyer =
  475. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  476. ? CodeGenFunction::destroyARCStrongPrecise
  477. : CodeGenFunction::destroyARCStrongImprecise);
  478. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  479. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  480. cleanupKind & EHCleanup);
  481. break;
  482. }
  483. case Qualifiers::OCL_Autoreleasing:
  484. // nothing to do
  485. break;
  486. case Qualifiers::OCL_Weak:
  487. // __weak objects always get EH cleanups; otherwise, exceptions
  488. // could cause really nasty crashes instead of mere leaks.
  489. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  490. CodeGenFunction::destroyARCWeak,
  491. /*useEHCleanup*/ true);
  492. break;
  493. }
  494. }
  495. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  496. if (const Expr *e = dyn_cast<Expr>(s)) {
  497. // Skip the most common kinds of expressions that make
  498. // hierarchy-walking expensive.
  499. s = e = e->IgnoreParenCasts();
  500. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  501. return (ref->getDecl() == &var);
  502. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  503. const BlockDecl *block = be->getBlockDecl();
  504. for (const auto &I : block->captures()) {
  505. if (I.getVariable() == &var)
  506. return true;
  507. }
  508. }
  509. }
  510. for (const Stmt *SubStmt : s->children())
  511. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  512. if (SubStmt && isAccessedBy(var, SubStmt))
  513. return true;
  514. return false;
  515. }
  516. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  517. if (!decl) return false;
  518. if (!isa<VarDecl>(decl)) return false;
  519. const VarDecl *var = cast<VarDecl>(decl);
  520. return isAccessedBy(*var, e);
  521. }
  522. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  523. const LValue &destLV, const Expr *init) {
  524. bool needsCast = false;
  525. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  526. switch (castExpr->getCastKind()) {
  527. // Look through casts that don't require representation changes.
  528. case CK_NoOp:
  529. case CK_BitCast:
  530. case CK_BlockPointerToObjCPointerCast:
  531. needsCast = true;
  532. break;
  533. // If we find an l-value to r-value cast from a __weak variable,
  534. // emit this operation as a copy or move.
  535. case CK_LValueToRValue: {
  536. const Expr *srcExpr = castExpr->getSubExpr();
  537. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  538. return false;
  539. // Emit the source l-value.
  540. LValue srcLV = CGF.EmitLValue(srcExpr);
  541. // Handle a formal type change to avoid asserting.
  542. auto srcAddr = srcLV.getAddress();
  543. if (needsCast) {
  544. srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
  545. destLV.getAddress().getElementType());
  546. }
  547. // If it was an l-value, use objc_copyWeak.
  548. if (srcExpr->getValueKind() == VK_LValue) {
  549. CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
  550. } else {
  551. assert(srcExpr->getValueKind() == VK_XValue);
  552. CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
  553. }
  554. return true;
  555. }
  556. // Stop at anything else.
  557. default:
  558. return false;
  559. }
  560. init = castExpr->getSubExpr();
  561. }
  562. return false;
  563. }
  564. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  565. LValue &lvalue,
  566. const VarDecl *var) {
  567. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
  568. }
  569. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  570. LValue lvalue, bool capturedByInit) {
  571. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  572. if (!lifetime) {
  573. llvm::Value *value = EmitScalarExpr(init);
  574. if (capturedByInit)
  575. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  576. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  577. return;
  578. }
  579. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  580. init = DIE->getExpr();
  581. // If we're emitting a value with lifetime, we have to do the
  582. // initialization *before* we leave the cleanup scopes.
  583. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  584. enterFullExpression(ewc);
  585. init = ewc->getSubExpr();
  586. }
  587. CodeGenFunction::RunCleanupsScope Scope(*this);
  588. // We have to maintain the illusion that the variable is
  589. // zero-initialized. If the variable might be accessed in its
  590. // initializer, zero-initialize before running the initializer, then
  591. // actually perform the initialization with an assign.
  592. bool accessedByInit = false;
  593. if (lifetime != Qualifiers::OCL_ExplicitNone)
  594. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  595. if (accessedByInit) {
  596. LValue tempLV = lvalue;
  597. // Drill down to the __block object if necessary.
  598. if (capturedByInit) {
  599. // We can use a simple GEP for this because it can't have been
  600. // moved yet.
  601. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
  602. cast<VarDecl>(D),
  603. /*follow*/ false));
  604. }
  605. auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
  606. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  607. // If __weak, we want to use a barrier under certain conditions.
  608. if (lifetime == Qualifiers::OCL_Weak)
  609. EmitARCInitWeak(tempLV.getAddress(), zero);
  610. // Otherwise just do a simple store.
  611. else
  612. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  613. }
  614. // Emit the initializer.
  615. llvm::Value *value = nullptr;
  616. switch (lifetime) {
  617. case Qualifiers::OCL_None:
  618. llvm_unreachable("present but none");
  619. case Qualifiers::OCL_ExplicitNone:
  620. value = EmitARCUnsafeUnretainedScalarExpr(init);
  621. break;
  622. case Qualifiers::OCL_Strong: {
  623. value = EmitARCRetainScalarExpr(init);
  624. break;
  625. }
  626. case Qualifiers::OCL_Weak: {
  627. // If it's not accessed by the initializer, try to emit the
  628. // initialization with a copy or move.
  629. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  630. return;
  631. }
  632. // No way to optimize a producing initializer into this. It's not
  633. // worth optimizing for, because the value will immediately
  634. // disappear in the common case.
  635. value = EmitScalarExpr(init);
  636. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  637. if (accessedByInit)
  638. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  639. else
  640. EmitARCInitWeak(lvalue.getAddress(), value);
  641. return;
  642. }
  643. case Qualifiers::OCL_Autoreleasing:
  644. value = EmitARCRetainAutoreleaseScalarExpr(init);
  645. break;
  646. }
  647. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  648. // If the variable might have been accessed by its initializer, we
  649. // might have to initialize with a barrier. We have to do this for
  650. // both __weak and __strong, but __weak got filtered out above.
  651. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  652. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  653. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  654. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  655. return;
  656. }
  657. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  658. }
  659. /// EmitScalarInit - Initialize the given lvalue with the given object.
  660. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  661. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  662. if (!lifetime)
  663. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  664. switch (lifetime) {
  665. case Qualifiers::OCL_None:
  666. llvm_unreachable("present but none");
  667. case Qualifiers::OCL_ExplicitNone:
  668. // nothing to do
  669. break;
  670. case Qualifiers::OCL_Strong:
  671. init = EmitARCRetain(lvalue.getType(), init);
  672. break;
  673. case Qualifiers::OCL_Weak:
  674. // Initialize and then skip the primitive store.
  675. EmitARCInitWeak(lvalue.getAddress(), init);
  676. return;
  677. case Qualifiers::OCL_Autoreleasing:
  678. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  679. break;
  680. }
  681. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  682. }
  683. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  684. /// non-zero parts of the specified initializer with equal or fewer than
  685. /// NumStores scalar stores.
  686. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  687. unsigned &NumStores) {
  688. // Zero and Undef never requires any extra stores.
  689. if (isa<llvm::ConstantAggregateZero>(Init) ||
  690. isa<llvm::ConstantPointerNull>(Init) ||
  691. isa<llvm::UndefValue>(Init))
  692. return true;
  693. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  694. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  695. isa<llvm::ConstantExpr>(Init))
  696. return Init->isNullValue() || NumStores--;
  697. // See if we can emit each element.
  698. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  699. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  700. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  701. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  702. return false;
  703. }
  704. return true;
  705. }
  706. if (llvm::ConstantDataSequential *CDS =
  707. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  708. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  709. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  710. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  711. return false;
  712. }
  713. return true;
  714. }
  715. // Anything else is hard and scary.
  716. return false;
  717. }
  718. /// emitStoresForInitAfterMemset - For inits that
  719. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  720. /// stores that would be required.
  721. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  722. bool isVolatile, CGBuilderTy &Builder) {
  723. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  724. "called emitStoresForInitAfterMemset for zero or undef value.");
  725. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  726. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  727. isa<llvm::ConstantExpr>(Init)) {
  728. Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
  729. return;
  730. }
  731. if (llvm::ConstantDataSequential *CDS =
  732. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  733. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  734. llvm::Constant *Elt = CDS->getElementAsConstant(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. return;
  742. }
  743. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  744. "Unknown value type!");
  745. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  746. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  747. // If necessary, get a pointer to the element and emit it.
  748. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  749. emitStoresForInitAfterMemset(
  750. Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
  751. isVolatile, Builder);
  752. }
  753. }
  754. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  755. /// plus some stores to initialize a local variable instead of using a memcpy
  756. /// from a constant global. It is beneficial to use memset if the global is all
  757. /// zeros, or mostly zeros and large.
  758. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  759. uint64_t GlobalSize) {
  760. // If a global is all zeros, always use a memset.
  761. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  762. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  763. // do it if it will require 6 or fewer scalar stores.
  764. // TODO: Should budget depends on the size? Avoiding a large global warrants
  765. // plopping in more stores.
  766. unsigned StoreBudget = 6;
  767. uint64_t SizeLimit = 32;
  768. return GlobalSize > SizeLimit &&
  769. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  770. }
  771. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  772. /// variable declaration with auto, register, or no storage class specifier.
  773. /// These turn into simple stack objects, or GlobalValues depending on target.
  774. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  775. AutoVarEmission emission = EmitAutoVarAlloca(D);
  776. EmitAutoVarInit(emission);
  777. EmitAutoVarCleanups(emission);
  778. }
  779. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  780. /// markers.
  781. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  782. const LangOptions &LangOpts) {
  783. // Asan uses markers for use-after-scope checks.
  784. if (CGOpts.SanitizeAddressUseAfterScope)
  785. return true;
  786. // Disable lifetime markers in msan builds.
  787. // FIXME: Remove this when msan works with lifetime markers.
  788. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  789. return false;
  790. // For now, only in optimized builds.
  791. return CGOpts.OptimizationLevel != 0;
  792. }
  793. /// Emit a lifetime.begin marker if some criteria are satisfied.
  794. /// \return a pointer to the temporary size Value if a marker was emitted, null
  795. /// otherwise
  796. llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
  797. llvm::Value *Addr) {
  798. if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
  799. return nullptr;
  800. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  801. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  802. llvm::CallInst *C =
  803. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  804. C->setDoesNotThrow();
  805. return SizeV;
  806. }
  807. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  808. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  809. llvm::CallInst *C =
  810. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  811. C->setDoesNotThrow();
  812. }
  813. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  814. /// local variable. Does not emit initialization or destruction.
  815. CodeGenFunction::AutoVarEmission
  816. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  817. QualType Ty = D.getType();
  818. AutoVarEmission emission(D);
  819. bool isByRef = D.hasAttr<BlocksAttr>();
  820. emission.IsByRef = isByRef;
  821. CharUnits alignment = getContext().getDeclAlign(&D);
  822. // If the type is variably-modified, emit all the VLA sizes for it.
  823. if (Ty->isVariablyModifiedType())
  824. EmitVariablyModifiedType(Ty);
  825. Address address = Address::invalid();
  826. if (Ty->isConstantSizeType()) {
  827. bool NRVO = getLangOpts().ElideConstructors &&
  828. D.isNRVOVariable();
  829. // If this value is an array or struct with a statically determinable
  830. // constant initializer, there are optimizations we can do.
  831. //
  832. // TODO: We should constant-evaluate the initializer of any variable,
  833. // as long as it is initialized by a constant expression. Currently,
  834. // isConstantInitializer produces wrong answers for structs with
  835. // reference or bitfield members, and a few other cases, and checking
  836. // for POD-ness protects us from some of these.
  837. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  838. (D.isConstexpr() ||
  839. ((Ty.isPODType(getContext()) ||
  840. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  841. D.getInit()->isConstantInitializer(getContext(), false)))) {
  842. // If the variable's a const type, and it's neither an NRVO
  843. // candidate nor a __block variable and has no mutable members,
  844. // emit it as a global instead.
  845. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  846. CGM.isTypeConstant(Ty, true)) {
  847. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  848. // Signal this condition to later callbacks.
  849. emission.Addr = Address::invalid();
  850. assert(emission.wasEmittedAsGlobal());
  851. return emission;
  852. }
  853. // Otherwise, tell the initialization code that we're in this case.
  854. emission.IsConstantAggregate = true;
  855. }
  856. // A normal fixed sized variable becomes an alloca in the entry block,
  857. // unless it's an NRVO variable.
  858. if (NRVO) {
  859. // The named return value optimization: allocate this variable in the
  860. // return slot, so that we can elide the copy when returning this
  861. // variable (C++0x [class.copy]p34).
  862. address = ReturnValue;
  863. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  864. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  865. // Create a flag that is used to indicate when the NRVO was applied
  866. // to this variable. Set it to zero to indicate that NRVO was not
  867. // applied.
  868. llvm::Value *Zero = Builder.getFalse();
  869. Address NRVOFlag =
  870. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
  871. EnsureInsertPoint();
  872. Builder.CreateStore(Zero, NRVOFlag);
  873. // Record the NRVO flag for this variable.
  874. NRVOFlags[&D] = NRVOFlag.getPointer();
  875. emission.NRVOFlag = NRVOFlag.getPointer();
  876. }
  877. }
  878. } else {
  879. CharUnits allocaAlignment;
  880. llvm::Type *allocaTy;
  881. if (isByRef) {
  882. auto &byrefInfo = getBlockByrefInfo(&D);
  883. allocaTy = byrefInfo.Type;
  884. allocaAlignment = byrefInfo.ByrefAlignment;
  885. } else {
  886. allocaTy = ConvertTypeForMem(Ty);
  887. allocaAlignment = alignment;
  888. }
  889. // Create the alloca. Note that we set the name separately from
  890. // building the instruction so that it's there even in no-asserts
  891. // builds.
  892. address = CreateTempAlloca(allocaTy, allocaAlignment);
  893. address.getPointer()->setName(D.getName());
  894. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  895. // the catch parameter starts in the catchpad instruction, and we can't
  896. // insert code in those basic blocks.
  897. bool IsMSCatchParam =
  898. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  899. // Emit a lifetime intrinsic if meaningful. There's no point
  900. // in doing this if we don't have a valid insertion point (?).
  901. if (HaveInsertPoint() && !IsMSCatchParam) {
  902. uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  903. emission.SizeForLifetimeMarkers =
  904. EmitLifetimeStart(size, address.getPointer());
  905. } else {
  906. assert(!emission.useLifetimeMarkers());
  907. }
  908. }
  909. } else {
  910. EnsureInsertPoint();
  911. if (!DidCallStackSave) {
  912. // Save the stack.
  913. Address Stack =
  914. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  915. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  916. llvm::Value *V = Builder.CreateCall(F);
  917. Builder.CreateStore(V, Stack);
  918. DidCallStackSave = true;
  919. // Push a cleanup block and restore the stack there.
  920. // FIXME: in general circumstances, this should be an EH cleanup.
  921. pushStackRestore(NormalCleanup, Stack);
  922. }
  923. llvm::Value *elementCount;
  924. QualType elementType;
  925. std::tie(elementCount, elementType) = getVLASize(Ty);
  926. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  927. // Allocate memory for the array.
  928. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  929. vla->setAlignment(alignment.getQuantity());
  930. address = Address(vla, alignment);
  931. }
  932. setAddrOfLocalVar(&D, address);
  933. emission.Addr = address;
  934. // Emit debug info for local var declaration.
  935. if (HaveInsertPoint())
  936. if (CGDebugInfo *DI = getDebugInfo()) {
  937. if (CGM.getCodeGenOpts().getDebugInfo() >=
  938. codegenoptions::LimitedDebugInfo) {
  939. DI->setLocation(D.getLocation());
  940. DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
  941. }
  942. }
  943. if (D.hasAttr<AnnotateAttr>())
  944. EmitVarAnnotations(&D, address.getPointer());
  945. return emission;
  946. }
  947. /// Determines whether the given __block variable is potentially
  948. /// captured by the given expression.
  949. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  950. // Skip the most common kinds of expressions that make
  951. // hierarchy-walking expensive.
  952. e = e->IgnoreParenCasts();
  953. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  954. const BlockDecl *block = be->getBlockDecl();
  955. for (const auto &I : block->captures()) {
  956. if (I.getVariable() == &var)
  957. return true;
  958. }
  959. // No need to walk into the subexpressions.
  960. return false;
  961. }
  962. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  963. const CompoundStmt *CS = SE->getSubStmt();
  964. for (const auto *BI : CS->body())
  965. if (const auto *E = dyn_cast<Expr>(BI)) {
  966. if (isCapturedBy(var, E))
  967. return true;
  968. }
  969. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  970. // special case declarations
  971. for (const auto *I : DS->decls()) {
  972. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  973. const Expr *Init = VD->getInit();
  974. if (Init && isCapturedBy(var, Init))
  975. return true;
  976. }
  977. }
  978. }
  979. else
  980. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  981. // Later, provide code to poke into statements for capture analysis.
  982. return true;
  983. return false;
  984. }
  985. for (const Stmt *SubStmt : e->children())
  986. if (isCapturedBy(var, cast<Expr>(SubStmt)))
  987. return true;
  988. return false;
  989. }
  990. /// \brief Determine whether the given initializer is trivial in the sense
  991. /// that it requires no code to be generated.
  992. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  993. if (!Init)
  994. return true;
  995. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  996. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  997. if (Constructor->isTrivial() &&
  998. Constructor->isDefaultConstructor() &&
  999. !Construct->requiresZeroInitialization())
  1000. return true;
  1001. return false;
  1002. }
  1003. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1004. assert(emission.Variable && "emission was not valid!");
  1005. // If this was emitted as a global constant, we're done.
  1006. if (emission.wasEmittedAsGlobal()) return;
  1007. const VarDecl &D = *emission.Variable;
  1008. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1009. QualType type = D.getType();
  1010. // If this local has an initializer, emit it now.
  1011. const Expr *Init = D.getInit();
  1012. // If we are at an unreachable point, we don't need to emit the initializer
  1013. // unless it contains a label.
  1014. if (!HaveInsertPoint()) {
  1015. if (!Init || !ContainsLabel(Init)) return;
  1016. EnsureInsertPoint();
  1017. }
  1018. // Initialize the structure of a __block variable.
  1019. if (emission.IsByRef)
  1020. emitByrefStructureInit(emission);
  1021. if (isTrivialInitializer(Init))
  1022. return;
  1023. // Check whether this is a byref variable that's potentially
  1024. // captured and moved by its own initializer. If so, we'll need to
  1025. // emit the initializer first, then copy into the variable.
  1026. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  1027. Address Loc =
  1028. capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
  1029. llvm::Constant *constant = nullptr;
  1030. if (emission.IsConstantAggregate || D.isConstexpr()) {
  1031. assert(!capturedByInit && "constant init contains a capturing block?");
  1032. constant = CGM.EmitConstantInit(D, this);
  1033. }
  1034. if (!constant) {
  1035. LValue lv = MakeAddrLValue(Loc, type);
  1036. lv.setNonGC(true);
  1037. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1038. }
  1039. if (!emission.IsConstantAggregate) {
  1040. // For simple scalar/complex initialization, store the value directly.
  1041. LValue lv = MakeAddrLValue(Loc, type);
  1042. lv.setNonGC(true);
  1043. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1044. }
  1045. // If this is a simple aggregate initialization, we can optimize it
  1046. // in various ways.
  1047. bool isVolatile = type.isVolatileQualified();
  1048. llvm::Value *SizeVal =
  1049. llvm::ConstantInt::get(IntPtrTy,
  1050. getContext().getTypeSizeInChars(type).getQuantity());
  1051. llvm::Type *BP = Int8PtrTy;
  1052. if (Loc.getType() != BP)
  1053. Loc = Builder.CreateBitCast(Loc, BP);
  1054. // If the initializer is all or mostly zeros, codegen with memset then do
  1055. // a few stores afterward.
  1056. if (shouldUseMemSetPlusStoresToInitialize(constant,
  1057. CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
  1058. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1059. isVolatile);
  1060. // Zero and undef don't require a stores.
  1061. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  1062. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  1063. emitStoresForInitAfterMemset(constant, Loc.getPointer(),
  1064. isVolatile, Builder);
  1065. }
  1066. } else {
  1067. // Otherwise, create a temporary global with the initializer then
  1068. // memcpy from the global to the alloca.
  1069. std::string Name = getStaticDeclName(CGM, D);
  1070. llvm::GlobalVariable *GV =
  1071. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  1072. llvm::GlobalValue::PrivateLinkage,
  1073. constant, Name);
  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. }
  1504. Address DeclPtr = Address::invalid();
  1505. bool DoStore = false;
  1506. bool IsScalar = hasScalarEvaluationKind(Ty);
  1507. // If we already have a pointer to the argument, reuse the input pointer.
  1508. if (Arg.isIndirect()) {
  1509. DeclPtr = Arg.getIndirectAddress();
  1510. // If we have a prettier pointer type at this point, bitcast to that.
  1511. unsigned AS = DeclPtr.getType()->getAddressSpace();
  1512. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1513. if (DeclPtr.getType() != IRTy)
  1514. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  1515. // Push a destructor cleanup for this parameter if the ABI requires it.
  1516. // Don't push a cleanup in a thunk for a method that will also emit a
  1517. // cleanup.
  1518. if (!IsScalar && !CurFuncIsThunk &&
  1519. getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1520. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  1521. if (RD && RD->hasNonTrivialDestructor())
  1522. pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
  1523. }
  1524. } else {
  1525. // Otherwise, create a temporary to hold the value.
  1526. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  1527. D.getName() + ".addr");
  1528. DoStore = true;
  1529. }
  1530. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  1531. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  1532. if (IsScalar) {
  1533. Qualifiers qs = Ty.getQualifiers();
  1534. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1535. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1536. // For __strong, it's handled by just skipping the initial retain;
  1537. // otherwise we have to balance out the initial +1 with an extra
  1538. // cleanup to do the release at the end of the function.
  1539. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1540. // 'self' is always formally __strong, but if this is not an
  1541. // init method then we don't want to retain it.
  1542. if (D.isARCPseudoStrong()) {
  1543. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1544. assert(&D == method->getSelfDecl());
  1545. assert(lt == Qualifiers::OCL_Strong);
  1546. assert(qs.hasConst());
  1547. assert(method->getMethodFamily() != OMF_init);
  1548. (void) method;
  1549. lt = Qualifiers::OCL_ExplicitNone;
  1550. }
  1551. if (lt == Qualifiers::OCL_Strong) {
  1552. if (!isConsumed) {
  1553. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1554. // use objc_storeStrong(&dest, value) for retaining the
  1555. // object. But first, store a null into 'dest' because
  1556. // objc_storeStrong attempts to release its old value.
  1557. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1558. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1559. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  1560. DoStore = false;
  1561. }
  1562. else
  1563. // Don't use objc_retainBlock for block pointers, because we
  1564. // don't want to Block_copy something just because we got it
  1565. // as a parameter.
  1566. ArgVal = EmitARCRetainNonBlock(ArgVal);
  1567. }
  1568. } else {
  1569. // Push the cleanup for a consumed parameter.
  1570. if (isConsumed) {
  1571. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1572. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1573. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  1574. precise);
  1575. }
  1576. if (lt == Qualifiers::OCL_Weak) {
  1577. EmitARCInitWeak(DeclPtr, ArgVal);
  1578. DoStore = false; // The weak init is a store, no need to do two.
  1579. }
  1580. }
  1581. // Enter the cleanup scope.
  1582. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1583. }
  1584. }
  1585. // Store the initial value into the alloca.
  1586. if (DoStore)
  1587. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  1588. setAddrOfLocalVar(&D, DeclPtr);
  1589. // Emit debug info for param declaration.
  1590. if (CGDebugInfo *DI = getDebugInfo()) {
  1591. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1592. codegenoptions::LimitedDebugInfo) {
  1593. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  1594. }
  1595. }
  1596. if (D.hasAttr<AnnotateAttr>())
  1597. EmitVarAnnotations(&D, DeclPtr.getPointer());
  1598. }
  1599. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1600. CodeGenFunction *CGF) {
  1601. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  1602. return;
  1603. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  1604. }