CGDecl.cpp 68 KB

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