CGDecl.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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. case Decl::HLSLBuffer: // HLSL Change
  93. // None of these decls require codegen support.
  94. return;
  95. case Decl::NamespaceAlias:
  96. if (CGDebugInfo *DI = getDebugInfo())
  97. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  98. return;
  99. case Decl::Using: // using X; [C++]
  100. if (CGDebugInfo *DI = getDebugInfo())
  101. DI->EmitUsingDecl(cast<UsingDecl>(D));
  102. return;
  103. case Decl::UsingDirective: // using namespace X; [C++]
  104. if (CGDebugInfo *DI = getDebugInfo())
  105. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  106. return;
  107. case Decl::Var: {
  108. const VarDecl &VD = cast<VarDecl>(D);
  109. assert(VD.isLocalVarDecl() &&
  110. "Should not see file-scope variables inside a function!");
  111. return EmitVarDecl(VD);
  112. }
  113. case Decl::Typedef: // typedef int X;
  114. case Decl::TypeAlias: { // using X = int; [C++0x]
  115. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  116. QualType Ty = TD.getUnderlyingType();
  117. if (Ty->isVariablyModifiedType())
  118. EmitVariablyModifiedType(Ty);
  119. }
  120. }
  121. }
  122. /// EmitVarDecl - This method handles emission of any variable declaration
  123. /// inside a function, including static vars etc.
  124. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  125. if (D.isStaticLocal()) {
  126. llvm::GlobalValue::LinkageTypes Linkage =
  127. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  128. // FIXME: We need to force the emission/use of a guard variable for
  129. // some variables even if we can constant-evaluate them because
  130. // we can't guarantee every translation unit will constant-evaluate them.
  131. return EmitStaticVarDecl(D, Linkage);
  132. }
  133. // HLSL Change Begin - treat local constant as static.
  134. // Global variable will be generated instead of alloca.
  135. if (D.getType().isConstQualified() && D.isLocalVarDecl()) {
  136. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  137. // Only create global when has constant init.
  138. if (Init) {
  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.
  749. // Enable this will require SROA_HLSL to support the intrinsic.
  750. // Will do it later when support lifetime marker in HLSL.
  751. if (CGM.getLangOpts().HLSL)
  752. return nullptr;
  753. // HLSL Change Ends
  754. // Disable lifetime markers in msan builds.
  755. // FIXME: Remove this when msan works with lifetime markers.
  756. if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
  757. return nullptr;
  758. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  759. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  760. llvm::CallInst *C =
  761. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  762. C->setDoesNotThrow();
  763. return SizeV;
  764. }
  765. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  766. Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
  767. llvm::CallInst *C =
  768. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  769. C->setDoesNotThrow();
  770. }
  771. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  772. /// local variable. Does not emit initialization or destruction.
  773. CodeGenFunction::AutoVarEmission
  774. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  775. QualType Ty = D.getType();
  776. AutoVarEmission emission(D);
  777. bool isByRef = D.hasAttr<BlocksAttr>();
  778. emission.IsByRef = isByRef;
  779. CharUnits alignment = getContext().getDeclAlign(&D);
  780. emission.Alignment = alignment;
  781. // If the type is variably-modified, emit all the VLA sizes for it.
  782. if (Ty->isVariablyModifiedType())
  783. EmitVariablyModifiedType(Ty);
  784. llvm::Value *DeclPtr;
  785. if (Ty->isConstantSizeType()) {
  786. bool NRVO = getLangOpts().ElideConstructors &&
  787. D.isNRVOVariable();
  788. // If this value is an array or struct with a statically determinable
  789. // constant initializer, there are optimizations we can do.
  790. //
  791. // TODO: We should constant-evaluate the initializer of any variable,
  792. // as long as it is initialized by a constant expression. Currently,
  793. // isConstantInitializer produces wrong answers for structs with
  794. // reference or bitfield members, and a few other cases, and checking
  795. // for POD-ness protects us from some of these.
  796. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  797. // HLSL Change Begins.
  798. // HLSL will not evaluate constant array init list.
  799. // So skip it here.
  800. !getLangOpts().HLSL &&
  801. // HLSL Change Ends.
  802. (D.isConstexpr() ||
  803. ((Ty.isPODType(getContext()) ||
  804. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  805. D.getInit()->isConstantInitializer(getContext(), false)))) {
  806. // If the variable's a const type, and it's neither an NRVO
  807. // candidate nor a __block variable and has no mutable members,
  808. // emit it as a global instead.
  809. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  810. CGM.isTypeConstant(Ty, true)) {
  811. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  812. emission.Address = nullptr; // signal this condition to later callbacks
  813. assert(emission.wasEmittedAsGlobal());
  814. return emission;
  815. }
  816. // Otherwise, tell the initialization code that we're in this case.
  817. emission.IsConstantAggregate = true;
  818. }
  819. // A normal fixed sized variable becomes an alloca in the entry block,
  820. // unless it's an NRVO variable.
  821. llvm::Type *LTy = ConvertTypeForMem(Ty);
  822. if (NRVO) {
  823. // The named return value optimization: allocate this variable in the
  824. // return slot, so that we can elide the copy when returning this
  825. // variable (C++0x [class.copy]p34).
  826. DeclPtr = ReturnValue;
  827. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  828. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  829. // Create a flag that is used to indicate when the NRVO was applied
  830. // to this variable. Set it to zero to indicate that NRVO was not
  831. // applied.
  832. llvm::Value *Zero = Builder.getFalse();
  833. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  834. EnsureInsertPoint();
  835. Builder.CreateStore(Zero, NRVOFlag);
  836. // Record the NRVO flag for this variable.
  837. NRVOFlags[&D] = NRVOFlag;
  838. emission.NRVOFlag = NRVOFlag;
  839. }
  840. }
  841. } else {
  842. if (isByRef)
  843. LTy = BuildByRefType(&D);
  844. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  845. Alloc->setName(D.getNameForIR()); // HLSL Change: use getNameForIR rather than getName
  846. CharUnits allocaAlignment = alignment;
  847. if (isByRef)
  848. allocaAlignment = std::max(allocaAlignment,
  849. getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
  850. Alloc->setAlignment(allocaAlignment.getQuantity());
  851. DeclPtr = Alloc;
  852. // Emit a lifetime intrinsic if meaningful. There's no point
  853. // in doing this if we don't have a valid insertion point (?).
  854. uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
  855. if (HaveInsertPoint()) {
  856. emission.SizeForLifetimeMarkers = EmitLifetimeStart(size, Alloc);
  857. } else {
  858. assert(!emission.useLifetimeMarkers());
  859. }
  860. }
  861. } else {
  862. EnsureInsertPoint();
  863. if (!DidCallStackSave) {
  864. // Save the stack.
  865. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  866. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  867. llvm::Value *V = Builder.CreateCall(F);
  868. Builder.CreateStore(V, Stack);
  869. DidCallStackSave = true;
  870. // Push a cleanup block and restore the stack there.
  871. // FIXME: in general circumstances, this should be an EH cleanup.
  872. pushStackRestore(NormalCleanup, Stack);
  873. }
  874. llvm::Value *elementCount;
  875. QualType elementType;
  876. std::tie(elementCount, elementType) = getVLASize(Ty);
  877. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  878. // Allocate memory for the array.
  879. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  880. vla->setAlignment(alignment.getQuantity());
  881. DeclPtr = vla;
  882. }
  883. llvm::Value *&DMEntry = LocalDeclMap[&D];
  884. assert(!DMEntry && "Decl already exists in localdeclmap!");
  885. DMEntry = DeclPtr;
  886. emission.Address = DeclPtr;
  887. // Emit debug info for local var declaration.
  888. if (HaveInsertPoint())
  889. if (CGDebugInfo *DI = getDebugInfo()) {
  890. if (CGM.getCodeGenOpts().getDebugInfo()
  891. >= CodeGenOptions::LimitedDebugInfo) {
  892. DI->setLocation(D.getLocation());
  893. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  894. }
  895. }
  896. if (D.hasAttr<AnnotateAttr>())
  897. EmitVarAnnotations(&D, emission.Address);
  898. CGM.getHLSLRuntime().FinishAutoVar(*this, D, emission.Address); // HLSL Change
  899. return emission;
  900. }
  901. /// Determines whether the given __block variable is potentially
  902. /// captured by the given expression.
  903. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  904. // Skip the most common kinds of expressions that make
  905. // hierarchy-walking expensive.
  906. e = e->IgnoreParenCasts();
  907. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  908. const BlockDecl *block = be->getBlockDecl();
  909. for (const auto &I : block->captures()) {
  910. if (I.getVariable() == &var)
  911. return true;
  912. }
  913. // No need to walk into the subexpressions.
  914. return false;
  915. }
  916. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  917. const CompoundStmt *CS = SE->getSubStmt();
  918. for (const auto *BI : CS->body())
  919. if (const auto *E = dyn_cast<Expr>(BI)) {
  920. if (isCapturedBy(var, E))
  921. return true;
  922. }
  923. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  924. // special case declarations
  925. for (const auto *I : DS->decls()) {
  926. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  927. const Expr *Init = VD->getInit();
  928. if (Init && isCapturedBy(var, Init))
  929. return true;
  930. }
  931. }
  932. }
  933. else
  934. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  935. // Later, provide code to poke into statements for capture analysis.
  936. return true;
  937. return false;
  938. }
  939. for (const Stmt *SubStmt : e->children())
  940. if (isCapturedBy(var, cast<Expr>(SubStmt)))
  941. return true;
  942. return false;
  943. }
  944. /// \brief Determine whether the given initializer is trivial in the sense
  945. /// that it requires no code to be generated.
  946. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  947. if (!Init)
  948. return true;
  949. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  950. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  951. if (Constructor->isTrivial() &&
  952. Constructor->isDefaultConstructor() &&
  953. !Construct->requiresZeroInitialization())
  954. return true;
  955. return false;
  956. }
  957. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  958. assert(emission.Variable && "emission was not valid!");
  959. // If this was emitted as a global constant, we're done.
  960. if (emission.wasEmittedAsGlobal()) return;
  961. const VarDecl &D = *emission.Variable;
  962. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  963. QualType type = D.getType();
  964. // If this local has an initializer, emit it now.
  965. const Expr *Init = D.getInit();
  966. // If we are at an unreachable point, we don't need to emit the initializer
  967. // unless it contains a label.
  968. if (!HaveInsertPoint()) {
  969. if (!Init || !ContainsLabel(Init)) return;
  970. EnsureInsertPoint();
  971. }
  972. // Initialize the structure of a __block variable.
  973. if (emission.IsByRef)
  974. emitByrefStructureInit(emission);
  975. if (isTrivialInitializer(Init))
  976. return;
  977. CharUnits alignment = emission.Alignment;
  978. // Check whether this is a byref variable that's potentially
  979. // captured and moved by its own initializer. If so, we'll need to
  980. // emit the initializer first, then copy into the variable.
  981. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  982. llvm::Value *Loc =
  983. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  984. llvm::Constant *constant = nullptr;
  985. if (emission.IsConstantAggregate || D.isConstexpr()) {
  986. assert(!capturedByInit && "constant init contains a capturing block?");
  987. constant = CGM.EmitConstantInit(D, this);
  988. }
  989. if (!constant) {
  990. LValue lv = MakeAddrLValue(Loc, type, alignment);
  991. lv.setNonGC(true);
  992. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  993. }
  994. if (!emission.IsConstantAggregate) {
  995. // For simple scalar/complex initialization, store the value directly.
  996. LValue lv = MakeAddrLValue(Loc, type, alignment);
  997. lv.setNonGC(true);
  998. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  999. }
  1000. // HLSL Change Begins
  1001. if (getLangOpts().HLSL) {
  1002. // create a temporary global with the initializer then
  1003. // Store from the global to the alloca.
  1004. std::string Name = getStaticDeclName(CGM, D);
  1005. llvm::GlobalVariable *GV =
  1006. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  1007. llvm::GlobalValue::PrivateLinkage,
  1008. constant, Name);
  1009. GV->setAlignment(alignment.getQuantity());
  1010. GV->setUnnamedAddr(true);
  1011. // Don't generate memcpy for hlsl.
  1012. CGM.getHLSLRuntime().EmitHLSLAggregateCopy(*this, GV, Loc, type);
  1013. return;
  1014. }
  1015. // HLSL Change Ends
  1016. // If this is a simple aggregate initialization, we can optimize it
  1017. // in various ways.
  1018. bool isVolatile = type.isVolatileQualified();
  1019. llvm::Value *SizeVal =
  1020. llvm::ConstantInt::get(IntPtrTy,
  1021. getContext().getTypeSizeInChars(type).getQuantity());
  1022. llvm::Type *BP = Int8PtrTy;
  1023. if (Loc->getType() != BP)
  1024. Loc = Builder.CreateBitCast(Loc, BP);
  1025. // If the initializer is all or mostly zeros, codegen with memset then do
  1026. // a few stores afterward.
  1027. if (shouldUseMemSetPlusStoresToInitialize(constant,
  1028. CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
  1029. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1030. alignment.getQuantity(), isVolatile);
  1031. // Zero and undef don't require a stores.
  1032. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  1033. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  1034. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  1035. }
  1036. } else {
  1037. // Otherwise, create a temporary global with the initializer then
  1038. // memcpy from the global to the alloca.
  1039. std::string Name = getStaticDeclName(CGM, D);
  1040. llvm::GlobalVariable *GV =
  1041. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  1042. llvm::GlobalValue::PrivateLinkage,
  1043. constant, Name);
  1044. GV->setAlignment(alignment.getQuantity());
  1045. GV->setUnnamedAddr(true);
  1046. llvm::Value *SrcPtr = GV;
  1047. if (SrcPtr->getType() != BP)
  1048. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  1049. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  1050. isVolatile);
  1051. }
  1052. }
  1053. /// Emit an expression as an initializer for a variable at the given
  1054. /// location. The expression is not necessarily the normal
  1055. /// initializer for the variable, and the address is not necessarily
  1056. /// its normal location.
  1057. ///
  1058. /// \param init the initializing expression
  1059. /// \param var the variable to act as if we're initializing
  1060. /// \param loc the address to initialize; its type is a pointer
  1061. /// to the LLVM mapping of the variable's type
  1062. /// \param alignment the alignment of the address
  1063. /// \param capturedByInit true if the variable is a __block variable
  1064. /// whose address is potentially changed by the initializer
  1065. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1066. LValue lvalue, bool capturedByInit) {
  1067. QualType type = D->getType();
  1068. if (type->isReferenceType()) {
  1069. RValue rvalue = EmitReferenceBindingToExpr(init);
  1070. if (capturedByInit)
  1071. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1072. EmitStoreThroughLValue(rvalue, lvalue, true);
  1073. return;
  1074. }
  1075. switch (getEvaluationKind(type)) {
  1076. case TEK_Scalar:
  1077. EmitScalarInit(init, D, lvalue, capturedByInit);
  1078. return;
  1079. case TEK_Complex: {
  1080. ComplexPairTy complex = EmitComplexExpr(init);
  1081. if (capturedByInit)
  1082. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1083. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1084. return;
  1085. }
  1086. case TEK_Aggregate:
  1087. if (type->isAtomicType()) {
  1088. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1089. } else {
  1090. // TODO: how can we delay here if D is captured by its initializer?
  1091. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1092. AggValueSlot::IsDestructed,
  1093. AggValueSlot::DoesNotNeedGCBarriers,
  1094. AggValueSlot::IsNotAliased));
  1095. }
  1096. return;
  1097. }
  1098. llvm_unreachable("bad evaluation kind");
  1099. }
  1100. /// Enter a destroy cleanup for the given local variable.
  1101. void CodeGenFunction::emitAutoVarTypeCleanup(
  1102. const CodeGenFunction::AutoVarEmission &emission,
  1103. QualType::DestructionKind dtorKind) {
  1104. assert(dtorKind != QualType::DK_none);
  1105. // Note that for __block variables, we want to destroy the
  1106. // original stack object, not the possibly forwarded object.
  1107. llvm::Value *addr = emission.getObjectAddress(*this);
  1108. const VarDecl *var = emission.Variable;
  1109. QualType type = var->getType();
  1110. CleanupKind cleanupKind = NormalAndEHCleanup;
  1111. CodeGenFunction::Destroyer *destroyer = nullptr;
  1112. switch (dtorKind) {
  1113. case QualType::DK_none:
  1114. llvm_unreachable("no cleanup for trivially-destructible variable");
  1115. case QualType::DK_cxx_destructor:
  1116. // If there's an NRVO flag on the emission, we need a different
  1117. // cleanup.
  1118. if (emission.NRVOFlag) {
  1119. assert(!type->isArrayType());
  1120. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1121. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  1122. emission.NRVOFlag);
  1123. return;
  1124. }
  1125. break;
  1126. case QualType::DK_objc_strong_lifetime:
  1127. // Suppress cleanups for pseudo-strong variables.
  1128. if (var->isARCPseudoStrong()) return;
  1129. // Otherwise, consider whether to use an EH cleanup or not.
  1130. cleanupKind = getARCCleanupKind();
  1131. // Use the imprecise destroyer by default.
  1132. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1133. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1134. break;
  1135. case QualType::DK_objc_weak_lifetime:
  1136. break;
  1137. }
  1138. // If we haven't chosen a more specific destroyer, use the default.
  1139. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1140. // Use an EH cleanup in array destructors iff the destructor itself
  1141. // is being pushed as an EH cleanup.
  1142. bool useEHCleanup = (cleanupKind & EHCleanup);
  1143. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1144. useEHCleanup);
  1145. }
  1146. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1147. assert(emission.Variable && "emission was not valid!");
  1148. // If this was emitted as a global constant, we're done.
  1149. if (emission.wasEmittedAsGlobal()) return;
  1150. // If we don't have an insertion point, we're done. Sema prevents
  1151. // us from jumping into any of these scopes anyway.
  1152. if (!HaveInsertPoint()) return;
  1153. const VarDecl &D = *emission.Variable;
  1154. // Make sure we call @llvm.lifetime.end. This needs to happen
  1155. // *last*, so the cleanup needs to be pushed *first*.
  1156. if (emission.useLifetimeMarkers()) {
  1157. EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
  1158. emission.getAllocatedAddress(),
  1159. emission.getSizeForLifetimeMarkers());
  1160. EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
  1161. cleanup.setLifetimeMarker();
  1162. }
  1163. // Check the type for a cleanup.
  1164. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1165. emitAutoVarTypeCleanup(emission, dtorKind);
  1166. // In GC mode, honor objc_precise_lifetime.
  1167. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1168. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1169. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1170. }
  1171. // Handle the cleanup attribute.
  1172. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1173. const FunctionDecl *FD = CA->getFunctionDecl();
  1174. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1175. assert(F && "Could not find function!");
  1176. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1177. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1178. }
  1179. // If this is a block variable, call _Block_object_destroy
  1180. // (on the unforwarded address).
  1181. if (emission.IsByRef)
  1182. enterByrefCleanup(emission);
  1183. }
  1184. CodeGenFunction::Destroyer *
  1185. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1186. switch (kind) {
  1187. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1188. case QualType::DK_cxx_destructor:
  1189. return destroyCXXObject;
  1190. case QualType::DK_objc_strong_lifetime:
  1191. return destroyARCStrongPrecise;
  1192. case QualType::DK_objc_weak_lifetime:
  1193. return destroyARCWeak;
  1194. }
  1195. llvm_unreachable("Unknown DestructionKind");
  1196. }
  1197. /// pushEHDestroy - Push the standard destructor for the given type as
  1198. /// an EH-only cleanup.
  1199. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1200. llvm::Value *addr, QualType type) {
  1201. assert(dtorKind && "cannot push destructor for trivial type");
  1202. assert(needsEHCleanup(dtorKind));
  1203. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1204. }
  1205. /// pushDestroy - Push the standard destructor for the given type as
  1206. /// at least a normal cleanup.
  1207. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1208. llvm::Value *addr, QualType type) {
  1209. assert(dtorKind && "cannot push destructor for trivial type");
  1210. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1211. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1212. cleanupKind & EHCleanup);
  1213. }
  1214. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1215. QualType type, Destroyer *destroyer,
  1216. bool useEHCleanupForArray) {
  1217. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1218. destroyer, useEHCleanupForArray);
  1219. }
  1220. void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
  1221. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1222. }
  1223. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1224. CleanupKind cleanupKind, llvm::Value *addr, QualType type,
  1225. Destroyer *destroyer, bool useEHCleanupForArray) {
  1226. assert(!isInConditionalBranch() &&
  1227. "performing lifetime extension from within conditional");
  1228. // Push an EH-only cleanup for the object now.
  1229. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1230. // around in case a temporary's destructor throws an exception.
  1231. if (cleanupKind & EHCleanup)
  1232. EHStack.pushCleanup<DestroyObject>(
  1233. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1234. destroyer, useEHCleanupForArray);
  1235. // Remember that we need to push a full cleanup for the object at the
  1236. // end of the full-expression.
  1237. pushCleanupAfterFullExpr<DestroyObject>(
  1238. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1239. }
  1240. /// emitDestroy - Immediately perform the destruction of the given
  1241. /// object.
  1242. ///
  1243. /// \param addr - the address of the object; a type*
  1244. /// \param type - the type of the object; if an array type, all
  1245. /// objects are destroyed in reverse order
  1246. /// \param destroyer - the function to call to destroy individual
  1247. /// elements
  1248. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1249. /// used when destroying array elements, in case one of the
  1250. /// destructions throws an exception
  1251. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1252. Destroyer *destroyer,
  1253. bool useEHCleanupForArray) {
  1254. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1255. if (!arrayType)
  1256. return destroyer(*this, addr, type);
  1257. llvm::Value *begin = addr;
  1258. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1259. // Normally we have to check whether the array is zero-length.
  1260. bool checkZeroLength = true;
  1261. // But if the array length is constant, we can suppress that.
  1262. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1263. // ...and if it's constant zero, we can just skip the entire thing.
  1264. if (constLength->isZero()) return;
  1265. checkZeroLength = false;
  1266. }
  1267. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1268. emitArrayDestroy(begin, end, type, destroyer,
  1269. checkZeroLength, useEHCleanupForArray);
  1270. }
  1271. /// emitArrayDestroy - Destroys all the elements of the given array,
  1272. /// beginning from last to first. The array cannot be zero-length.
  1273. ///
  1274. /// \param begin - a type* denoting the first element of the array
  1275. /// \param end - a type* denoting one past the end of the array
  1276. /// \param type - the element type of the array
  1277. /// \param destroyer - the function to call to destroy elements
  1278. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1279. /// the remaining elements in case the destruction of a single
  1280. /// element throws
  1281. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1282. llvm::Value *end,
  1283. QualType type,
  1284. Destroyer *destroyer,
  1285. bool checkZeroLength,
  1286. bool useEHCleanup) {
  1287. assert(!type->isArrayType());
  1288. // The basic structure here is a do-while loop, because we don't
  1289. // need to check for the zero-element case.
  1290. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1291. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1292. if (checkZeroLength) {
  1293. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1294. "arraydestroy.isempty");
  1295. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1296. }
  1297. // Enter the loop body, making that address the current address.
  1298. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1299. EmitBlock(bodyBB);
  1300. llvm::PHINode *elementPast =
  1301. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1302. elementPast->addIncoming(end, entryBB);
  1303. // Shift the address back by one element.
  1304. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1305. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1306. "arraydestroy.element");
  1307. if (useEHCleanup)
  1308. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1309. // Perform the actual destruction there.
  1310. destroyer(*this, element, type);
  1311. if (useEHCleanup)
  1312. PopCleanupBlock();
  1313. // Check whether we've reached the end.
  1314. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1315. Builder.CreateCondBr(done, doneBB, bodyBB);
  1316. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1317. // Done.
  1318. EmitBlock(doneBB);
  1319. }
  1320. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1321. /// emitArrayDestroy, the element type here may still be an array type.
  1322. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1323. llvm::Value *begin, llvm::Value *end,
  1324. QualType type,
  1325. CodeGenFunction::Destroyer *destroyer) {
  1326. // If the element type is itself an array, drill down.
  1327. unsigned arrayDepth = 0;
  1328. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1329. // VLAs don't require a GEP index to walk into.
  1330. if (!isa<VariableArrayType>(arrayType))
  1331. arrayDepth++;
  1332. type = arrayType->getElementType();
  1333. }
  1334. if (arrayDepth) {
  1335. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1336. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1337. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1338. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1339. }
  1340. // Destroy the array. We don't ever need an EH cleanup because we
  1341. // assume that we're in an EH cleanup ourselves, so a throwing
  1342. // destructor causes an immediate terminate.
  1343. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1344. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1345. }
  1346. namespace {
  1347. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1348. /// array destroy where the end pointer is regularly determined and
  1349. /// does not need to be loaded from a local.
  1350. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1351. llvm::Value *ArrayBegin;
  1352. llvm::Value *ArrayEnd;
  1353. QualType ElementType;
  1354. CodeGenFunction::Destroyer *Destroyer;
  1355. public:
  1356. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1357. QualType elementType,
  1358. CodeGenFunction::Destroyer *destroyer)
  1359. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1360. ElementType(elementType), Destroyer(destroyer) {}
  1361. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1362. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1363. ElementType, Destroyer);
  1364. }
  1365. };
  1366. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1367. /// partial array destroy where the end pointer is irregularly
  1368. /// determined and must be loaded from a local.
  1369. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1370. llvm::Value *ArrayBegin;
  1371. llvm::Value *ArrayEndPointer;
  1372. QualType ElementType;
  1373. CodeGenFunction::Destroyer *Destroyer;
  1374. public:
  1375. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1376. llvm::Value *arrayEndPointer,
  1377. QualType elementType,
  1378. CodeGenFunction::Destroyer *destroyer)
  1379. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1380. ElementType(elementType), Destroyer(destroyer) {}
  1381. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1382. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1383. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1384. ElementType, Destroyer);
  1385. }
  1386. };
  1387. }
  1388. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1389. /// already-constructed elements of the given array. The cleanup
  1390. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1391. ///
  1392. /// \param elementType - the immediate element type of the array;
  1393. /// possibly still an array type
  1394. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1395. llvm::Value *arrayEndPointer,
  1396. QualType elementType,
  1397. Destroyer *destroyer) {
  1398. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1399. arrayBegin, arrayEndPointer,
  1400. elementType, destroyer);
  1401. }
  1402. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1403. /// already-constructed elements of the given array. The cleanup
  1404. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1405. ///
  1406. /// \param elementType - the immediate element type of the array;
  1407. /// possibly still an array type
  1408. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1409. llvm::Value *arrayEnd,
  1410. QualType elementType,
  1411. Destroyer *destroyer) {
  1412. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1413. arrayBegin, arrayEnd,
  1414. elementType, destroyer);
  1415. }
  1416. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1417. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1418. if (LifetimeStartFn) return LifetimeStartFn;
  1419. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1420. llvm::Intrinsic::lifetime_start);
  1421. return LifetimeStartFn;
  1422. }
  1423. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1424. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1425. if (LifetimeEndFn) return LifetimeEndFn;
  1426. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1427. llvm::Intrinsic::lifetime_end);
  1428. return LifetimeEndFn;
  1429. }
  1430. namespace {
  1431. /// A cleanup to perform a release of an object at the end of a
  1432. /// function. This is used to balance out the incoming +1 of a
  1433. /// ns_consumed argument when we can't reasonably do that just by
  1434. /// not doing the initial retain for a __block argument.
  1435. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1436. ConsumeARCParameter(llvm::Value *param,
  1437. ARCPreciseLifetime_t precise)
  1438. : Param(param), Precise(precise) {}
  1439. llvm::Value *Param;
  1440. ARCPreciseLifetime_t Precise;
  1441. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1442. CGF.EmitARCRelease(Param, Precise);
  1443. }
  1444. };
  1445. }
  1446. /// Emit an alloca (or GlobalValue depending on target)
  1447. /// for the specified parameter and set up LocalDeclMap.
  1448. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1449. bool ArgIsPointer, unsigned ArgNo) {
  1450. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1451. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1452. "Invalid argument to EmitParmDecl");
  1453. Arg->setName(D.getName());
  1454. QualType Ty = D.getType();
  1455. // HLSL Change Begin - add noalias for all out param.
  1456. if (Ty.isRestrictQualified() && isa<llvm::Argument>(Arg)) {
  1457. llvm::Argument *AI = cast<llvm::Argument>(Arg);
  1458. if (!AI->hasNoAliasAttr())
  1459. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
  1460. llvm::Attribute::NoAlias));
  1461. }
  1462. // HLSL Change End
  1463. // Use better IR generation for certain implicit parameters.
  1464. if (isa<ImplicitParamDecl>(D)) {
  1465. #if 1 // HLSL Change - no support for blocks
  1466. assert(!BlockInfo && "HLSL does not support blocks");
  1467. #else
  1468. // The only implicit argument a block has is its literal.
  1469. if (BlockInfo) {
  1470. LocalDeclMap[&D] = Arg;
  1471. llvm::Value *LocalAddr = nullptr;
  1472. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1473. // Allocate a stack slot to let the debug info survive the RA.
  1474. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1475. D.getName() + ".addr");
  1476. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1477. LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
  1478. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1479. LocalAddr = Builder.CreateLoad(Alloc);
  1480. }
  1481. if (CGDebugInfo *DI = getDebugInfo()) {
  1482. if (CGM.getCodeGenOpts().getDebugInfo()
  1483. >= CodeGenOptions::LimitedDebugInfo) {
  1484. DI->setLocation(D.getLocation());
  1485. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
  1486. LocalAddr, Builder);
  1487. }
  1488. }
  1489. return;
  1490. }
  1491. #endif // HLSL Change - no support for blocks.
  1492. }
  1493. llvm::Value *DeclPtr;
  1494. bool DoStore = false;
  1495. bool IsScalar = hasScalarEvaluationKind(Ty);
  1496. CharUnits Align = getContext().getDeclAlign(&D);
  1497. // If we already have a pointer to the argument, reuse the input pointer.
  1498. if (ArgIsPointer) {
  1499. // If we have a prettier pointer type at this point, bitcast to that.
  1500. unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
  1501. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1502. DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
  1503. D.getName());
  1504. // Push a destructor cleanup for this parameter if the ABI requires it.
  1505. // Don't push a cleanup in a thunk for a method that will also emit a
  1506. // cleanup.
  1507. if (!IsScalar && !CurFuncIsThunk &&
  1508. getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1509. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  1510. if (RD && RD->hasNonTrivialDestructor())
  1511. pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
  1512. }
  1513. } else {
  1514. // HLSL Change Starts
  1515. if (getLangOpts().HLSL && Arg->getType()->isPointerTy()) {
  1516. // HLSL doesn't have pointer.
  1517. // Only case pointer type will generated is this pointer for methods.
  1518. // Don't store this pointer, just use the parameter directly.
  1519. if (Ty->isPointerType())
  1520. DoStore = false;
  1521. // For out parameter, this could happen too.
  1522. // Because the parameter is reference type.
  1523. // Just use the Arg directly, not store it to a temp alloca.
  1524. DoStore = false;
  1525. DeclPtr = Arg;
  1526. }
  1527. // HLSL Change Ends
  1528. else {
  1529. // Otherwise, create a temporary to hold the value.
  1530. llvm::AllocaInst *Alloc =
  1531. CreateTempAlloca(ConvertTypeForMem(Ty), D.getName() + ".addr");
  1532. Alloc->setAlignment(Align.getQuantity());
  1533. DeclPtr = Alloc;
  1534. DoStore = true;
  1535. }
  1536. }
  1537. LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
  1538. if (IsScalar) {
  1539. Qualifiers qs = Ty.getQualifiers();
  1540. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1541. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1542. // For __strong, it's handled by just skipping the initial retain;
  1543. // otherwise we have to balance out the initial +1 with an extra
  1544. // cleanup to do the release at the end of the function.
  1545. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1546. // 'self' is always formally __strong, but if this is not an
  1547. // init method then we don't want to retain it.
  1548. if (D.isARCPseudoStrong()) {
  1549. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1550. assert(&D == method->getSelfDecl());
  1551. assert(lt == Qualifiers::OCL_Strong);
  1552. assert(qs.hasConst());
  1553. assert(method->getMethodFamily() != OMF_init);
  1554. (void) method;
  1555. lt = Qualifiers::OCL_ExplicitNone;
  1556. }
  1557. if (lt == Qualifiers::OCL_Strong) {
  1558. if (!isConsumed) {
  1559. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1560. // use objc_storeStrong(&dest, value) for retaining the
  1561. // object. But first, store a null into 'dest' because
  1562. // objc_storeStrong attempts to release its old value.
  1563. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1564. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1565. EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
  1566. DoStore = false;
  1567. }
  1568. else
  1569. // Don't use objc_retainBlock for block pointers, because we
  1570. // don't want to Block_copy something just because we got it
  1571. // as a parameter.
  1572. Arg = EmitARCRetainNonBlock(Arg);
  1573. }
  1574. } else {
  1575. // Push the cleanup for a consumed parameter.
  1576. if (isConsumed) {
  1577. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1578. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1579. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
  1580. precise);
  1581. }
  1582. if (lt == Qualifiers::OCL_Weak) {
  1583. EmitARCInitWeak(DeclPtr, Arg);
  1584. DoStore = false; // The weak init is a store, no need to do two.
  1585. }
  1586. }
  1587. // Enter the cleanup scope.
  1588. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1589. }
  1590. }
  1591. // Store the initial value into the alloca.
  1592. if (DoStore)
  1593. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1594. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1595. assert(!DMEntry && "Decl already exists in localdeclmap!");
  1596. DMEntry = DeclPtr;
  1597. // Emit debug info for param declaration.
  1598. if (CGDebugInfo *DI = getDebugInfo()) {
  1599. if (CGM.getCodeGenOpts().getDebugInfo()
  1600. >= CodeGenOptions::LimitedDebugInfo) {
  1601. // HLSL Change Begins.
  1602. // Use the Arg directly instead of DeclPtr for HLSL.
  1603. // The DeclPtr will be promoted in later pass.
  1604. DI->EmitDeclareOfArgVariable(&D, Arg, ArgNo, Builder);
  1605. // HLSL Change Ends.
  1606. }
  1607. }
  1608. if (D.hasAttr<AnnotateAttr>())
  1609. EmitVarAnnotations(&D, DeclPtr);
  1610. }