CGDecl.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220
  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 "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGCleanup.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGOpenCLRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "ConstantEmitter.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/CharUnits.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclOpenMP.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/CodeGen/CGFunctionInfo.h"
  31. #include "clang/Frontend/CodeGenOptions.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/GlobalVariable.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/Type.h"
  36. using namespace clang;
  37. using namespace CodeGen;
  38. void CodeGenFunction::EmitDecl(const Decl &D) {
  39. switch (D.getKind()) {
  40. case Decl::BuiltinTemplate:
  41. case Decl::TranslationUnit:
  42. case Decl::ExternCContext:
  43. case Decl::Namespace:
  44. case Decl::UnresolvedUsingTypename:
  45. case Decl::ClassTemplateSpecialization:
  46. case Decl::ClassTemplatePartialSpecialization:
  47. case Decl::VarTemplateSpecialization:
  48. case Decl::VarTemplatePartialSpecialization:
  49. case Decl::TemplateTypeParm:
  50. case Decl::UnresolvedUsingValue:
  51. case Decl::NonTypeTemplateParm:
  52. case Decl::CXXDeductionGuide:
  53. case Decl::CXXMethod:
  54. case Decl::CXXConstructor:
  55. case Decl::CXXDestructor:
  56. case Decl::CXXConversion:
  57. case Decl::Field:
  58. case Decl::MSProperty:
  59. case Decl::IndirectField:
  60. case Decl::ObjCIvar:
  61. case Decl::ObjCAtDefsField:
  62. case Decl::ParmVar:
  63. case Decl::ImplicitParam:
  64. case Decl::ClassTemplate:
  65. case Decl::VarTemplate:
  66. case Decl::FunctionTemplate:
  67. case Decl::TypeAliasTemplate:
  68. case Decl::TemplateTemplateParm:
  69. case Decl::ObjCMethod:
  70. case Decl::ObjCCategory:
  71. case Decl::ObjCProtocol:
  72. case Decl::ObjCInterface:
  73. case Decl::ObjCCategoryImpl:
  74. case Decl::ObjCImplementation:
  75. case Decl::ObjCProperty:
  76. case Decl::ObjCCompatibleAlias:
  77. case Decl::PragmaComment:
  78. case Decl::PragmaDetectMismatch:
  79. case Decl::AccessSpec:
  80. case Decl::LinkageSpec:
  81. case Decl::Export:
  82. case Decl::ObjCPropertyImpl:
  83. case Decl::FileScopeAsm:
  84. case Decl::Friend:
  85. case Decl::FriendTemplate:
  86. case Decl::Block:
  87. case Decl::Captured:
  88. case Decl::ClassScopeFunctionSpecialization:
  89. case Decl::UsingShadow:
  90. case Decl::ConstructorUsingShadow:
  91. case Decl::ObjCTypeParam:
  92. case Decl::Binding:
  93. llvm_unreachable("Declaration should not be in declstmts!");
  94. case Decl::Function: // void X();
  95. case Decl::Record: // struct/union/class X;
  96. case Decl::Enum: // enum X;
  97. case Decl::EnumConstant: // enum ? { X = ? }
  98. case Decl::CXXRecord: // struct/union/class X; [C++]
  99. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  100. case Decl::Label: // __label__ x;
  101. case Decl::Import:
  102. case Decl::OMPThreadPrivate:
  103. case Decl::OMPCapturedExpr:
  104. case Decl::Empty:
  105. // None of these decls require codegen support.
  106. return;
  107. case Decl::NamespaceAlias:
  108. if (CGDebugInfo *DI = getDebugInfo())
  109. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  110. return;
  111. case Decl::Using: // using X; [C++]
  112. if (CGDebugInfo *DI = getDebugInfo())
  113. DI->EmitUsingDecl(cast<UsingDecl>(D));
  114. return;
  115. case Decl::UsingPack:
  116. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  117. EmitDecl(*Using);
  118. return;
  119. case Decl::UsingDirective: // using namespace X; [C++]
  120. if (CGDebugInfo *DI = getDebugInfo())
  121. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  122. return;
  123. case Decl::Var:
  124. case Decl::Decomposition: {
  125. const VarDecl &VD = cast<VarDecl>(D);
  126. assert(VD.isLocalVarDecl() &&
  127. "Should not see file-scope variables inside a function!");
  128. EmitVarDecl(VD);
  129. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  130. for (auto *B : DD->bindings())
  131. if (auto *HD = B->getHoldingVar())
  132. EmitVarDecl(*HD);
  133. return;
  134. }
  135. case Decl::OMPDeclareReduction:
  136. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  137. case Decl::Typedef: // typedef int X;
  138. case Decl::TypeAlias: { // using X = int; [C++0x]
  139. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  140. QualType Ty = TD.getUnderlyingType();
  141. if (Ty->isVariablyModifiedType())
  142. EmitVariablyModifiedType(Ty);
  143. }
  144. }
  145. }
  146. /// EmitVarDecl - This method handles emission of any variable declaration
  147. /// inside a function, including static vars etc.
  148. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  149. if (D.hasExternalStorage())
  150. // Don't emit it now, allow it to be emitted lazily on its first use.
  151. return;
  152. // Some function-scope variable does not have static storage but still
  153. // needs to be emitted like a static variable, e.g. a function-scope
  154. // variable in constant address space in OpenCL.
  155. if (D.getStorageDuration() != SD_Automatic) {
  156. // Static sampler variables translated to function calls.
  157. if (D.getType()->isSamplerT())
  158. return;
  159. llvm::GlobalValue::LinkageTypes Linkage =
  160. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  161. // FIXME: We need to force the emission/use of a guard variable for
  162. // some variables even if we can constant-evaluate them because
  163. // we can't guarantee every translation unit will constant-evaluate them.
  164. return EmitStaticVarDecl(D, Linkage);
  165. }
  166. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  167. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  168. assert(D.hasLocalStorage());
  169. return EmitAutoVarDecl(D);
  170. }
  171. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  172. if (CGM.getLangOpts().CPlusPlus)
  173. return CGM.getMangledName(&D).str();
  174. // If this isn't C++, we don't need a mangled name, just a pretty one.
  175. assert(!D.isExternallyVisible() && "name shouldn't matter");
  176. std::string ContextName;
  177. const DeclContext *DC = D.getDeclContext();
  178. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  179. DC = cast<DeclContext>(CD->getNonClosureContext());
  180. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  181. ContextName = CGM.getMangledName(FD);
  182. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  183. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  184. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  185. ContextName = OMD->getSelector().getAsString();
  186. else
  187. llvm_unreachable("Unknown context for static var decl");
  188. ContextName += "." + D.getNameAsString();
  189. return ContextName;
  190. }
  191. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  192. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  193. // In general, we don't always emit static var decls once before we reference
  194. // them. It is possible to reference them before emitting the function that
  195. // contains them, and it is possible to emit the containing function multiple
  196. // times.
  197. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  198. return ExistingGV;
  199. QualType Ty = D.getType();
  200. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  201. // Use the label if the variable is renamed with the asm-label extension.
  202. std::string Name;
  203. if (D.hasAttr<AsmLabelAttr>())
  204. Name = getMangledName(&D);
  205. else
  206. Name = getStaticDeclName(*this, D);
  207. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  208. LangAS AS = GetGlobalVarAddressSpace(&D);
  209. unsigned TargetAS = getContext().getTargetAddressSpace(AS);
  210. // OpenCL variables in local address space and CUDA shared
  211. // variables cannot have an initializer.
  212. llvm::Constant *Init = nullptr;
  213. if (Ty.getAddressSpace() == LangAS::opencl_local ||
  214. D.hasAttr<CUDASharedAttr>())
  215. Init = llvm::UndefValue::get(LTy);
  216. else
  217. Init = EmitNullConstant(Ty);
  218. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  219. getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
  220. nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  221. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  222. if (supportsCOMDAT() && GV->isWeakForLinker())
  223. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  224. if (D.getTLSKind())
  225. setTLSMode(GV, D);
  226. setGVProperties(GV, &D);
  227. // Make sure the result is of the correct type.
  228. LangAS ExpectedAS = Ty.getAddressSpace();
  229. llvm::Constant *Addr = GV;
  230. if (AS != ExpectedAS) {
  231. Addr = getTargetCodeGenInfo().performAddrSpaceCast(
  232. *this, GV, AS, ExpectedAS,
  233. LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
  234. }
  235. setStaticLocalDeclAddress(&D, Addr);
  236. // Ensure that the static local gets initialized by making sure the parent
  237. // function gets emitted eventually.
  238. const Decl *DC = cast<Decl>(D.getDeclContext());
  239. // We can't name blocks or captured statements directly, so try to emit their
  240. // parents.
  241. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  242. DC = DC->getNonClosureContext();
  243. // FIXME: Ensure that global blocks get emitted.
  244. if (!DC)
  245. return Addr;
  246. }
  247. GlobalDecl GD;
  248. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  249. GD = GlobalDecl(CD, Ctor_Base);
  250. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  251. GD = GlobalDecl(DD, Dtor_Base);
  252. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  253. GD = GlobalDecl(FD);
  254. else {
  255. // Don't do anything for Obj-C method decls or global closures. We should
  256. // never defer them.
  257. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  258. }
  259. if (GD.getDecl()) {
  260. // Disable emission of the parent function for the OpenMP device codegen.
  261. CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
  262. (void)GetAddrOfGlobal(GD);
  263. }
  264. return Addr;
  265. }
  266. /// hasNontrivialDestruction - Determine whether a type's destruction is
  267. /// non-trivial. If so, and the variable uses static initialization, we must
  268. /// register its destructor to run on exit.
  269. static bool hasNontrivialDestruction(QualType T) {
  270. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  271. return RD && !RD->hasTrivialDestructor();
  272. }
  273. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  274. /// global variable that has already been created for it. If the initializer
  275. /// has a different type than GV does, this may free GV and return a different
  276. /// one. Otherwise it just returns GV.
  277. llvm::GlobalVariable *
  278. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  279. llvm::GlobalVariable *GV) {
  280. ConstantEmitter emitter(*this);
  281. llvm::Constant *Init = emitter.tryEmitForInitializer(D);
  282. // If constant emission failed, then this should be a C++ static
  283. // initializer.
  284. if (!Init) {
  285. if (!getLangOpts().CPlusPlus)
  286. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  287. else if (HaveInsertPoint()) {
  288. // Since we have a static initializer, this global variable can't
  289. // be constant.
  290. GV->setConstant(false);
  291. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  292. }
  293. return GV;
  294. }
  295. // The initializer may differ in type from the global. Rewrite
  296. // the global to match the initializer. (We have to do this
  297. // because some types, like unions, can't be completely represented
  298. // in the LLVM type system.)
  299. if (GV->getType()->getElementType() != Init->getType()) {
  300. llvm::GlobalVariable *OldGV = GV;
  301. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  302. OldGV->isConstant(),
  303. OldGV->getLinkage(), Init, "",
  304. /*InsertBefore*/ OldGV,
  305. OldGV->getThreadLocalMode(),
  306. CGM.getContext().getTargetAddressSpace(D.getType()));
  307. GV->setVisibility(OldGV->getVisibility());
  308. GV->setDSOLocal(OldGV->isDSOLocal());
  309. GV->setComdat(OldGV->getComdat());
  310. // Steal the name of the old global
  311. GV->takeName(OldGV);
  312. // Replace all uses of the old global with the new global
  313. llvm::Constant *NewPtrForOldDecl =
  314. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  315. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  316. // Erase the old global, since it is no longer used.
  317. OldGV->eraseFromParent();
  318. }
  319. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  320. GV->setInitializer(Init);
  321. emitter.finalize(GV);
  322. if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
  323. // We have a constant initializer, but a nontrivial destructor. We still
  324. // need to perform a guarded "initialization" in order to register the
  325. // destructor.
  326. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  327. }
  328. return GV;
  329. }
  330. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  331. llvm::GlobalValue::LinkageTypes Linkage) {
  332. // Check to see if we already have a global variable for this
  333. // declaration. This can happen when double-emitting function
  334. // bodies, e.g. with complete and base constructors.
  335. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  336. CharUnits alignment = getContext().getDeclAlign(&D);
  337. // Store into LocalDeclMap before generating initializer to handle
  338. // circular references.
  339. setAddrOfLocalVar(&D, Address(addr, alignment));
  340. // We can't have a VLA here, but we can have a pointer to a VLA,
  341. // even though that doesn't really make any sense.
  342. // Make sure to evaluate VLA bounds now so that we have them for later.
  343. if (D.getType()->isVariablyModifiedType())
  344. EmitVariablyModifiedType(D.getType());
  345. // Save the type in case adding the initializer forces a type change.
  346. llvm::Type *expectedType = addr->getType();
  347. llvm::GlobalVariable *var =
  348. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  349. // CUDA's local and local static __shared__ variables should not
  350. // have any non-empty initializers. This is ensured by Sema.
  351. // Whatever initializer such variable may have when it gets here is
  352. // a no-op and should not be emitted.
  353. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  354. D.hasAttr<CUDASharedAttr>();
  355. // If this value has an initializer, emit it.
  356. if (D.getInit() && !isCudaSharedVar)
  357. var = AddInitializerToStaticVarDecl(D, var);
  358. var->setAlignment(alignment.getQuantity());
  359. if (D.hasAttr<AnnotateAttr>())
  360. CGM.AddGlobalAnnotations(&D, var);
  361. if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
  362. var->addAttribute("bss-section", SA->getName());
  363. if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
  364. var->addAttribute("data-section", SA->getName());
  365. if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
  366. var->addAttribute("rodata-section", SA->getName());
  367. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  368. var->setSection(SA->getName());
  369. if (D.hasAttr<UsedAttr>())
  370. CGM.addUsedGlobal(var);
  371. // We may have to cast the constant because of the initializer
  372. // mismatch above.
  373. //
  374. // FIXME: It is really dangerous to store this in the map; if anyone
  375. // RAUW's the GV uses of this constant will be invalid.
  376. llvm::Constant *castedAddr =
  377. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  378. if (var != castedAddr)
  379. LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
  380. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  381. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  382. // Emit global variable debug descriptor for static vars.
  383. CGDebugInfo *DI = getDebugInfo();
  384. if (DI &&
  385. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  386. DI->setLocation(D.getLocation());
  387. DI->EmitGlobalVariable(var, &D);
  388. }
  389. }
  390. namespace {
  391. struct DestroyObject final : EHScopeStack::Cleanup {
  392. DestroyObject(Address addr, QualType type,
  393. CodeGenFunction::Destroyer *destroyer,
  394. bool useEHCleanupForArray)
  395. : addr(addr), type(type), destroyer(destroyer),
  396. useEHCleanupForArray(useEHCleanupForArray) {}
  397. Address addr;
  398. QualType type;
  399. CodeGenFunction::Destroyer *destroyer;
  400. bool useEHCleanupForArray;
  401. void Emit(CodeGenFunction &CGF, Flags flags) override {
  402. // Don't use an EH cleanup recursively from an EH cleanup.
  403. bool useEHCleanupForArray =
  404. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  405. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  406. }
  407. };
  408. template <class Derived>
  409. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  410. DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
  411. : NRVOFlag(NRVOFlag), Loc(addr) {}
  412. llvm::Value *NRVOFlag;
  413. Address Loc;
  414. void Emit(CodeGenFunction &CGF, Flags flags) override {
  415. // Along the exceptions path we always execute the dtor.
  416. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  417. llvm::BasicBlock *SkipDtorBB = nullptr;
  418. if (NRVO) {
  419. // If we exited via NRVO, we skip the destructor call.
  420. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  421. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  422. llvm::Value *DidNRVO =
  423. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  424. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  425. CGF.EmitBlock(RunDtorBB);
  426. }
  427. static_cast<Derived *>(this)->emitDestructorCall(CGF);
  428. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  429. }
  430. virtual ~DestroyNRVOVariable() = default;
  431. };
  432. struct DestroyNRVOVariableCXX final
  433. : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
  434. DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
  435. llvm::Value *NRVOFlag)
  436. : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
  437. Dtor(Dtor) {}
  438. const CXXDestructorDecl *Dtor;
  439. void emitDestructorCall(CodeGenFunction &CGF) {
  440. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  441. /*ForVirtualBase=*/false,
  442. /*Delegating=*/false, Loc);
  443. }
  444. };
  445. struct DestroyNRVOVariableC final
  446. : DestroyNRVOVariable<DestroyNRVOVariableC> {
  447. DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
  448. : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
  449. QualType Ty;
  450. void emitDestructorCall(CodeGenFunction &CGF) {
  451. CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
  452. }
  453. };
  454. struct CallStackRestore final : EHScopeStack::Cleanup {
  455. Address Stack;
  456. CallStackRestore(Address Stack) : Stack(Stack) {}
  457. void Emit(CodeGenFunction &CGF, Flags flags) override {
  458. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  459. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  460. CGF.Builder.CreateCall(F, V);
  461. }
  462. };
  463. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  464. const VarDecl &Var;
  465. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  466. void Emit(CodeGenFunction &CGF, Flags flags) override {
  467. // Compute the address of the local variable, in case it's a
  468. // byref or something.
  469. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  470. Var.getType(), VK_LValue, SourceLocation());
  471. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  472. SourceLocation());
  473. CGF.EmitExtendGCLifetime(value);
  474. }
  475. };
  476. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  477. llvm::Constant *CleanupFn;
  478. const CGFunctionInfo &FnInfo;
  479. const VarDecl &Var;
  480. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  481. const VarDecl *Var)
  482. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  483. void Emit(CodeGenFunction &CGF, Flags flags) override {
  484. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  485. Var.getType(), VK_LValue, SourceLocation());
  486. // Compute the address of the local variable, in case it's a byref
  487. // or something.
  488. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
  489. // In some cases, the type of the function argument will be different from
  490. // the type of the pointer. An example of this is
  491. // void f(void* arg);
  492. // __attribute__((cleanup(f))) void *g;
  493. //
  494. // To fix this we insert a bitcast here.
  495. QualType ArgTy = FnInfo.arg_begin()->type;
  496. llvm::Value *Arg =
  497. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  498. CallArgList Args;
  499. Args.add(RValue::get(Arg),
  500. CGF.getContext().getPointerType(Var.getType()));
  501. auto Callee = CGCallee::forDirect(CleanupFn);
  502. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  503. }
  504. };
  505. } // end anonymous namespace
  506. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  507. /// variable with lifetime.
  508. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  509. Address addr,
  510. Qualifiers::ObjCLifetime lifetime) {
  511. switch (lifetime) {
  512. case Qualifiers::OCL_None:
  513. llvm_unreachable("present but none");
  514. case Qualifiers::OCL_ExplicitNone:
  515. // nothing to do
  516. break;
  517. case Qualifiers::OCL_Strong: {
  518. CodeGenFunction::Destroyer *destroyer =
  519. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  520. ? CodeGenFunction::destroyARCStrongPrecise
  521. : CodeGenFunction::destroyARCStrongImprecise);
  522. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  523. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  524. cleanupKind & EHCleanup);
  525. break;
  526. }
  527. case Qualifiers::OCL_Autoreleasing:
  528. // nothing to do
  529. break;
  530. case Qualifiers::OCL_Weak:
  531. // __weak objects always get EH cleanups; otherwise, exceptions
  532. // could cause really nasty crashes instead of mere leaks.
  533. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  534. CodeGenFunction::destroyARCWeak,
  535. /*useEHCleanup*/ true);
  536. break;
  537. }
  538. }
  539. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  540. if (const Expr *e = dyn_cast<Expr>(s)) {
  541. // Skip the most common kinds of expressions that make
  542. // hierarchy-walking expensive.
  543. s = e = e->IgnoreParenCasts();
  544. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  545. return (ref->getDecl() == &var);
  546. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  547. const BlockDecl *block = be->getBlockDecl();
  548. for (const auto &I : block->captures()) {
  549. if (I.getVariable() == &var)
  550. return true;
  551. }
  552. }
  553. }
  554. for (const Stmt *SubStmt : s->children())
  555. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  556. if (SubStmt && isAccessedBy(var, SubStmt))
  557. return true;
  558. return false;
  559. }
  560. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  561. if (!decl) return false;
  562. if (!isa<VarDecl>(decl)) return false;
  563. const VarDecl *var = cast<VarDecl>(decl);
  564. return isAccessedBy(*var, e);
  565. }
  566. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  567. const LValue &destLV, const Expr *init) {
  568. bool needsCast = false;
  569. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  570. switch (castExpr->getCastKind()) {
  571. // Look through casts that don't require representation changes.
  572. case CK_NoOp:
  573. case CK_BitCast:
  574. case CK_BlockPointerToObjCPointerCast:
  575. needsCast = true;
  576. break;
  577. // If we find an l-value to r-value cast from a __weak variable,
  578. // emit this operation as a copy or move.
  579. case CK_LValueToRValue: {
  580. const Expr *srcExpr = castExpr->getSubExpr();
  581. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  582. return false;
  583. // Emit the source l-value.
  584. LValue srcLV = CGF.EmitLValue(srcExpr);
  585. // Handle a formal type change to avoid asserting.
  586. auto srcAddr = srcLV.getAddress();
  587. if (needsCast) {
  588. srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
  589. destLV.getAddress().getElementType());
  590. }
  591. // If it was an l-value, use objc_copyWeak.
  592. if (srcExpr->getValueKind() == VK_LValue) {
  593. CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
  594. } else {
  595. assert(srcExpr->getValueKind() == VK_XValue);
  596. CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
  597. }
  598. return true;
  599. }
  600. // Stop at anything else.
  601. default:
  602. return false;
  603. }
  604. init = castExpr->getSubExpr();
  605. }
  606. return false;
  607. }
  608. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  609. LValue &lvalue,
  610. const VarDecl *var) {
  611. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
  612. }
  613. void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
  614. SourceLocation Loc) {
  615. if (!SanOpts.has(SanitizerKind::NullabilityAssign))
  616. return;
  617. auto Nullability = LHS.getType()->getNullability(getContext());
  618. if (!Nullability || *Nullability != NullabilityKind::NonNull)
  619. return;
  620. // Check if the right hand side of the assignment is nonnull, if the left
  621. // hand side must be nonnull.
  622. SanitizerScope SanScope(this);
  623. llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
  624. llvm::Constant *StaticData[] = {
  625. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
  626. llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
  627. llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
  628. EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
  629. SanitizerHandler::TypeMismatch, StaticData, RHS);
  630. }
  631. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  632. LValue lvalue, bool capturedByInit) {
  633. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  634. if (!lifetime) {
  635. llvm::Value *value = EmitScalarExpr(init);
  636. if (capturedByInit)
  637. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  638. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  639. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  640. return;
  641. }
  642. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  643. init = DIE->getExpr();
  644. // If we're emitting a value with lifetime, we have to do the
  645. // initialization *before* we leave the cleanup scopes.
  646. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  647. enterFullExpression(ewc);
  648. init = ewc->getSubExpr();
  649. }
  650. CodeGenFunction::RunCleanupsScope Scope(*this);
  651. // We have to maintain the illusion that the variable is
  652. // zero-initialized. If the variable might be accessed in its
  653. // initializer, zero-initialize before running the initializer, then
  654. // actually perform the initialization with an assign.
  655. bool accessedByInit = false;
  656. if (lifetime != Qualifiers::OCL_ExplicitNone)
  657. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  658. if (accessedByInit) {
  659. LValue tempLV = lvalue;
  660. // Drill down to the __block object if necessary.
  661. if (capturedByInit) {
  662. // We can use a simple GEP for this because it can't have been
  663. // moved yet.
  664. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
  665. cast<VarDecl>(D),
  666. /*follow*/ false));
  667. }
  668. auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
  669. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  670. // If __weak, we want to use a barrier under certain conditions.
  671. if (lifetime == Qualifiers::OCL_Weak)
  672. EmitARCInitWeak(tempLV.getAddress(), zero);
  673. // Otherwise just do a simple store.
  674. else
  675. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  676. }
  677. // Emit the initializer.
  678. llvm::Value *value = nullptr;
  679. switch (lifetime) {
  680. case Qualifiers::OCL_None:
  681. llvm_unreachable("present but none");
  682. case Qualifiers::OCL_ExplicitNone:
  683. value = EmitARCUnsafeUnretainedScalarExpr(init);
  684. break;
  685. case Qualifiers::OCL_Strong: {
  686. value = EmitARCRetainScalarExpr(init);
  687. break;
  688. }
  689. case Qualifiers::OCL_Weak: {
  690. // If it's not accessed by the initializer, try to emit the
  691. // initialization with a copy or move.
  692. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  693. return;
  694. }
  695. // No way to optimize a producing initializer into this. It's not
  696. // worth optimizing for, because the value will immediately
  697. // disappear in the common case.
  698. value = EmitScalarExpr(init);
  699. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  700. if (accessedByInit)
  701. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  702. else
  703. EmitARCInitWeak(lvalue.getAddress(), value);
  704. return;
  705. }
  706. case Qualifiers::OCL_Autoreleasing:
  707. value = EmitARCRetainAutoreleaseScalarExpr(init);
  708. break;
  709. }
  710. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  711. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  712. // If the variable might have been accessed by its initializer, we
  713. // might have to initialize with a barrier. We have to do this for
  714. // both __weak and __strong, but __weak got filtered out above.
  715. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  716. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  717. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  718. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  719. return;
  720. }
  721. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  722. }
  723. /// Decide whether we can emit the non-zero parts of the specified initializer
  724. /// with equal or fewer than NumStores scalar stores.
  725. static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
  726. unsigned &NumStores) {
  727. // Zero and Undef never requires any extra stores.
  728. if (isa<llvm::ConstantAggregateZero>(Init) ||
  729. isa<llvm::ConstantPointerNull>(Init) ||
  730. isa<llvm::UndefValue>(Init))
  731. return true;
  732. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  733. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  734. isa<llvm::ConstantExpr>(Init))
  735. return Init->isNullValue() || NumStores--;
  736. // See if we can emit each element.
  737. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  738. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  739. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  740. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  741. return false;
  742. }
  743. return true;
  744. }
  745. if (llvm::ConstantDataSequential *CDS =
  746. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  747. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  748. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  749. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  750. return false;
  751. }
  752. return true;
  753. }
  754. // Anything else is hard and scary.
  755. return false;
  756. }
  757. /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
  758. /// the scalar stores that would be required.
  759. static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
  760. llvm::Constant *Init, Address Loc,
  761. bool isVolatile, CGBuilderTy &Builder) {
  762. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  763. "called emitStoresForInitAfterBZero for zero or undef value.");
  764. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  765. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  766. isa<llvm::ConstantExpr>(Init)) {
  767. Builder.CreateStore(Init, Loc, isVolatile);
  768. return;
  769. }
  770. if (llvm::ConstantDataSequential *CDS =
  771. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  772. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  773. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  774. // If necessary, get a pointer to the element and emit it.
  775. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  776. emitStoresForInitAfterBZero(
  777. CGM, Elt,
  778. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
  779. isVolatile, Builder);
  780. }
  781. return;
  782. }
  783. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  784. "Unknown value type!");
  785. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  786. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  787. // If necessary, get a pointer to the element and emit it.
  788. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  789. emitStoresForInitAfterBZero(
  790. CGM, Elt,
  791. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
  792. isVolatile, Builder);
  793. }
  794. }
  795. /// Decide whether we should use bzero plus some stores to initialize a local
  796. /// variable instead of using a memcpy from a constant global. It is beneficial
  797. /// to use bzero if the global is all zeros, or mostly zeros and large.
  798. static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
  799. uint64_t GlobalSize) {
  800. // If a global is all zeros, always use a bzero.
  801. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  802. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  803. // do it if it will require 6 or fewer scalar stores.
  804. // TODO: Should budget depends on the size? Avoiding a large global warrants
  805. // plopping in more stores.
  806. unsigned StoreBudget = 6;
  807. uint64_t SizeLimit = 32;
  808. return GlobalSize > SizeLimit &&
  809. canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
  810. }
  811. /// A byte pattern.
  812. ///
  813. /// Can be "any" pattern if the value was padding or known to be undef.
  814. /// Can be "none" pattern if a sequence doesn't exist.
  815. class BytePattern {
  816. uint8_t Val;
  817. enum class ValueType : uint8_t { Specific, Any, None } Type;
  818. BytePattern(ValueType Type) : Type(Type) {}
  819. public:
  820. BytePattern(uint8_t Value) : Val(Value), Type(ValueType::Specific) {}
  821. static BytePattern Any() { return BytePattern(ValueType::Any); }
  822. static BytePattern None() { return BytePattern(ValueType::None); }
  823. bool isAny() const { return Type == ValueType::Any; }
  824. bool isNone() const { return Type == ValueType::None; }
  825. bool isValued() const { return Type == ValueType::Specific; }
  826. uint8_t getValue() const {
  827. assert(isValued());
  828. return Val;
  829. }
  830. BytePattern merge(const BytePattern Other) const {
  831. if (isNone() || Other.isNone())
  832. return None();
  833. if (isAny())
  834. return Other;
  835. if (Other.isAny())
  836. return *this;
  837. if (getValue() == Other.getValue())
  838. return *this;
  839. return None();
  840. }
  841. };
  842. /// Figures out whether the constant can be initialized with memset.
  843. static BytePattern constantIsRepeatedBytePattern(llvm::Constant *C) {
  844. if (isa<llvm::ConstantAggregateZero>(C) || isa<llvm::ConstantPointerNull>(C))
  845. return BytePattern(0x00);
  846. if (isa<llvm::UndefValue>(C))
  847. return BytePattern::Any();
  848. if (isa<llvm::ConstantInt>(C)) {
  849. auto *Int = cast<llvm::ConstantInt>(C);
  850. if (Int->getBitWidth() % 8 != 0)
  851. return BytePattern::None();
  852. const llvm::APInt &Value = Int->getValue();
  853. if (Value.isSplat(8))
  854. return BytePattern(Value.getLoBits(8).getLimitedValue());
  855. return BytePattern::None();
  856. }
  857. if (isa<llvm::ConstantFP>(C)) {
  858. auto *FP = cast<llvm::ConstantFP>(C);
  859. llvm::APInt Bits = FP->getValueAPF().bitcastToAPInt();
  860. if (Bits.getBitWidth() % 8 != 0)
  861. return BytePattern::None();
  862. if (!Bits.isSplat(8))
  863. return BytePattern::None();
  864. return BytePattern(Bits.getLimitedValue() & 0xFF);
  865. }
  866. if (isa<llvm::ConstantVector>(C)) {
  867. llvm::Constant *Splat = cast<llvm::ConstantVector>(C)->getSplatValue();
  868. if (Splat)
  869. return constantIsRepeatedBytePattern(Splat);
  870. return BytePattern::None();
  871. }
  872. if (isa<llvm::ConstantArray>(C) || isa<llvm::ConstantStruct>(C)) {
  873. BytePattern Pattern(BytePattern::Any());
  874. for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
  875. llvm::Constant *Elt = cast<llvm::Constant>(C->getOperand(I));
  876. Pattern = Pattern.merge(constantIsRepeatedBytePattern(Elt));
  877. if (Pattern.isNone())
  878. return Pattern;
  879. }
  880. return Pattern;
  881. }
  882. if (llvm::ConstantDataSequential *CDS =
  883. dyn_cast<llvm::ConstantDataSequential>(C)) {
  884. BytePattern Pattern(BytePattern::Any());
  885. for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
  886. llvm::Constant *Elt = CDS->getElementAsConstant(I);
  887. Pattern = Pattern.merge(constantIsRepeatedBytePattern(Elt));
  888. if (Pattern.isNone())
  889. return Pattern;
  890. }
  891. return Pattern;
  892. }
  893. // BlockAddress, ConstantExpr, and everything else is scary.
  894. return BytePattern::None();
  895. }
  896. /// Decide whether we should use memset to initialize a local variable instead
  897. /// of using a memcpy from a constant global. Assumes we've already decided to
  898. /// not user bzero.
  899. /// FIXME We could be more clever, as we are for bzero above, and generate
  900. /// memset followed by stores. It's unclear that's worth the effort.
  901. static BytePattern shouldUseMemSetToInitialize(llvm::Constant *Init,
  902. uint64_t GlobalSize) {
  903. uint64_t SizeLimit = 32;
  904. if (GlobalSize <= SizeLimit)
  905. return BytePattern::None();
  906. return constantIsRepeatedBytePattern(Init);
  907. }
  908. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  909. /// variable declaration with auto, register, or no storage class specifier.
  910. /// These turn into simple stack objects, or GlobalValues depending on target.
  911. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  912. AutoVarEmission emission = EmitAutoVarAlloca(D);
  913. EmitAutoVarInit(emission);
  914. EmitAutoVarCleanups(emission);
  915. }
  916. /// Emit a lifetime.begin marker if some criteria are satisfied.
  917. /// \return a pointer to the temporary size Value if a marker was emitted, null
  918. /// otherwise
  919. llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
  920. llvm::Value *Addr) {
  921. if (!ShouldEmitLifetimeMarkers)
  922. return nullptr;
  923. assert(Addr->getType()->getPointerAddressSpace() ==
  924. CGM.getDataLayout().getAllocaAddrSpace() &&
  925. "Pointer should be in alloca address space");
  926. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  927. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  928. llvm::CallInst *C =
  929. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  930. C->setDoesNotThrow();
  931. return SizeV;
  932. }
  933. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  934. assert(Addr->getType()->getPointerAddressSpace() ==
  935. CGM.getDataLayout().getAllocaAddrSpace() &&
  936. "Pointer should be in alloca address space");
  937. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  938. llvm::CallInst *C =
  939. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  940. C->setDoesNotThrow();
  941. }
  942. void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
  943. CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
  944. // For each dimension stores its QualType and corresponding
  945. // size-expression Value.
  946. SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
  947. // Break down the array into individual dimensions.
  948. QualType Type1D = D.getType();
  949. while (getContext().getAsVariableArrayType(Type1D)) {
  950. auto VlaSize = getVLAElements1D(Type1D);
  951. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  952. Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
  953. else {
  954. auto SizeExprAddr = CreateDefaultAlignTempAlloca(
  955. VlaSize.NumElts->getType(), "__vla_expr");
  956. Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
  957. Dimensions.emplace_back(SizeExprAddr.getPointer(),
  958. Type1D.getUnqualifiedType());
  959. }
  960. Type1D = VlaSize.Type;
  961. }
  962. if (!EmitDebugInfo)
  963. return;
  964. // Register each dimension's size-expression with a DILocalVariable,
  965. // so that it can be used by CGDebugInfo when instantiating a DISubrange
  966. // to describe this array.
  967. for (auto &VlaSize : Dimensions) {
  968. llvm::Metadata *MD;
  969. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  970. MD = llvm::ConstantAsMetadata::get(C);
  971. else {
  972. // Create an artificial VarDecl to generate debug info for.
  973. IdentifierInfo &NameIdent = getContext().Idents.getOwn(
  974. cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
  975. auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
  976. auto QT = getContext().getIntTypeForBitwidth(
  977. VlaExprTy->getScalarSizeInBits(), false);
  978. auto *ArtificialDecl = VarDecl::Create(
  979. getContext(), const_cast<DeclContext *>(D.getDeclContext()),
  980. D.getLocation(), D.getLocation(), &NameIdent, QT,
  981. getContext().CreateTypeSourceInfo(QT), SC_Auto);
  982. ArtificialDecl->setImplicit();
  983. MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
  984. Builder);
  985. }
  986. assert(MD && "No Size expression debug node created");
  987. DI->registerVLASizeExpression(VlaSize.Type, MD);
  988. }
  989. }
  990. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  991. /// local variable. Does not emit initialization or destruction.
  992. CodeGenFunction::AutoVarEmission
  993. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  994. QualType Ty = D.getType();
  995. assert(
  996. Ty.getAddressSpace() == LangAS::Default ||
  997. (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
  998. AutoVarEmission emission(D);
  999. bool isByRef = D.hasAttr<BlocksAttr>();
  1000. emission.IsByRef = isByRef;
  1001. CharUnits alignment = getContext().getDeclAlign(&D);
  1002. // If the type is variably-modified, emit all the VLA sizes for it.
  1003. if (Ty->isVariablyModifiedType())
  1004. EmitVariablyModifiedType(Ty);
  1005. auto *DI = getDebugInfo();
  1006. bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
  1007. codegenoptions::LimitedDebugInfo;
  1008. Address address = Address::invalid();
  1009. Address AllocaAddr = Address::invalid();
  1010. if (Ty->isConstantSizeType()) {
  1011. bool NRVO = getLangOpts().ElideConstructors &&
  1012. D.isNRVOVariable();
  1013. // If this value is an array or struct with a statically determinable
  1014. // constant initializer, there are optimizations we can do.
  1015. //
  1016. // TODO: We should constant-evaluate the initializer of any variable,
  1017. // as long as it is initialized by a constant expression. Currently,
  1018. // isConstantInitializer produces wrong answers for structs with
  1019. // reference or bitfield members, and a few other cases, and checking
  1020. // for POD-ness protects us from some of these.
  1021. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  1022. (D.isConstexpr() ||
  1023. ((Ty.isPODType(getContext()) ||
  1024. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  1025. D.getInit()->isConstantInitializer(getContext(), false)))) {
  1026. // If the variable's a const type, and it's neither an NRVO
  1027. // candidate nor a __block variable and has no mutable members,
  1028. // emit it as a global instead.
  1029. // Exception is if a variable is located in non-constant address space
  1030. // in OpenCL.
  1031. if ((!getLangOpts().OpenCL ||
  1032. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  1033. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  1034. CGM.isTypeConstant(Ty, true))) {
  1035. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  1036. // Signal this condition to later callbacks.
  1037. emission.Addr = Address::invalid();
  1038. assert(emission.wasEmittedAsGlobal());
  1039. return emission;
  1040. }
  1041. // Otherwise, tell the initialization code that we're in this case.
  1042. emission.IsConstantAggregate = true;
  1043. }
  1044. // A normal fixed sized variable becomes an alloca in the entry block,
  1045. // unless:
  1046. // - it's an NRVO variable.
  1047. // - we are compiling OpenMP and it's an OpenMP local variable.
  1048. Address OpenMPLocalAddr =
  1049. getLangOpts().OpenMP
  1050. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1051. : Address::invalid();
  1052. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1053. address = OpenMPLocalAddr;
  1054. } else if (NRVO) {
  1055. // The named return value optimization: allocate this variable in the
  1056. // return slot, so that we can elide the copy when returning this
  1057. // variable (C++0x [class.copy]p34).
  1058. address = ReturnValue;
  1059. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1060. const auto *RD = RecordTy->getDecl();
  1061. const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1062. if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
  1063. RD->isNonTrivialToPrimitiveDestroy()) {
  1064. // Create a flag that is used to indicate when the NRVO was applied
  1065. // to this variable. Set it to zero to indicate that NRVO was not
  1066. // applied.
  1067. llvm::Value *Zero = Builder.getFalse();
  1068. Address NRVOFlag =
  1069. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
  1070. EnsureInsertPoint();
  1071. Builder.CreateStore(Zero, NRVOFlag);
  1072. // Record the NRVO flag for this variable.
  1073. NRVOFlags[&D] = NRVOFlag.getPointer();
  1074. emission.NRVOFlag = NRVOFlag.getPointer();
  1075. }
  1076. }
  1077. } else {
  1078. CharUnits allocaAlignment;
  1079. llvm::Type *allocaTy;
  1080. if (isByRef) {
  1081. auto &byrefInfo = getBlockByrefInfo(&D);
  1082. allocaTy = byrefInfo.Type;
  1083. allocaAlignment = byrefInfo.ByrefAlignment;
  1084. } else {
  1085. allocaTy = ConvertTypeForMem(Ty);
  1086. allocaAlignment = alignment;
  1087. }
  1088. // Create the alloca. Note that we set the name separately from
  1089. // building the instruction so that it's there even in no-asserts
  1090. // builds.
  1091. address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
  1092. /*ArraySize=*/nullptr, &AllocaAddr);
  1093. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  1094. // the catch parameter starts in the catchpad instruction, and we can't
  1095. // insert code in those basic blocks.
  1096. bool IsMSCatchParam =
  1097. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  1098. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  1099. // if we don't have a valid insertion point (?).
  1100. if (HaveInsertPoint() && !IsMSCatchParam) {
  1101. // If there's a jump into the lifetime of this variable, its lifetime
  1102. // gets broken up into several regions in IR, which requires more work
  1103. // to handle correctly. For now, just omit the intrinsics; this is a
  1104. // rare case, and it's better to just be conservatively correct.
  1105. // PR28267.
  1106. //
  1107. // We have to do this in all language modes if there's a jump past the
  1108. // declaration. We also have to do it in C if there's a jump to an
  1109. // earlier point in the current block because non-VLA lifetimes begin as
  1110. // soon as the containing block is entered, not when its variables
  1111. // actually come into scope; suppressing the lifetime annotations
  1112. // completely in this case is unnecessarily pessimistic, but again, this
  1113. // is rare.
  1114. if (!Bypasses.IsBypassed(&D) &&
  1115. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  1116. uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  1117. emission.SizeForLifetimeMarkers =
  1118. EmitLifetimeStart(size, AllocaAddr.getPointer());
  1119. }
  1120. } else {
  1121. assert(!emission.useLifetimeMarkers());
  1122. }
  1123. }
  1124. } else {
  1125. EnsureInsertPoint();
  1126. if (!DidCallStackSave) {
  1127. // Save the stack.
  1128. Address Stack =
  1129. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  1130. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  1131. llvm::Value *V = Builder.CreateCall(F);
  1132. Builder.CreateStore(V, Stack);
  1133. DidCallStackSave = true;
  1134. // Push a cleanup block and restore the stack there.
  1135. // FIXME: in general circumstances, this should be an EH cleanup.
  1136. pushStackRestore(NormalCleanup, Stack);
  1137. }
  1138. auto VlaSize = getVLASize(Ty);
  1139. llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
  1140. // Allocate memory for the array.
  1141. address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
  1142. &AllocaAddr);
  1143. // If we have debug info enabled, properly describe the VLA dimensions for
  1144. // this type by registering the vla size expression for each of the
  1145. // dimensions.
  1146. EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
  1147. }
  1148. setAddrOfLocalVar(&D, address);
  1149. emission.Addr = address;
  1150. emission.AllocaAddr = AllocaAddr;
  1151. // Emit debug info for local var declaration.
  1152. if (EmitDebugInfo && HaveInsertPoint()) {
  1153. DI->setLocation(D.getLocation());
  1154. (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
  1155. }
  1156. if (D.hasAttr<AnnotateAttr>())
  1157. EmitVarAnnotations(&D, address.getPointer());
  1158. // Make sure we call @llvm.lifetime.end.
  1159. if (emission.useLifetimeMarkers())
  1160. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1161. emission.getOriginalAllocatedAddress(),
  1162. emission.getSizeForLifetimeMarkers());
  1163. return emission;
  1164. }
  1165. static bool isCapturedBy(const VarDecl &, const Expr *);
  1166. /// Determines whether the given __block variable is potentially
  1167. /// captured by the given statement.
  1168. static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
  1169. if (const Expr *E = dyn_cast<Expr>(S))
  1170. return isCapturedBy(Var, E);
  1171. for (const Stmt *SubStmt : S->children())
  1172. if (isCapturedBy(Var, SubStmt))
  1173. return true;
  1174. return false;
  1175. }
  1176. /// Determines whether the given __block variable is potentially
  1177. /// captured by the given expression.
  1178. static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
  1179. // Skip the most common kinds of expressions that make
  1180. // hierarchy-walking expensive.
  1181. E = E->IgnoreParenCasts();
  1182. if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
  1183. const BlockDecl *Block = BE->getBlockDecl();
  1184. for (const auto &I : Block->captures()) {
  1185. if (I.getVariable() == &Var)
  1186. return true;
  1187. }
  1188. // No need to walk into the subexpressions.
  1189. return false;
  1190. }
  1191. if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  1192. const CompoundStmt *CS = SE->getSubStmt();
  1193. for (const auto *BI : CS->body())
  1194. if (const auto *BIE = dyn_cast<Expr>(BI)) {
  1195. if (isCapturedBy(Var, BIE))
  1196. return true;
  1197. }
  1198. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  1199. // special case declarations
  1200. for (const auto *I : DS->decls()) {
  1201. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  1202. const Expr *Init = VD->getInit();
  1203. if (Init && isCapturedBy(Var, Init))
  1204. return true;
  1205. }
  1206. }
  1207. }
  1208. else
  1209. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  1210. // Later, provide code to poke into statements for capture analysis.
  1211. return true;
  1212. return false;
  1213. }
  1214. for (const Stmt *SubStmt : E->children())
  1215. if (isCapturedBy(Var, SubStmt))
  1216. return true;
  1217. return false;
  1218. }
  1219. /// Determine whether the given initializer is trivial in the sense
  1220. /// that it requires no code to be generated.
  1221. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  1222. if (!Init)
  1223. return true;
  1224. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  1225. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  1226. if (Constructor->isTrivial() &&
  1227. Constructor->isDefaultConstructor() &&
  1228. !Construct->requiresZeroInitialization())
  1229. return true;
  1230. return false;
  1231. }
  1232. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1233. assert(emission.Variable && "emission was not valid!");
  1234. // If this was emitted as a global constant, we're done.
  1235. if (emission.wasEmittedAsGlobal()) return;
  1236. const VarDecl &D = *emission.Variable;
  1237. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1238. QualType type = D.getType();
  1239. // If this local has an initializer, emit it now.
  1240. const Expr *Init = D.getInit();
  1241. // If we are at an unreachable point, we don't need to emit the initializer
  1242. // unless it contains a label.
  1243. if (!HaveInsertPoint()) {
  1244. if (!Init || !ContainsLabel(Init)) return;
  1245. EnsureInsertPoint();
  1246. }
  1247. // Initialize the structure of a __block variable.
  1248. if (emission.IsByRef)
  1249. emitByrefStructureInit(emission);
  1250. // Initialize the variable here if it doesn't have a initializer and it is a
  1251. // C struct that is non-trivial to initialize or an array containing such a
  1252. // struct.
  1253. if (!Init &&
  1254. type.isNonTrivialToPrimitiveDefaultInitialize() ==
  1255. QualType::PDIK_Struct) {
  1256. LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
  1257. if (emission.IsByRef)
  1258. drillIntoBlockVariable(*this, Dst, &D);
  1259. defaultInitNonTrivialCStructVar(Dst);
  1260. return;
  1261. }
  1262. if (isTrivialInitializer(Init))
  1263. return;
  1264. // Check whether this is a byref variable that's potentially
  1265. // captured and moved by its own initializer. If so, we'll need to
  1266. // emit the initializer first, then copy into the variable.
  1267. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  1268. Address Loc =
  1269. capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
  1270. llvm::Constant *constant = nullptr;
  1271. if (emission.IsConstantAggregate || D.isConstexpr()) {
  1272. assert(!capturedByInit && "constant init contains a capturing block?");
  1273. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1274. }
  1275. if (!constant) {
  1276. LValue lv = MakeAddrLValue(Loc, type);
  1277. lv.setNonGC(true);
  1278. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1279. }
  1280. if (!emission.IsConstantAggregate) {
  1281. // For simple scalar/complex initialization, store the value directly.
  1282. LValue lv = MakeAddrLValue(Loc, type);
  1283. lv.setNonGC(true);
  1284. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1285. }
  1286. // If this is a simple aggregate initialization, we can optimize it
  1287. // in various ways.
  1288. bool isVolatile = type.isVolatileQualified();
  1289. llvm::Value *SizeVal =
  1290. llvm::ConstantInt::get(IntPtrTy,
  1291. getContext().getTypeSizeInChars(type).getQuantity());
  1292. llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
  1293. if (Loc.getType() != BP)
  1294. Loc = Builder.CreateBitCast(Loc, BP);
  1295. // If the initializer is all or mostly the same, codegen with bzero / memset
  1296. // then do a few stores afterward.
  1297. uint64_t ConstantSize =
  1298. CGM.getDataLayout().getTypeAllocSize(constant->getType());
  1299. if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
  1300. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1301. isVolatile);
  1302. // Zero and undef don't require a stores.
  1303. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  1304. Loc = Builder.CreateBitCast(Loc,
  1305. constant->getType()->getPointerTo(Loc.getAddressSpace()));
  1306. emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
  1307. }
  1308. return;
  1309. }
  1310. BytePattern Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
  1311. if (!Pattern.isNone()) {
  1312. uint8_t Value = Pattern.isAny() ? 0x00 : Pattern.getValue();
  1313. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
  1314. isVolatile);
  1315. return;
  1316. }
  1317. // Otherwise, create a temporary global with the initializer then
  1318. // memcpy from the global to the alloca.
  1319. std::string Name = getStaticDeclName(CGM, D);
  1320. unsigned AS = CGM.getContext().getTargetAddressSpace(
  1321. CGM.getStringLiteralAddressSpace());
  1322. BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
  1323. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  1324. CGM.getModule(), constant->getType(), true,
  1325. llvm::GlobalValue::PrivateLinkage, constant, Name, nullptr,
  1326. llvm::GlobalValue::NotThreadLocal, AS);
  1327. GV->setAlignment(Loc.getAlignment().getQuantity());
  1328. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1329. Address SrcPtr = Address(GV, Loc.getAlignment());
  1330. if (SrcPtr.getType() != BP)
  1331. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  1332. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
  1333. }
  1334. /// Emit an expression as an initializer for an object (variable, field, etc.)
  1335. /// at the given location. The expression is not necessarily the normal
  1336. /// initializer for the object, and the address is not necessarily
  1337. /// its normal location.
  1338. ///
  1339. /// \param init the initializing expression
  1340. /// \param D the object to act as if we're initializing
  1341. /// \param loc the address to initialize; its type is a pointer
  1342. /// to the LLVM mapping of the object's type
  1343. /// \param alignment the alignment of the address
  1344. /// \param capturedByInit true if \p D is a __block variable
  1345. /// whose address is potentially changed by the initializer
  1346. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1347. LValue lvalue, bool capturedByInit) {
  1348. QualType type = D->getType();
  1349. if (type->isReferenceType()) {
  1350. RValue rvalue = EmitReferenceBindingToExpr(init);
  1351. if (capturedByInit)
  1352. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1353. EmitStoreThroughLValue(rvalue, lvalue, true);
  1354. return;
  1355. }
  1356. switch (getEvaluationKind(type)) {
  1357. case TEK_Scalar:
  1358. EmitScalarInit(init, D, lvalue, capturedByInit);
  1359. return;
  1360. case TEK_Complex: {
  1361. ComplexPairTy complex = EmitComplexExpr(init);
  1362. if (capturedByInit)
  1363. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1364. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1365. return;
  1366. }
  1367. case TEK_Aggregate:
  1368. if (type->isAtomicType()) {
  1369. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1370. } else {
  1371. AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
  1372. if (isa<VarDecl>(D))
  1373. Overlap = AggValueSlot::DoesNotOverlap;
  1374. else if (auto *FD = dyn_cast<FieldDecl>(D))
  1375. Overlap = overlapForFieldInit(FD);
  1376. // TODO: how can we delay here if D is captured by its initializer?
  1377. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1378. AggValueSlot::IsDestructed,
  1379. AggValueSlot::DoesNotNeedGCBarriers,
  1380. AggValueSlot::IsNotAliased,
  1381. Overlap));
  1382. }
  1383. return;
  1384. }
  1385. llvm_unreachable("bad evaluation kind");
  1386. }
  1387. /// Enter a destroy cleanup for the given local variable.
  1388. void CodeGenFunction::emitAutoVarTypeCleanup(
  1389. const CodeGenFunction::AutoVarEmission &emission,
  1390. QualType::DestructionKind dtorKind) {
  1391. assert(dtorKind != QualType::DK_none);
  1392. // Note that for __block variables, we want to destroy the
  1393. // original stack object, not the possibly forwarded object.
  1394. Address addr = emission.getObjectAddress(*this);
  1395. const VarDecl *var = emission.Variable;
  1396. QualType type = var->getType();
  1397. CleanupKind cleanupKind = NormalAndEHCleanup;
  1398. CodeGenFunction::Destroyer *destroyer = nullptr;
  1399. switch (dtorKind) {
  1400. case QualType::DK_none:
  1401. llvm_unreachable("no cleanup for trivially-destructible variable");
  1402. case QualType::DK_cxx_destructor:
  1403. // If there's an NRVO flag on the emission, we need a different
  1404. // cleanup.
  1405. if (emission.NRVOFlag) {
  1406. assert(!type->isArrayType());
  1407. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1408. EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
  1409. emission.NRVOFlag);
  1410. return;
  1411. }
  1412. break;
  1413. case QualType::DK_objc_strong_lifetime:
  1414. // Suppress cleanups for pseudo-strong variables.
  1415. if (var->isARCPseudoStrong()) return;
  1416. // Otherwise, consider whether to use an EH cleanup or not.
  1417. cleanupKind = getARCCleanupKind();
  1418. // Use the imprecise destroyer by default.
  1419. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1420. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1421. break;
  1422. case QualType::DK_objc_weak_lifetime:
  1423. break;
  1424. case QualType::DK_nontrivial_c_struct:
  1425. destroyer = CodeGenFunction::destroyNonTrivialCStruct;
  1426. if (emission.NRVOFlag) {
  1427. assert(!type->isArrayType());
  1428. EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
  1429. emission.NRVOFlag, type);
  1430. return;
  1431. }
  1432. break;
  1433. }
  1434. // If we haven't chosen a more specific destroyer, use the default.
  1435. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1436. // Use an EH cleanup in array destructors iff the destructor itself
  1437. // is being pushed as an EH cleanup.
  1438. bool useEHCleanup = (cleanupKind & EHCleanup);
  1439. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1440. useEHCleanup);
  1441. }
  1442. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1443. assert(emission.Variable && "emission was not valid!");
  1444. // If this was emitted as a global constant, we're done.
  1445. if (emission.wasEmittedAsGlobal()) return;
  1446. // If we don't have an insertion point, we're done. Sema prevents
  1447. // us from jumping into any of these scopes anyway.
  1448. if (!HaveInsertPoint()) return;
  1449. const VarDecl &D = *emission.Variable;
  1450. // Check the type for a cleanup.
  1451. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1452. emitAutoVarTypeCleanup(emission, dtorKind);
  1453. // In GC mode, honor objc_precise_lifetime.
  1454. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1455. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1456. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1457. }
  1458. // Handle the cleanup attribute.
  1459. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1460. const FunctionDecl *FD = CA->getFunctionDecl();
  1461. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1462. assert(F && "Could not find function!");
  1463. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1464. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1465. }
  1466. // If this is a block variable, call _Block_object_destroy
  1467. // (on the unforwarded address).
  1468. if (emission.IsByRef)
  1469. enterByrefCleanup(emission);
  1470. }
  1471. CodeGenFunction::Destroyer *
  1472. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1473. switch (kind) {
  1474. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1475. case QualType::DK_cxx_destructor:
  1476. return destroyCXXObject;
  1477. case QualType::DK_objc_strong_lifetime:
  1478. return destroyARCStrongPrecise;
  1479. case QualType::DK_objc_weak_lifetime:
  1480. return destroyARCWeak;
  1481. case QualType::DK_nontrivial_c_struct:
  1482. return destroyNonTrivialCStruct;
  1483. }
  1484. llvm_unreachable("Unknown DestructionKind");
  1485. }
  1486. /// pushEHDestroy - Push the standard destructor for the given type as
  1487. /// an EH-only cleanup.
  1488. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1489. Address addr, QualType type) {
  1490. assert(dtorKind && "cannot push destructor for trivial type");
  1491. assert(needsEHCleanup(dtorKind));
  1492. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1493. }
  1494. /// pushDestroy - Push the standard destructor for the given type as
  1495. /// at least a normal cleanup.
  1496. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1497. Address addr, QualType type) {
  1498. assert(dtorKind && "cannot push destructor for trivial type");
  1499. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1500. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1501. cleanupKind & EHCleanup);
  1502. }
  1503. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1504. QualType type, Destroyer *destroyer,
  1505. bool useEHCleanupForArray) {
  1506. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1507. destroyer, useEHCleanupForArray);
  1508. }
  1509. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1510. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1511. }
  1512. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1513. CleanupKind cleanupKind, Address addr, QualType type,
  1514. Destroyer *destroyer, bool useEHCleanupForArray) {
  1515. // Push an EH-only cleanup for the object now.
  1516. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1517. // around in case a temporary's destructor throws an exception.
  1518. if (cleanupKind & EHCleanup)
  1519. EHStack.pushCleanup<DestroyObject>(
  1520. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1521. destroyer, useEHCleanupForArray);
  1522. // Remember that we need to push a full cleanup for the object at the
  1523. // end of the full-expression.
  1524. pushCleanupAfterFullExpr<DestroyObject>(
  1525. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1526. }
  1527. /// emitDestroy - Immediately perform the destruction of the given
  1528. /// object.
  1529. ///
  1530. /// \param addr - the address of the object; a type*
  1531. /// \param type - the type of the object; if an array type, all
  1532. /// objects are destroyed in reverse order
  1533. /// \param destroyer - the function to call to destroy individual
  1534. /// elements
  1535. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1536. /// used when destroying array elements, in case one of the
  1537. /// destructions throws an exception
  1538. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1539. Destroyer *destroyer,
  1540. bool useEHCleanupForArray) {
  1541. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1542. if (!arrayType)
  1543. return destroyer(*this, addr, type);
  1544. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1545. CharUnits elementAlign =
  1546. addr.getAlignment()
  1547. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1548. // Normally we have to check whether the array is zero-length.
  1549. bool checkZeroLength = true;
  1550. // But if the array length is constant, we can suppress that.
  1551. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1552. // ...and if it's constant zero, we can just skip the entire thing.
  1553. if (constLength->isZero()) return;
  1554. checkZeroLength = false;
  1555. }
  1556. llvm::Value *begin = addr.getPointer();
  1557. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1558. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1559. checkZeroLength, useEHCleanupForArray);
  1560. }
  1561. /// emitArrayDestroy - Destroys all the elements of the given array,
  1562. /// beginning from last to first. The array cannot be zero-length.
  1563. ///
  1564. /// \param begin - a type* denoting the first element of the array
  1565. /// \param end - a type* denoting one past the end of the array
  1566. /// \param elementType - the element type of the array
  1567. /// \param destroyer - the function to call to destroy elements
  1568. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1569. /// the remaining elements in case the destruction of a single
  1570. /// element throws
  1571. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1572. llvm::Value *end,
  1573. QualType elementType,
  1574. CharUnits elementAlign,
  1575. Destroyer *destroyer,
  1576. bool checkZeroLength,
  1577. bool useEHCleanup) {
  1578. assert(!elementType->isArrayType());
  1579. // The basic structure here is a do-while loop, because we don't
  1580. // need to check for the zero-element case.
  1581. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1582. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1583. if (checkZeroLength) {
  1584. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1585. "arraydestroy.isempty");
  1586. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1587. }
  1588. // Enter the loop body, making that address the current address.
  1589. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1590. EmitBlock(bodyBB);
  1591. llvm::PHINode *elementPast =
  1592. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1593. elementPast->addIncoming(end, entryBB);
  1594. // Shift the address back by one element.
  1595. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1596. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1597. "arraydestroy.element");
  1598. if (useEHCleanup)
  1599. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1600. destroyer);
  1601. // Perform the actual destruction there.
  1602. destroyer(*this, Address(element, elementAlign), elementType);
  1603. if (useEHCleanup)
  1604. PopCleanupBlock();
  1605. // Check whether we've reached the end.
  1606. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1607. Builder.CreateCondBr(done, doneBB, bodyBB);
  1608. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1609. // Done.
  1610. EmitBlock(doneBB);
  1611. }
  1612. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1613. /// emitArrayDestroy, the element type here may still be an array type.
  1614. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1615. llvm::Value *begin, llvm::Value *end,
  1616. QualType type, CharUnits elementAlign,
  1617. CodeGenFunction::Destroyer *destroyer) {
  1618. // If the element type is itself an array, drill down.
  1619. unsigned arrayDepth = 0;
  1620. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1621. // VLAs don't require a GEP index to walk into.
  1622. if (!isa<VariableArrayType>(arrayType))
  1623. arrayDepth++;
  1624. type = arrayType->getElementType();
  1625. }
  1626. if (arrayDepth) {
  1627. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1628. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  1629. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1630. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1631. }
  1632. // Destroy the array. We don't ever need an EH cleanup because we
  1633. // assume that we're in an EH cleanup ourselves, so a throwing
  1634. // destructor causes an immediate terminate.
  1635. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1636. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1637. }
  1638. namespace {
  1639. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1640. /// array destroy where the end pointer is regularly determined and
  1641. /// does not need to be loaded from a local.
  1642. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1643. llvm::Value *ArrayBegin;
  1644. llvm::Value *ArrayEnd;
  1645. QualType ElementType;
  1646. CodeGenFunction::Destroyer *Destroyer;
  1647. CharUnits ElementAlign;
  1648. public:
  1649. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1650. QualType elementType, CharUnits elementAlign,
  1651. CodeGenFunction::Destroyer *destroyer)
  1652. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1653. ElementType(elementType), Destroyer(destroyer),
  1654. ElementAlign(elementAlign) {}
  1655. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1656. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1657. ElementType, ElementAlign, Destroyer);
  1658. }
  1659. };
  1660. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1661. /// partial array destroy where the end pointer is irregularly
  1662. /// determined and must be loaded from a local.
  1663. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1664. llvm::Value *ArrayBegin;
  1665. Address ArrayEndPointer;
  1666. QualType ElementType;
  1667. CodeGenFunction::Destroyer *Destroyer;
  1668. CharUnits ElementAlign;
  1669. public:
  1670. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1671. Address arrayEndPointer,
  1672. QualType elementType,
  1673. CharUnits elementAlign,
  1674. CodeGenFunction::Destroyer *destroyer)
  1675. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1676. ElementType(elementType), Destroyer(destroyer),
  1677. ElementAlign(elementAlign) {}
  1678. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1679. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1680. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1681. ElementType, ElementAlign, Destroyer);
  1682. }
  1683. };
  1684. } // end anonymous namespace
  1685. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1686. /// already-constructed elements of the given array. The cleanup
  1687. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1688. ///
  1689. /// \param elementType - the immediate element type of the array;
  1690. /// possibly still an array type
  1691. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1692. Address arrayEndPointer,
  1693. QualType elementType,
  1694. CharUnits elementAlign,
  1695. Destroyer *destroyer) {
  1696. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1697. arrayBegin, arrayEndPointer,
  1698. elementType, elementAlign,
  1699. destroyer);
  1700. }
  1701. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1702. /// already-constructed elements of the given array. The cleanup
  1703. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1704. ///
  1705. /// \param elementType - the immediate element type of the array;
  1706. /// possibly still an array type
  1707. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1708. llvm::Value *arrayEnd,
  1709. QualType elementType,
  1710. CharUnits elementAlign,
  1711. Destroyer *destroyer) {
  1712. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1713. arrayBegin, arrayEnd,
  1714. elementType, elementAlign,
  1715. destroyer);
  1716. }
  1717. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1718. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1719. if (LifetimeStartFn)
  1720. return LifetimeStartFn;
  1721. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1722. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  1723. return LifetimeStartFn;
  1724. }
  1725. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1726. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1727. if (LifetimeEndFn)
  1728. return LifetimeEndFn;
  1729. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1730. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  1731. return LifetimeEndFn;
  1732. }
  1733. namespace {
  1734. /// A cleanup to perform a release of an object at the end of a
  1735. /// function. This is used to balance out the incoming +1 of a
  1736. /// ns_consumed argument when we can't reasonably do that just by
  1737. /// not doing the initial retain for a __block argument.
  1738. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  1739. ConsumeARCParameter(llvm::Value *param,
  1740. ARCPreciseLifetime_t precise)
  1741. : Param(param), Precise(precise) {}
  1742. llvm::Value *Param;
  1743. ARCPreciseLifetime_t Precise;
  1744. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1745. CGF.EmitARCRelease(Param, Precise);
  1746. }
  1747. };
  1748. } // end anonymous namespace
  1749. /// Emit an alloca (or GlobalValue depending on target)
  1750. /// for the specified parameter and set up LocalDeclMap.
  1751. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  1752. unsigned ArgNo) {
  1753. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1754. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1755. "Invalid argument to EmitParmDecl");
  1756. Arg.getAnyValue()->setName(D.getName());
  1757. QualType Ty = D.getType();
  1758. // Use better IR generation for certain implicit parameters.
  1759. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  1760. // The only implicit argument a block has is its literal.
  1761. // This may be passed as an inalloca'ed value on Windows x86.
  1762. if (BlockInfo) {
  1763. llvm::Value *V = Arg.isIndirect()
  1764. ? Builder.CreateLoad(Arg.getIndirectAddress())
  1765. : Arg.getDirectValue();
  1766. setBlockContextParameter(IPD, ArgNo, V);
  1767. return;
  1768. }
  1769. }
  1770. Address DeclPtr = Address::invalid();
  1771. bool DoStore = false;
  1772. bool IsScalar = hasScalarEvaluationKind(Ty);
  1773. // If we already have a pointer to the argument, reuse the input pointer.
  1774. if (Arg.isIndirect()) {
  1775. DeclPtr = Arg.getIndirectAddress();
  1776. // If we have a prettier pointer type at this point, bitcast to that.
  1777. unsigned AS = DeclPtr.getType()->getAddressSpace();
  1778. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1779. if (DeclPtr.getType() != IRTy)
  1780. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  1781. // Indirect argument is in alloca address space, which may be different
  1782. // from the default address space.
  1783. auto AllocaAS = CGM.getASTAllocaAddressSpace();
  1784. auto *V = DeclPtr.getPointer();
  1785. auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
  1786. auto DestLangAS =
  1787. getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
  1788. if (SrcLangAS != DestLangAS) {
  1789. assert(getContext().getTargetAddressSpace(SrcLangAS) ==
  1790. CGM.getDataLayout().getAllocaAddrSpace());
  1791. auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
  1792. auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
  1793. DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
  1794. *this, V, SrcLangAS, DestLangAS, T, true),
  1795. DeclPtr.getAlignment());
  1796. }
  1797. // Push a destructor cleanup for this parameter if the ABI requires it.
  1798. // Don't push a cleanup in a thunk for a method that will also emit a
  1799. // cleanup.
  1800. if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
  1801. Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  1802. if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
  1803. assert((DtorKind == QualType::DK_cxx_destructor ||
  1804. DtorKind == QualType::DK_nontrivial_c_struct) &&
  1805. "unexpected destructor type");
  1806. pushDestroy(DtorKind, DeclPtr, Ty);
  1807. CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
  1808. EHStack.stable_begin();
  1809. }
  1810. }
  1811. } else {
  1812. // Check if the parameter address is controlled by OpenMP runtime.
  1813. Address OpenMPLocalAddr =
  1814. getLangOpts().OpenMP
  1815. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1816. : Address::invalid();
  1817. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1818. DeclPtr = OpenMPLocalAddr;
  1819. } else {
  1820. // Otherwise, create a temporary to hold the value.
  1821. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  1822. D.getName() + ".addr");
  1823. }
  1824. DoStore = true;
  1825. }
  1826. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  1827. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  1828. if (IsScalar) {
  1829. Qualifiers qs = Ty.getQualifiers();
  1830. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1831. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1832. // For __strong, it's handled by just skipping the initial retain;
  1833. // otherwise we have to balance out the initial +1 with an extra
  1834. // cleanup to do the release at the end of the function.
  1835. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1836. // 'self' is always formally __strong, but if this is not an
  1837. // init method then we don't want to retain it.
  1838. if (D.isARCPseudoStrong()) {
  1839. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1840. assert(&D == method->getSelfDecl());
  1841. assert(lt == Qualifiers::OCL_Strong);
  1842. assert(qs.hasConst());
  1843. assert(method->getMethodFamily() != OMF_init);
  1844. (void) method;
  1845. lt = Qualifiers::OCL_ExplicitNone;
  1846. }
  1847. // Load objects passed indirectly.
  1848. if (Arg.isIndirect() && !ArgVal)
  1849. ArgVal = Builder.CreateLoad(DeclPtr);
  1850. if (lt == Qualifiers::OCL_Strong) {
  1851. if (!isConsumed) {
  1852. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1853. // use objc_storeStrong(&dest, value) for retaining the
  1854. // object. But first, store a null into 'dest' because
  1855. // objc_storeStrong attempts to release its old value.
  1856. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1857. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1858. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  1859. DoStore = false;
  1860. }
  1861. else
  1862. // Don't use objc_retainBlock for block pointers, because we
  1863. // don't want to Block_copy something just because we got it
  1864. // as a parameter.
  1865. ArgVal = EmitARCRetainNonBlock(ArgVal);
  1866. }
  1867. } else {
  1868. // Push the cleanup for a consumed parameter.
  1869. if (isConsumed) {
  1870. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1871. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1872. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  1873. precise);
  1874. }
  1875. if (lt == Qualifiers::OCL_Weak) {
  1876. EmitARCInitWeak(DeclPtr, ArgVal);
  1877. DoStore = false; // The weak init is a store, no need to do two.
  1878. }
  1879. }
  1880. // Enter the cleanup scope.
  1881. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1882. }
  1883. }
  1884. // Store the initial value into the alloca.
  1885. if (DoStore)
  1886. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  1887. setAddrOfLocalVar(&D, DeclPtr);
  1888. // Emit debug info for param declaration.
  1889. if (CGDebugInfo *DI = getDebugInfo()) {
  1890. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1891. codegenoptions::LimitedDebugInfo) {
  1892. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  1893. }
  1894. }
  1895. if (D.hasAttr<AnnotateAttr>())
  1896. EmitVarAnnotations(&D, DeclPtr.getPointer());
  1897. // We can only check return value nullability if all arguments to the
  1898. // function satisfy their nullability preconditions. This makes it necessary
  1899. // to emit null checks for args in the function body itself.
  1900. if (requiresReturnValueNullabilityCheck()) {
  1901. auto Nullability = Ty->getNullability(getContext());
  1902. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  1903. SanitizerScope SanScope(this);
  1904. RetValNullabilityPrecondition =
  1905. Builder.CreateAnd(RetValNullabilityPrecondition,
  1906. Builder.CreateIsNotNull(Arg.getAnyValue()));
  1907. }
  1908. }
  1909. }
  1910. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1911. CodeGenFunction *CGF) {
  1912. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  1913. return;
  1914. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  1915. }