CGDecl.cpp 69 KB

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