CGDecl.cpp 69 KB

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