CGDecl.cpp 98 KB

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