CGDecl.cpp 97 KB

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