CGDecl.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "llvm/GlobalVariable.h"
  25. #include "llvm/Intrinsics.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Type.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. void CodeGenFunction::EmitDecl(const Decl &D) {
  31. switch (D.getKind()) {
  32. case Decl::TranslationUnit:
  33. case Decl::Namespace:
  34. case Decl::UnresolvedUsingTypename:
  35. case Decl::ClassTemplateSpecialization:
  36. case Decl::ClassTemplatePartialSpecialization:
  37. case Decl::TemplateTypeParm:
  38. case Decl::UnresolvedUsingValue:
  39. case Decl::NonTypeTemplateParm:
  40. case Decl::CXXMethod:
  41. case Decl::CXXConstructor:
  42. case Decl::CXXDestructor:
  43. case Decl::CXXConversion:
  44. case Decl::Field:
  45. case Decl::IndirectField:
  46. case Decl::ObjCIvar:
  47. case Decl::ObjCAtDefsField:
  48. case Decl::ParmVar:
  49. case Decl::ImplicitParam:
  50. case Decl::ClassTemplate:
  51. case Decl::FunctionTemplate:
  52. case Decl::TypeAliasTemplate:
  53. case Decl::TemplateTemplateParm:
  54. case Decl::ObjCMethod:
  55. case Decl::ObjCCategory:
  56. case Decl::ObjCProtocol:
  57. case Decl::ObjCInterface:
  58. case Decl::ObjCCategoryImpl:
  59. case Decl::ObjCImplementation:
  60. case Decl::ObjCProperty:
  61. case Decl::ObjCCompatibleAlias:
  62. case Decl::AccessSpec:
  63. case Decl::LinkageSpec:
  64. case Decl::ObjCPropertyImpl:
  65. case Decl::FileScopeAsm:
  66. case Decl::Friend:
  67. case Decl::FriendTemplate:
  68. case Decl::Block:
  69. case Decl::ClassScopeFunctionSpecialization:
  70. llvm_unreachable("Declaration should not be in declstmts!");
  71. case Decl::Function: // void X();
  72. case Decl::Record: // struct/union/class X;
  73. case Decl::Enum: // enum X;
  74. case Decl::EnumConstant: // enum ? { X = ? }
  75. case Decl::CXXRecord: // struct/union/class X; [C++]
  76. case Decl::Using: // using X; [C++]
  77. case Decl::UsingShadow:
  78. case Decl::UsingDirective: // using namespace X; [C++]
  79. case Decl::NamespaceAlias:
  80. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  81. case Decl::Label: // __label__ x;
  82. case Decl::Import:
  83. // None of these decls require codegen support.
  84. return;
  85. case Decl::Var: {
  86. const VarDecl &VD = cast<VarDecl>(D);
  87. assert(VD.isLocalVarDecl() &&
  88. "Should not see file-scope variables inside a function!");
  89. return EmitVarDecl(VD);
  90. }
  91. case Decl::Typedef: // typedef int X;
  92. case Decl::TypeAlias: { // using X = int; [C++0x]
  93. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  94. QualType Ty = TD.getUnderlyingType();
  95. if (Ty->isVariablyModifiedType())
  96. EmitVariablyModifiedType(Ty);
  97. }
  98. }
  99. }
  100. /// EmitVarDecl - This method handles emission of any variable declaration
  101. /// inside a function, including static vars etc.
  102. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  103. switch (D.getStorageClass()) {
  104. case SC_None:
  105. case SC_Auto:
  106. case SC_Register:
  107. return EmitAutoVarDecl(D);
  108. case SC_Static: {
  109. llvm::GlobalValue::LinkageTypes Linkage =
  110. llvm::GlobalValue::InternalLinkage;
  111. // If the function definition has some sort of weak linkage, its
  112. // static variables should also be weak so that they get properly
  113. // uniqued. We can't do this in C, though, because there's no
  114. // standard way to agree on which variables are the same (i.e.
  115. // there's no mangling).
  116. if (getContext().getLangOpts().CPlusPlus)
  117. if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
  118. Linkage = CurFn->getLinkage();
  119. return EmitStaticVarDecl(D, Linkage);
  120. }
  121. case SC_Extern:
  122. case SC_PrivateExtern:
  123. // Don't emit it now, allow it to be emitted lazily on its first use.
  124. return;
  125. case SC_OpenCLWorkGroupLocal:
  126. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  127. }
  128. llvm_unreachable("Unknown storage class");
  129. }
  130. static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
  131. const char *Separator) {
  132. CodeGenModule &CGM = CGF.CGM;
  133. if (CGF.getContext().getLangOpts().CPlusPlus) {
  134. StringRef Name = CGM.getMangledName(&D);
  135. return Name.str();
  136. }
  137. std::string ContextName;
  138. if (!CGF.CurFuncDecl) {
  139. // Better be in a block declared in global scope.
  140. const NamedDecl *ND = cast<NamedDecl>(&D);
  141. const DeclContext *DC = ND->getDeclContext();
  142. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  143. MangleBuffer Name;
  144. CGM.getBlockMangledName(GlobalDecl(), Name, BD);
  145. ContextName = Name.getString();
  146. }
  147. else
  148. llvm_unreachable("Unknown context for block static var decl");
  149. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
  150. StringRef Name = CGM.getMangledName(FD);
  151. ContextName = Name.str();
  152. } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
  153. ContextName = CGF.CurFn->getName();
  154. else
  155. llvm_unreachable("Unknown context for static var decl");
  156. return ContextName + Separator + D.getNameAsString();
  157. }
  158. llvm::GlobalVariable *
  159. CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
  160. const char *Separator,
  161. llvm::GlobalValue::LinkageTypes Linkage) {
  162. QualType Ty = D.getType();
  163. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  164. // Use the label if the variable is renamed with the asm-label extension.
  165. std::string Name;
  166. if (D.hasAttr<AsmLabelAttr>())
  167. Name = CGM.getMangledName(&D);
  168. else
  169. Name = GetStaticDeclName(*this, D, Separator);
  170. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
  171. llvm::GlobalVariable *GV =
  172. new llvm::GlobalVariable(CGM.getModule(), LTy,
  173. Ty.isConstant(getContext()), Linkage,
  174. CGM.EmitNullConstant(D.getType()), Name, 0,
  175. D.isThreadSpecified(),
  176. CGM.getContext().getTargetAddressSpace(Ty));
  177. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  178. if (Linkage != llvm::GlobalValue::InternalLinkage)
  179. GV->setVisibility(CurFn->getVisibility());
  180. return GV;
  181. }
  182. /// hasNontrivialDestruction - Determine whether a type's destruction is
  183. /// non-trivial. If so, and the variable uses static initialization, we must
  184. /// register its destructor to run on exit.
  185. static bool hasNontrivialDestruction(QualType T) {
  186. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  187. return RD && !RD->hasTrivialDestructor();
  188. }
  189. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  190. /// global variable that has already been created for it. If the initializer
  191. /// has a different type than GV does, this may free GV and return a different
  192. /// one. Otherwise it just returns GV.
  193. llvm::GlobalVariable *
  194. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  195. llvm::GlobalVariable *GV) {
  196. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  197. // If constant emission failed, then this should be a C++ static
  198. // initializer.
  199. if (!Init) {
  200. if (!getContext().getLangOpts().CPlusPlus)
  201. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  202. else if (Builder.GetInsertBlock()) {
  203. // Since we have a static initializer, this global variable can't
  204. // be constant.
  205. GV->setConstant(false);
  206. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  207. }
  208. return GV;
  209. }
  210. // The initializer may differ in type from the global. Rewrite
  211. // the global to match the initializer. (We have to do this
  212. // because some types, like unions, can't be completely represented
  213. // in the LLVM type system.)
  214. if (GV->getType()->getElementType() != Init->getType()) {
  215. llvm::GlobalVariable *OldGV = GV;
  216. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  217. OldGV->isConstant(),
  218. OldGV->getLinkage(), Init, "",
  219. /*InsertBefore*/ OldGV,
  220. D.isThreadSpecified(),
  221. CGM.getContext().getTargetAddressSpace(D.getType()));
  222. GV->setVisibility(OldGV->getVisibility());
  223. // Steal the name of the old global
  224. GV->takeName(OldGV);
  225. // Replace all uses of the old global with the new global
  226. llvm::Constant *NewPtrForOldDecl =
  227. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  228. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  229. // Erase the old global, since it is no longer used.
  230. OldGV->eraseFromParent();
  231. }
  232. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  233. GV->setInitializer(Init);
  234. if (hasNontrivialDestruction(D.getType())) {
  235. // We have a constant initializer, but a nontrivial destructor. We still
  236. // need to perform a guarded "initialization" in order to register the
  237. // destructor.
  238. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  239. }
  240. return GV;
  241. }
  242. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  243. llvm::GlobalValue::LinkageTypes Linkage) {
  244. llvm::Value *&DMEntry = LocalDeclMap[&D];
  245. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  246. llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
  247. // Store into LocalDeclMap before generating initializer to handle
  248. // circular references.
  249. DMEntry = GV;
  250. // We can't have a VLA here, but we can have a pointer to a VLA,
  251. // even though that doesn't really make any sense.
  252. // Make sure to evaluate VLA bounds now so that we have them for later.
  253. if (D.getType()->isVariablyModifiedType())
  254. EmitVariablyModifiedType(D.getType());
  255. // Local static block variables must be treated as globals as they may be
  256. // referenced in their RHS initializer block-literal expresion.
  257. CGM.setStaticLocalDeclAddress(&D, GV);
  258. // If this value has an initializer, emit it.
  259. if (D.getInit())
  260. GV = AddInitializerToStaticVarDecl(D, GV);
  261. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  262. if (D.hasAttr<AnnotateAttr>())
  263. CGM.AddGlobalAnnotations(&D, GV);
  264. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  265. GV->setSection(SA->getName());
  266. if (D.hasAttr<UsedAttr>())
  267. CGM.AddUsedGlobal(GV);
  268. // We may have to cast the constant because of the initializer
  269. // mismatch above.
  270. //
  271. // FIXME: It is really dangerous to store this in the map; if anyone
  272. // RAUW's the GV uses of this constant will be invalid.
  273. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
  274. llvm::Type *LPtrTy =
  275. LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
  276. llvm::Constant *CastedVal = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
  277. DMEntry = CastedVal;
  278. CGM.setStaticLocalDeclAddress(&D, CastedVal);
  279. // Emit global variable debug descriptor for static vars.
  280. CGDebugInfo *DI = getDebugInfo();
  281. if (DI) {
  282. DI->setLocation(D.getLocation());
  283. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
  284. }
  285. }
  286. namespace {
  287. struct DestroyObject : EHScopeStack::Cleanup {
  288. DestroyObject(llvm::Value *addr, QualType type,
  289. CodeGenFunction::Destroyer *destroyer,
  290. bool useEHCleanupForArray)
  291. : addr(addr), type(type), destroyer(destroyer),
  292. useEHCleanupForArray(useEHCleanupForArray) {}
  293. llvm::Value *addr;
  294. QualType type;
  295. CodeGenFunction::Destroyer *destroyer;
  296. bool useEHCleanupForArray;
  297. void Emit(CodeGenFunction &CGF, Flags flags) {
  298. // Don't use an EH cleanup recursively from an EH cleanup.
  299. bool useEHCleanupForArray =
  300. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  301. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  302. }
  303. };
  304. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  305. DestroyNRVOVariable(llvm::Value *addr,
  306. const CXXDestructorDecl *Dtor,
  307. llvm::Value *NRVOFlag)
  308. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  309. const CXXDestructorDecl *Dtor;
  310. llvm::Value *NRVOFlag;
  311. llvm::Value *Loc;
  312. void Emit(CodeGenFunction &CGF, Flags flags) {
  313. // Along the exceptions path we always execute the dtor.
  314. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  315. llvm::BasicBlock *SkipDtorBB = 0;
  316. if (NRVO) {
  317. // If we exited via NRVO, we skip the destructor call.
  318. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  319. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  320. llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
  321. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  322. CGF.EmitBlock(RunDtorBB);
  323. }
  324. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  325. /*ForVirtualBase=*/false, Loc);
  326. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  327. }
  328. };
  329. struct CallStackRestore : EHScopeStack::Cleanup {
  330. llvm::Value *Stack;
  331. CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
  332. void Emit(CodeGenFunction &CGF, Flags flags) {
  333. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  334. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  335. CGF.Builder.CreateCall(F, V);
  336. }
  337. };
  338. struct ExtendGCLifetime : EHScopeStack::Cleanup {
  339. const VarDecl &Var;
  340. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  341. void Emit(CodeGenFunction &CGF, Flags flags) {
  342. // Compute the address of the local variable, in case it's a
  343. // byref or something.
  344. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  345. Var.getType(), VK_LValue, SourceLocation());
  346. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
  347. CGF.EmitExtendGCLifetime(value);
  348. }
  349. };
  350. struct CallCleanupFunction : EHScopeStack::Cleanup {
  351. llvm::Constant *CleanupFn;
  352. const CGFunctionInfo &FnInfo;
  353. const VarDecl &Var;
  354. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  355. const VarDecl *Var)
  356. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  357. void Emit(CodeGenFunction &CGF, Flags flags) {
  358. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  359. Var.getType(), VK_LValue, SourceLocation());
  360. // Compute the address of the local variable, in case it's a byref
  361. // or something.
  362. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
  363. // In some cases, the type of the function argument will be different from
  364. // the type of the pointer. An example of this is
  365. // void f(void* arg);
  366. // __attribute__((cleanup(f))) void *g;
  367. //
  368. // To fix this we insert a bitcast here.
  369. QualType ArgTy = FnInfo.arg_begin()->type;
  370. llvm::Value *Arg =
  371. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  372. CallArgList Args;
  373. Args.add(RValue::get(Arg),
  374. CGF.getContext().getPointerType(Var.getType()));
  375. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  376. }
  377. };
  378. }
  379. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  380. /// variable with lifetime.
  381. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  382. llvm::Value *addr,
  383. Qualifiers::ObjCLifetime lifetime) {
  384. switch (lifetime) {
  385. case Qualifiers::OCL_None:
  386. llvm_unreachable("present but none");
  387. case Qualifiers::OCL_ExplicitNone:
  388. // nothing to do
  389. break;
  390. case Qualifiers::OCL_Strong: {
  391. CodeGenFunction::Destroyer *destroyer =
  392. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  393. ? CodeGenFunction::destroyARCStrongPrecise
  394. : CodeGenFunction::destroyARCStrongImprecise);
  395. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  396. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  397. cleanupKind & EHCleanup);
  398. break;
  399. }
  400. case Qualifiers::OCL_Autoreleasing:
  401. // nothing to do
  402. break;
  403. case Qualifiers::OCL_Weak:
  404. // __weak objects always get EH cleanups; otherwise, exceptions
  405. // could cause really nasty crashes instead of mere leaks.
  406. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  407. CodeGenFunction::destroyARCWeak,
  408. /*useEHCleanup*/ true);
  409. break;
  410. }
  411. }
  412. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  413. if (const Expr *e = dyn_cast<Expr>(s)) {
  414. // Skip the most common kinds of expressions that make
  415. // hierarchy-walking expensive.
  416. s = e = e->IgnoreParenCasts();
  417. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  418. return (ref->getDecl() == &var);
  419. }
  420. for (Stmt::const_child_range children = s->children(); children; ++children)
  421. // children might be null; as in missing decl or conditional of an if-stmt.
  422. if ((*children) && isAccessedBy(var, *children))
  423. return true;
  424. return false;
  425. }
  426. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  427. if (!decl) return false;
  428. if (!isa<VarDecl>(decl)) return false;
  429. const VarDecl *var = cast<VarDecl>(decl);
  430. return isAccessedBy(*var, e);
  431. }
  432. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  433. LValue &lvalue,
  434. const VarDecl *var) {
  435. lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
  436. }
  437. void CodeGenFunction::EmitScalarInit(const Expr *init,
  438. const ValueDecl *D,
  439. LValue lvalue,
  440. bool capturedByInit) {
  441. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  442. if (!lifetime) {
  443. llvm::Value *value = EmitScalarExpr(init);
  444. if (capturedByInit)
  445. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  446. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  447. return;
  448. }
  449. // If we're emitting a value with lifetime, we have to do the
  450. // initialization *before* we leave the cleanup scopes.
  451. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  452. enterFullExpression(ewc);
  453. init = ewc->getSubExpr();
  454. }
  455. CodeGenFunction::RunCleanupsScope Scope(*this);
  456. // We have to maintain the illusion that the variable is
  457. // zero-initialized. If the variable might be accessed in its
  458. // initializer, zero-initialize before running the initializer, then
  459. // actually perform the initialization with an assign.
  460. bool accessedByInit = false;
  461. if (lifetime != Qualifiers::OCL_ExplicitNone)
  462. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  463. if (accessedByInit) {
  464. LValue tempLV = lvalue;
  465. // Drill down to the __block object if necessary.
  466. if (capturedByInit) {
  467. // We can use a simple GEP for this because it can't have been
  468. // moved yet.
  469. tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
  470. getByRefValueLLVMField(cast<VarDecl>(D))));
  471. }
  472. llvm::PointerType *ty
  473. = cast<llvm::PointerType>(tempLV.getAddress()->getType());
  474. ty = cast<llvm::PointerType>(ty->getElementType());
  475. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  476. // If __weak, we want to use a barrier under certain conditions.
  477. if (lifetime == Qualifiers::OCL_Weak)
  478. EmitARCInitWeak(tempLV.getAddress(), zero);
  479. // Otherwise just do a simple store.
  480. else
  481. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  482. }
  483. // Emit the initializer.
  484. llvm::Value *value = 0;
  485. switch (lifetime) {
  486. case Qualifiers::OCL_None:
  487. llvm_unreachable("present but none");
  488. case Qualifiers::OCL_ExplicitNone:
  489. // nothing to do
  490. value = EmitScalarExpr(init);
  491. break;
  492. case Qualifiers::OCL_Strong: {
  493. value = EmitARCRetainScalarExpr(init);
  494. break;
  495. }
  496. case Qualifiers::OCL_Weak: {
  497. // No way to optimize a producing initializer into this. It's not
  498. // worth optimizing for, because the value will immediately
  499. // disappear in the common case.
  500. value = EmitScalarExpr(init);
  501. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  502. if (accessedByInit)
  503. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  504. else
  505. EmitARCInitWeak(lvalue.getAddress(), value);
  506. return;
  507. }
  508. case Qualifiers::OCL_Autoreleasing:
  509. value = EmitARCRetainAutoreleaseScalarExpr(init);
  510. break;
  511. }
  512. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  513. // If the variable might have been accessed by its initializer, we
  514. // might have to initialize with a barrier. We have to do this for
  515. // both __weak and __strong, but __weak got filtered out above.
  516. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  517. llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
  518. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  519. EmitARCRelease(oldValue, /*precise*/ false);
  520. return;
  521. }
  522. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  523. }
  524. /// EmitScalarInit - Initialize the given lvalue with the given object.
  525. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  526. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  527. if (!lifetime)
  528. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  529. switch (lifetime) {
  530. case Qualifiers::OCL_None:
  531. llvm_unreachable("present but none");
  532. case Qualifiers::OCL_ExplicitNone:
  533. // nothing to do
  534. break;
  535. case Qualifiers::OCL_Strong:
  536. init = EmitARCRetain(lvalue.getType(), init);
  537. break;
  538. case Qualifiers::OCL_Weak:
  539. // Initialize and then skip the primitive store.
  540. EmitARCInitWeak(lvalue.getAddress(), init);
  541. return;
  542. case Qualifiers::OCL_Autoreleasing:
  543. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  544. break;
  545. }
  546. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  547. }
  548. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  549. /// non-zero parts of the specified initializer with equal or fewer than
  550. /// NumStores scalar stores.
  551. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  552. unsigned &NumStores) {
  553. // Zero and Undef never requires any extra stores.
  554. if (isa<llvm::ConstantAggregateZero>(Init) ||
  555. isa<llvm::ConstantPointerNull>(Init) ||
  556. isa<llvm::UndefValue>(Init))
  557. return true;
  558. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  559. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  560. isa<llvm::ConstantExpr>(Init))
  561. return Init->isNullValue() || NumStores--;
  562. // See if we can emit each element.
  563. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  564. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  565. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  566. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  567. return false;
  568. }
  569. return true;
  570. }
  571. if (llvm::ConstantDataSequential *CDS =
  572. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  573. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  574. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  575. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  576. return false;
  577. }
  578. return true;
  579. }
  580. // Anything else is hard and scary.
  581. return false;
  582. }
  583. /// emitStoresForInitAfterMemset - For inits that
  584. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  585. /// stores that would be required.
  586. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  587. bool isVolatile, CGBuilderTy &Builder) {
  588. // Zero doesn't require a store.
  589. if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
  590. return;
  591. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  592. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  593. isa<llvm::ConstantExpr>(Init)) {
  594. Builder.CreateStore(Init, Loc, isVolatile);
  595. return;
  596. }
  597. if (llvm::ConstantDataSequential *CDS =
  598. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  599. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  600. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  601. // Get a pointer to the element and emit it.
  602. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  603. isVolatile, Builder);
  604. }
  605. return;
  606. }
  607. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  608. "Unknown value type!");
  609. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  610. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  611. // Get a pointer to the element and emit it.
  612. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  613. isVolatile, Builder);
  614. }
  615. }
  616. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  617. /// plus some stores to initialize a local variable instead of using a memcpy
  618. /// from a constant global. It is beneficial to use memset if the global is all
  619. /// zeros, or mostly zeros and large.
  620. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  621. uint64_t GlobalSize) {
  622. // If a global is all zeros, always use a memset.
  623. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  624. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  625. // do it if it will require 6 or fewer scalar stores.
  626. // TODO: Should budget depends on the size? Avoiding a large global warrants
  627. // plopping in more stores.
  628. unsigned StoreBudget = 6;
  629. uint64_t SizeLimit = 32;
  630. return GlobalSize > SizeLimit &&
  631. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  632. }
  633. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  634. /// variable declaration with auto, register, or no storage class specifier.
  635. /// These turn into simple stack objects, or GlobalValues depending on target.
  636. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  637. AutoVarEmission emission = EmitAutoVarAlloca(D);
  638. EmitAutoVarInit(emission);
  639. EmitAutoVarCleanups(emission);
  640. }
  641. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  642. /// local variable. Does not emit initalization or destruction.
  643. CodeGenFunction::AutoVarEmission
  644. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  645. QualType Ty = D.getType();
  646. AutoVarEmission emission(D);
  647. bool isByRef = D.hasAttr<BlocksAttr>();
  648. emission.IsByRef = isByRef;
  649. CharUnits alignment = getContext().getDeclAlign(&D);
  650. emission.Alignment = alignment;
  651. // If the type is variably-modified, emit all the VLA sizes for it.
  652. if (Ty->isVariablyModifiedType())
  653. EmitVariablyModifiedType(Ty);
  654. llvm::Value *DeclPtr;
  655. if (Ty->isConstantSizeType()) {
  656. if (!Target.useGlobalsForAutomaticVariables()) {
  657. bool NRVO = getContext().getLangOpts().ElideConstructors &&
  658. D.isNRVOVariable();
  659. // If this value is a POD array or struct with a statically
  660. // determinable constant initializer, there are optimizations we can do.
  661. //
  662. // TODO: We should constant-evaluate the initializer of any variable,
  663. // as long as it is initialized by a constant expression. Currently,
  664. // isConstantInitializer produces wrong answers for structs with
  665. // reference or bitfield members, and a few other cases, and checking
  666. // for POD-ness protects us from some of these.
  667. if (D.getInit() &&
  668. (Ty->isArrayType() || Ty->isRecordType()) &&
  669. (Ty.isPODType(getContext()) ||
  670. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  671. D.getInit()->isConstantInitializer(getContext(), false)) {
  672. // If the variable's a const type, and it's neither an NRVO
  673. // candidate nor a __block variable and has no mutable members,
  674. // emit it as a global instead.
  675. if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  676. CGM.isTypeConstant(Ty, true)) {
  677. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  678. emission.Address = 0; // signal this condition to later callbacks
  679. assert(emission.wasEmittedAsGlobal());
  680. return emission;
  681. }
  682. // Otherwise, tell the initialization code that we're in this case.
  683. emission.IsConstantAggregate = true;
  684. }
  685. // A normal fixed sized variable becomes an alloca in the entry block,
  686. // unless it's an NRVO variable.
  687. llvm::Type *LTy = ConvertTypeForMem(Ty);
  688. if (NRVO) {
  689. // The named return value optimization: allocate this variable in the
  690. // return slot, so that we can elide the copy when returning this
  691. // variable (C++0x [class.copy]p34).
  692. DeclPtr = ReturnValue;
  693. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  694. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  695. // Create a flag that is used to indicate when the NRVO was applied
  696. // to this variable. Set it to zero to indicate that NRVO was not
  697. // applied.
  698. llvm::Value *Zero = Builder.getFalse();
  699. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  700. EnsureInsertPoint();
  701. Builder.CreateStore(Zero, NRVOFlag);
  702. // Record the NRVO flag for this variable.
  703. NRVOFlags[&D] = NRVOFlag;
  704. emission.NRVOFlag = NRVOFlag;
  705. }
  706. }
  707. } else {
  708. if (isByRef)
  709. LTy = BuildByRefType(&D);
  710. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  711. Alloc->setName(D.getName());
  712. CharUnits allocaAlignment = alignment;
  713. if (isByRef)
  714. allocaAlignment = std::max(allocaAlignment,
  715. getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
  716. Alloc->setAlignment(allocaAlignment.getQuantity());
  717. DeclPtr = Alloc;
  718. }
  719. } else {
  720. // Targets that don't support recursion emit locals as globals.
  721. const char *Class =
  722. D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
  723. DeclPtr = CreateStaticVarDecl(D, Class,
  724. llvm::GlobalValue::InternalLinkage);
  725. }
  726. } else {
  727. EnsureInsertPoint();
  728. if (!DidCallStackSave) {
  729. // Save the stack.
  730. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  731. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  732. llvm::Value *V = Builder.CreateCall(F);
  733. Builder.CreateStore(V, Stack);
  734. DidCallStackSave = true;
  735. // Push a cleanup block and restore the stack there.
  736. // FIXME: in general circumstances, this should be an EH cleanup.
  737. EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
  738. }
  739. llvm::Value *elementCount;
  740. QualType elementType;
  741. llvm::tie(elementCount, elementType) = getVLASize(Ty);
  742. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  743. // Allocate memory for the array.
  744. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  745. vla->setAlignment(alignment.getQuantity());
  746. DeclPtr = vla;
  747. }
  748. llvm::Value *&DMEntry = LocalDeclMap[&D];
  749. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  750. DMEntry = DeclPtr;
  751. emission.Address = DeclPtr;
  752. // Emit debug info for local var declaration.
  753. if (HaveInsertPoint())
  754. if (CGDebugInfo *DI = getDebugInfo()) {
  755. DI->setLocation(D.getLocation());
  756. if (Target.useGlobalsForAutomaticVariables()) {
  757. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
  758. } else
  759. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  760. }
  761. if (D.hasAttr<AnnotateAttr>())
  762. EmitVarAnnotations(&D, emission.Address);
  763. return emission;
  764. }
  765. /// Determines whether the given __block variable is potentially
  766. /// captured by the given expression.
  767. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  768. // Skip the most common kinds of expressions that make
  769. // hierarchy-walking expensive.
  770. e = e->IgnoreParenCasts();
  771. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  772. const BlockDecl *block = be->getBlockDecl();
  773. for (BlockDecl::capture_const_iterator i = block->capture_begin(),
  774. e = block->capture_end(); i != e; ++i) {
  775. if (i->getVariable() == &var)
  776. return true;
  777. }
  778. // No need to walk into the subexpressions.
  779. return false;
  780. }
  781. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  782. const CompoundStmt *CS = SE->getSubStmt();
  783. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  784. BE = CS->body_end(); BI != BE; ++BI)
  785. if (Expr *E = dyn_cast<Expr>((*BI))) {
  786. if (isCapturedBy(var, E))
  787. return true;
  788. }
  789. else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
  790. // special case declarations
  791. for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
  792. I != E; ++I) {
  793. if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
  794. Expr *Init = VD->getInit();
  795. if (Init && isCapturedBy(var, Init))
  796. return true;
  797. }
  798. }
  799. }
  800. else
  801. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  802. // Later, provide code to poke into statements for capture analysis.
  803. return true;
  804. return false;
  805. }
  806. for (Stmt::const_child_range children = e->children(); children; ++children)
  807. if (isCapturedBy(var, cast<Expr>(*children)))
  808. return true;
  809. return false;
  810. }
  811. /// \brief Determine whether the given initializer is trivial in the sense
  812. /// that it requires no code to be generated.
  813. static bool isTrivialInitializer(const Expr *Init) {
  814. if (!Init)
  815. return true;
  816. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  817. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  818. if (Constructor->isTrivial() &&
  819. Constructor->isDefaultConstructor() &&
  820. !Construct->requiresZeroInitialization())
  821. return true;
  822. return false;
  823. }
  824. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  825. assert(emission.Variable && "emission was not valid!");
  826. // If this was emitted as a global constant, we're done.
  827. if (emission.wasEmittedAsGlobal()) return;
  828. const VarDecl &D = *emission.Variable;
  829. QualType type = D.getType();
  830. // If this local has an initializer, emit it now.
  831. const Expr *Init = D.getInit();
  832. // If we are at an unreachable point, we don't need to emit the initializer
  833. // unless it contains a label.
  834. if (!HaveInsertPoint()) {
  835. if (!Init || !ContainsLabel(Init)) return;
  836. EnsureInsertPoint();
  837. }
  838. // Initialize the structure of a __block variable.
  839. if (emission.IsByRef)
  840. emitByrefStructureInit(emission);
  841. if (isTrivialInitializer(Init))
  842. return;
  843. CharUnits alignment = emission.Alignment;
  844. // Check whether this is a byref variable that's potentially
  845. // captured and moved by its own initializer. If so, we'll need to
  846. // emit the initializer first, then copy into the variable.
  847. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  848. llvm::Value *Loc =
  849. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  850. llvm::Constant *constant = 0;
  851. if (emission.IsConstantAggregate) {
  852. assert(!capturedByInit && "constant init contains a capturing block?");
  853. constant = CGM.EmitConstantInit(D, this);
  854. }
  855. if (!constant) {
  856. LValue lv = MakeAddrLValue(Loc, type, alignment);
  857. lv.setNonGC(true);
  858. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  859. }
  860. // If this is a simple aggregate initialization, we can optimize it
  861. // in various ways.
  862. bool isVolatile = type.isVolatileQualified();
  863. llvm::Value *SizeVal =
  864. llvm::ConstantInt::get(IntPtrTy,
  865. getContext().getTypeSizeInChars(type).getQuantity());
  866. llvm::Type *BP = Int8PtrTy;
  867. if (Loc->getType() != BP)
  868. Loc = Builder.CreateBitCast(Loc, BP);
  869. // If the initializer is all or mostly zeros, codegen with memset then do
  870. // a few stores afterward.
  871. if (shouldUseMemSetPlusStoresToInitialize(constant,
  872. CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
  873. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  874. alignment.getQuantity(), isVolatile);
  875. if (!constant->isNullValue()) {
  876. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  877. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  878. }
  879. } else {
  880. // Otherwise, create a temporary global with the initializer then
  881. // memcpy from the global to the alloca.
  882. std::string Name = GetStaticDeclName(*this, D, ".");
  883. llvm::GlobalVariable *GV =
  884. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  885. llvm::GlobalValue::PrivateLinkage,
  886. constant, Name, 0, false, 0);
  887. GV->setAlignment(alignment.getQuantity());
  888. GV->setUnnamedAddr(true);
  889. llvm::Value *SrcPtr = GV;
  890. if (SrcPtr->getType() != BP)
  891. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  892. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  893. isVolatile);
  894. }
  895. }
  896. /// Emit an expression as an initializer for a variable at the given
  897. /// location. The expression is not necessarily the normal
  898. /// initializer for the variable, and the address is not necessarily
  899. /// its normal location.
  900. ///
  901. /// \param init the initializing expression
  902. /// \param var the variable to act as if we're initializing
  903. /// \param loc the address to initialize; its type is a pointer
  904. /// to the LLVM mapping of the variable's type
  905. /// \param alignment the alignment of the address
  906. /// \param capturedByInit true if the variable is a __block variable
  907. /// whose address is potentially changed by the initializer
  908. void CodeGenFunction::EmitExprAsInit(const Expr *init,
  909. const ValueDecl *D,
  910. LValue lvalue,
  911. bool capturedByInit) {
  912. QualType type = D->getType();
  913. if (type->isReferenceType()) {
  914. RValue rvalue = EmitReferenceBindingToExpr(init, D);
  915. if (capturedByInit)
  916. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  917. EmitStoreThroughLValue(rvalue, lvalue, true);
  918. } else if (!hasAggregateLLVMType(type)) {
  919. EmitScalarInit(init, D, lvalue, capturedByInit);
  920. } else if (type->isAnyComplexType()) {
  921. ComplexPairTy complex = EmitComplexExpr(init);
  922. if (capturedByInit)
  923. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  924. StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
  925. } else {
  926. // TODO: how can we delay here if D is captured by its initializer?
  927. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  928. AggValueSlot::IsDestructed,
  929. AggValueSlot::DoesNotNeedGCBarriers,
  930. AggValueSlot::IsNotAliased));
  931. MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
  932. }
  933. }
  934. /// Enter a destroy cleanup for the given local variable.
  935. void CodeGenFunction::emitAutoVarTypeCleanup(
  936. const CodeGenFunction::AutoVarEmission &emission,
  937. QualType::DestructionKind dtorKind) {
  938. assert(dtorKind != QualType::DK_none);
  939. // Note that for __block variables, we want to destroy the
  940. // original stack object, not the possibly forwarded object.
  941. llvm::Value *addr = emission.getObjectAddress(*this);
  942. const VarDecl *var = emission.Variable;
  943. QualType type = var->getType();
  944. CleanupKind cleanupKind = NormalAndEHCleanup;
  945. CodeGenFunction::Destroyer *destroyer = 0;
  946. switch (dtorKind) {
  947. case QualType::DK_none:
  948. llvm_unreachable("no cleanup for trivially-destructible variable");
  949. case QualType::DK_cxx_destructor:
  950. // If there's an NRVO flag on the emission, we need a different
  951. // cleanup.
  952. if (emission.NRVOFlag) {
  953. assert(!type->isArrayType());
  954. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  955. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  956. emission.NRVOFlag);
  957. return;
  958. }
  959. break;
  960. case QualType::DK_objc_strong_lifetime:
  961. // Suppress cleanups for pseudo-strong variables.
  962. if (var->isARCPseudoStrong()) return;
  963. // Otherwise, consider whether to use an EH cleanup or not.
  964. cleanupKind = getARCCleanupKind();
  965. // Use the imprecise destroyer by default.
  966. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  967. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  968. break;
  969. case QualType::DK_objc_weak_lifetime:
  970. break;
  971. }
  972. // If we haven't chosen a more specific destroyer, use the default.
  973. if (!destroyer) destroyer = getDestroyer(dtorKind);
  974. // Use an EH cleanup in array destructors iff the destructor itself
  975. // is being pushed as an EH cleanup.
  976. bool useEHCleanup = (cleanupKind & EHCleanup);
  977. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  978. useEHCleanup);
  979. }
  980. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  981. assert(emission.Variable && "emission was not valid!");
  982. // If this was emitted as a global constant, we're done.
  983. if (emission.wasEmittedAsGlobal()) return;
  984. const VarDecl &D = *emission.Variable;
  985. // Check the type for a cleanup.
  986. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  987. emitAutoVarTypeCleanup(emission, dtorKind);
  988. // In GC mode, honor objc_precise_lifetime.
  989. if (getLangOpts().getGC() != LangOptions::NonGC &&
  990. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  991. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  992. }
  993. // Handle the cleanup attribute.
  994. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  995. const FunctionDecl *FD = CA->getFunctionDecl();
  996. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  997. assert(F && "Could not find function!");
  998. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  999. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1000. }
  1001. // If this is a block variable, call _Block_object_destroy
  1002. // (on the unforwarded address).
  1003. if (emission.IsByRef)
  1004. enterByrefCleanup(emission);
  1005. }
  1006. CodeGenFunction::Destroyer *
  1007. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1008. switch (kind) {
  1009. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1010. case QualType::DK_cxx_destructor:
  1011. return destroyCXXObject;
  1012. case QualType::DK_objc_strong_lifetime:
  1013. return destroyARCStrongPrecise;
  1014. case QualType::DK_objc_weak_lifetime:
  1015. return destroyARCWeak;
  1016. }
  1017. llvm_unreachable("Unknown DestructionKind");
  1018. }
  1019. /// pushDestroy - Push the standard destructor for the given type.
  1020. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1021. llvm::Value *addr, QualType type) {
  1022. assert(dtorKind && "cannot push destructor for trivial type");
  1023. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1024. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1025. cleanupKind & EHCleanup);
  1026. }
  1027. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1028. QualType type, Destroyer *destroyer,
  1029. bool useEHCleanupForArray) {
  1030. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1031. destroyer, useEHCleanupForArray);
  1032. }
  1033. /// emitDestroy - Immediately perform the destruction of the given
  1034. /// object.
  1035. ///
  1036. /// \param addr - the address of the object; a type*
  1037. /// \param type - the type of the object; if an array type, all
  1038. /// objects are destroyed in reverse order
  1039. /// \param destroyer - the function to call to destroy individual
  1040. /// elements
  1041. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1042. /// used when destroying array elements, in case one of the
  1043. /// destructions throws an exception
  1044. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1045. Destroyer *destroyer,
  1046. bool useEHCleanupForArray) {
  1047. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1048. if (!arrayType)
  1049. return destroyer(*this, addr, type);
  1050. llvm::Value *begin = addr;
  1051. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1052. // Normally we have to check whether the array is zero-length.
  1053. bool checkZeroLength = true;
  1054. // But if the array length is constant, we can suppress that.
  1055. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1056. // ...and if it's constant zero, we can just skip the entire thing.
  1057. if (constLength->isZero()) return;
  1058. checkZeroLength = false;
  1059. }
  1060. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1061. emitArrayDestroy(begin, end, type, destroyer,
  1062. checkZeroLength, useEHCleanupForArray);
  1063. }
  1064. /// emitArrayDestroy - Destroys all the elements of the given array,
  1065. /// beginning from last to first. The array cannot be zero-length.
  1066. ///
  1067. /// \param begin - a type* denoting the first element of the array
  1068. /// \param end - a type* denoting one past the end of the array
  1069. /// \param type - the element type of the array
  1070. /// \param destroyer - the function to call to destroy elements
  1071. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1072. /// the remaining elements in case the destruction of a single
  1073. /// element throws
  1074. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1075. llvm::Value *end,
  1076. QualType type,
  1077. Destroyer *destroyer,
  1078. bool checkZeroLength,
  1079. bool useEHCleanup) {
  1080. assert(!type->isArrayType());
  1081. // The basic structure here is a do-while loop, because we don't
  1082. // need to check for the zero-element case.
  1083. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1084. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1085. if (checkZeroLength) {
  1086. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1087. "arraydestroy.isempty");
  1088. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1089. }
  1090. // Enter the loop body, making that address the current address.
  1091. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1092. EmitBlock(bodyBB);
  1093. llvm::PHINode *elementPast =
  1094. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1095. elementPast->addIncoming(end, entryBB);
  1096. // Shift the address back by one element.
  1097. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1098. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1099. "arraydestroy.element");
  1100. if (useEHCleanup)
  1101. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1102. // Perform the actual destruction there.
  1103. destroyer(*this, element, type);
  1104. if (useEHCleanup)
  1105. PopCleanupBlock();
  1106. // Check whether we've reached the end.
  1107. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1108. Builder.CreateCondBr(done, doneBB, bodyBB);
  1109. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1110. // Done.
  1111. EmitBlock(doneBB);
  1112. }
  1113. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1114. /// emitArrayDestroy, the element type here may still be an array type.
  1115. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1116. llvm::Value *begin, llvm::Value *end,
  1117. QualType type,
  1118. CodeGenFunction::Destroyer *destroyer) {
  1119. // If the element type is itself an array, drill down.
  1120. unsigned arrayDepth = 0;
  1121. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1122. // VLAs don't require a GEP index to walk into.
  1123. if (!isa<VariableArrayType>(arrayType))
  1124. arrayDepth++;
  1125. type = arrayType->getElementType();
  1126. }
  1127. if (arrayDepth) {
  1128. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1129. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1130. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1131. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1132. }
  1133. // Destroy the array. We don't ever need an EH cleanup because we
  1134. // assume that we're in an EH cleanup ourselves, so a throwing
  1135. // destructor causes an immediate terminate.
  1136. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1137. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1138. }
  1139. namespace {
  1140. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1141. /// array destroy where the end pointer is regularly determined and
  1142. /// does not need to be loaded from a local.
  1143. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1144. llvm::Value *ArrayBegin;
  1145. llvm::Value *ArrayEnd;
  1146. QualType ElementType;
  1147. CodeGenFunction::Destroyer *Destroyer;
  1148. public:
  1149. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1150. QualType elementType,
  1151. CodeGenFunction::Destroyer *destroyer)
  1152. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1153. ElementType(elementType), Destroyer(destroyer) {}
  1154. void Emit(CodeGenFunction &CGF, Flags flags) {
  1155. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1156. ElementType, Destroyer);
  1157. }
  1158. };
  1159. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1160. /// partial array destroy where the end pointer is irregularly
  1161. /// determined and must be loaded from a local.
  1162. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1163. llvm::Value *ArrayBegin;
  1164. llvm::Value *ArrayEndPointer;
  1165. QualType ElementType;
  1166. CodeGenFunction::Destroyer *Destroyer;
  1167. public:
  1168. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1169. llvm::Value *arrayEndPointer,
  1170. QualType elementType,
  1171. CodeGenFunction::Destroyer *destroyer)
  1172. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1173. ElementType(elementType), Destroyer(destroyer) {}
  1174. void Emit(CodeGenFunction &CGF, Flags flags) {
  1175. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1176. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1177. ElementType, Destroyer);
  1178. }
  1179. };
  1180. }
  1181. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1182. /// already-constructed elements of the given array. The cleanup
  1183. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1184. ///
  1185. /// \param elementType - the immediate element type of the array;
  1186. /// possibly still an array type
  1187. /// \param array - a value of type elementType*
  1188. /// \param destructionKind - the kind of destruction required
  1189. /// \param initializedElementCount - a value of type size_t* holding
  1190. /// the number of successfully-constructed elements
  1191. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1192. llvm::Value *arrayEndPointer,
  1193. QualType elementType,
  1194. Destroyer *destroyer) {
  1195. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1196. arrayBegin, arrayEndPointer,
  1197. elementType, destroyer);
  1198. }
  1199. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1200. /// already-constructed elements of the given array. The cleanup
  1201. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1202. ///
  1203. /// \param elementType - the immediate element type of the array;
  1204. /// possibly still an array type
  1205. /// \param array - a value of type elementType*
  1206. /// \param destructionKind - the kind of destruction required
  1207. /// \param initializedElementCount - a value of type size_t* holding
  1208. /// the number of successfully-constructed elements
  1209. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1210. llvm::Value *arrayEnd,
  1211. QualType elementType,
  1212. Destroyer *destroyer) {
  1213. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1214. arrayBegin, arrayEnd,
  1215. elementType, destroyer);
  1216. }
  1217. namespace {
  1218. /// A cleanup to perform a release of an object at the end of a
  1219. /// function. This is used to balance out the incoming +1 of a
  1220. /// ns_consumed argument when we can't reasonably do that just by
  1221. /// not doing the initial retain for a __block argument.
  1222. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1223. ConsumeARCParameter(llvm::Value *param) : Param(param) {}
  1224. llvm::Value *Param;
  1225. void Emit(CodeGenFunction &CGF, Flags flags) {
  1226. CGF.EmitARCRelease(Param, /*precise*/ false);
  1227. }
  1228. };
  1229. }
  1230. /// Emit an alloca (or GlobalValue depending on target)
  1231. /// for the specified parameter and set up LocalDeclMap.
  1232. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1233. unsigned ArgNo) {
  1234. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1235. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1236. "Invalid argument to EmitParmDecl");
  1237. Arg->setName(D.getName());
  1238. // Use better IR generation for certain implicit parameters.
  1239. if (isa<ImplicitParamDecl>(D)) {
  1240. // The only implicit argument a block has is its literal.
  1241. if (BlockInfo) {
  1242. LocalDeclMap[&D] = Arg;
  1243. if (CGDebugInfo *DI = getDebugInfo()) {
  1244. DI->setLocation(D.getLocation());
  1245. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
  1246. }
  1247. return;
  1248. }
  1249. }
  1250. QualType Ty = D.getType();
  1251. llvm::Value *DeclPtr;
  1252. // If this is an aggregate or variable sized value, reuse the input pointer.
  1253. if (!Ty->isConstantSizeType() ||
  1254. CodeGenFunction::hasAggregateLLVMType(Ty)) {
  1255. DeclPtr = Arg;
  1256. } else {
  1257. // Otherwise, create a temporary to hold the value.
  1258. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1259. D.getName() + ".addr");
  1260. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1261. DeclPtr = Alloc;
  1262. bool doStore = true;
  1263. Qualifiers qs = Ty.getQualifiers();
  1264. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1265. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1266. // For __strong, it's handled by just skipping the initial retain;
  1267. // otherwise we have to balance out the initial +1 with an extra
  1268. // cleanup to do the release at the end of the function.
  1269. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1270. // 'self' is always formally __strong, but if this is not an
  1271. // init method then we don't want to retain it.
  1272. if (D.isARCPseudoStrong()) {
  1273. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1274. assert(&D == method->getSelfDecl());
  1275. assert(lt == Qualifiers::OCL_Strong);
  1276. assert(qs.hasConst());
  1277. assert(method->getMethodFamily() != OMF_init);
  1278. (void) method;
  1279. lt = Qualifiers::OCL_ExplicitNone;
  1280. }
  1281. if (lt == Qualifiers::OCL_Strong) {
  1282. if (!isConsumed)
  1283. // Don't use objc_retainBlock for block pointers, because we
  1284. // don't want to Block_copy something just because we got it
  1285. // as a parameter.
  1286. Arg = EmitARCRetainNonBlock(Arg);
  1287. } else {
  1288. // Push the cleanup for a consumed parameter.
  1289. if (isConsumed)
  1290. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
  1291. if (lt == Qualifiers::OCL_Weak) {
  1292. EmitARCInitWeak(DeclPtr, Arg);
  1293. doStore = false; // The weak init is a store, no need to do two.
  1294. }
  1295. }
  1296. // Enter the cleanup scope.
  1297. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1298. }
  1299. // Store the initial value into the alloca.
  1300. if (doStore) {
  1301. LValue lv = MakeAddrLValue(DeclPtr, Ty,
  1302. getContext().getDeclAlign(&D));
  1303. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1304. }
  1305. }
  1306. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1307. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  1308. DMEntry = DeclPtr;
  1309. // Emit debug info for param declaration.
  1310. if (CGDebugInfo *DI = getDebugInfo())
  1311. DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
  1312. if (D.hasAttr<AnnotateAttr>())
  1313. EmitVarAnnotations(&D, DeclPtr);
  1314. }