blob: cb15748646310ba3c84f54bfa97a0d38bc365795 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000034 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000048 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000049 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000051 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000052 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000053 case Decl::ImplicitParam:
54 case Decl::ClassTemplate:
55 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000056 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000057 case Decl::TemplateTemplateParm:
58 case Decl::ObjCMethod:
59 case Decl::ObjCCategory:
60 case Decl::ObjCProtocol:
61 case Decl::ObjCInterface:
62 case Decl::ObjCCategoryImpl:
63 case Decl::ObjCImplementation:
64 case Decl::ObjCProperty:
65 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000066 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::LinkageSpec:
68 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000069 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000073 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000075 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000076 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000077 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000079 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000080 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000082 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000083 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000084 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000085 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000086 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 // None of these decls require codegen support.
88 return;
David Blaikiec8c24272013-02-02 00:39:32 +000089
David Blaikiefc46ebc2013-05-20 22:50:41 +000090 case Decl::NamespaceAlias:
91 if (CGDebugInfo *DI = getDebugInfo())
92 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
93 return;
David Blaikie9faebd22013-05-20 04:58:53 +000094 case Decl::Using: // using X; [C++]
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitUsingDecl(cast<UsingDecl>(D));
97 return;
David Blaikie957dac52013-04-22 06:13:21 +000098 case Decl::UsingDirective: // using namespace X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
101 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000102 case Decl::Var: {
103 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000104 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000106 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Richard Smith162e1c12011-04-15 14:24:37 +0000109 case Decl::Typedef: // typedef int X;
110 case Decl::TypeAlias: { // using X = int; [C++0x]
111 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000112 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000114 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000115 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000116 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000117 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
119
John McCallb6bbcc92010-10-15 04:57:14 +0000120/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000122void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000123 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000124 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000125 llvm::GlobalValue::InternalLinkage;
126
John McCall8b242332010-05-25 04:30:21 +0000127 // If the function definition has some sort of weak linkage, its
128 // static variables should also be weak so that they get properly
129 // uniqued. We can't do this in C, though, because there's no
130 // standard way to agree on which variables are the same (i.e.
131 // there's no mangling).
Eli Friedman678eca42013-06-13 21:50:44 +0000132 if (getLangOpts().CPlusPlus) {
133 const Decl *D = CurCodeDecl;
134 while (true) {
135 if (isa<BlockDecl>(D)) {
136 // FIXME: Handle this case properly! (Should be similar to the
137 // way we handle lambdas in computeLVForDecl in Decl.cpp.)
138 break;
139 } else if (isa<CapturedDecl>(D)) {
140 D = cast<Decl>(cast<CapturedDecl>(D)->getParent());
141 } else {
142 break;
143 }
144 }
145 // FIXME: Do we really only care about FunctionDecls here?
146 if (D && isa<FunctionDecl>(D)) {
147 llvm::GlobalValue::LinkageTypes ParentLinkage =
148 CGM.getFunctionLinkage(cast<FunctionDecl>(D));
149 if (llvm::GlobalValue::isWeakForLinker(ParentLinkage))
150 Linkage = ParentLinkage;
151 }
152 }
Eric Christophere1f54902011-08-23 22:38:00 +0000153
John McCallb6bbcc92010-10-15 04:57:14 +0000154 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000155 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000156
157 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000158 // Don't emit it now, allow it to be emitted lazily on its first use.
159 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000160
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000161 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
162 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
163
164 assert(D.hasLocalStorage());
165 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000166}
167
Chris Lattner761acc12009-12-05 08:22:11 +0000168static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
169 const char *Separator) {
170 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000171 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000172 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000173 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000174 }
Eric Christophere1f54902011-08-23 22:38:00 +0000175
Chris Lattner761acc12009-12-05 08:22:11 +0000176 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000177 if (!CGF.CurFuncDecl) {
178 // Better be in a block declared in global scope.
179 const NamedDecl *ND = cast<NamedDecl>(&D);
180 const DeclContext *DC = ND->getDeclContext();
181 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
182 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000183 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000184 ContextName = Name.getString();
185 }
186 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000187 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000188 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000189 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000190 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000191 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000192 ContextName = CGF.CurFn->getName();
193 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000194 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000195
Chris Lattner761acc12009-12-05 08:22:11 +0000196 return ContextName + Separator + D.getNameAsString();
197}
198
Chandler Carruth0f30a122012-03-30 19:44:53 +0000199llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000200CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
201 const char *Separator,
202 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000203 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000204 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000205
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000206 // Use the label if the variable is renamed with the asm-label extension.
207 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000208 if (D.hasAttr<AsmLabelAttr>())
209 Name = CGM.getMangledName(&D);
210 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000211 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000212
Chris Lattner2acc6e32011-07-18 04:24:23 +0000213 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000214 unsigned AddrSpace =
215 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000216 llvm::GlobalVariable *GV =
217 new llvm::GlobalVariable(CGM.getModule(), LTy,
218 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000219 CGM.EmitNullConstant(D.getType()), Name, 0,
220 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000221 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000222 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000223 if (Linkage != llvm::GlobalValue::InternalLinkage)
224 GV->setVisibility(CurFn->getVisibility());
Hans Wennborgde981f32012-06-28 08:01:44 +0000225
Richard Smith38afbc72013-04-13 02:43:54 +0000226 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000227 CGM.setTLSMode(GV, D);
228
Anders Carlsson41f8a132009-09-26 18:16:06 +0000229 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000230}
231
Richard Smith7ca48502012-02-13 22:16:19 +0000232/// hasNontrivialDestruction - Determine whether a type's destruction is
233/// non-trivial. If so, and the variable uses static initialization, we must
234/// register its destructor to run on exit.
235static bool hasNontrivialDestruction(QualType T) {
236 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
237 return RD && !RD->hasTrivialDestructor();
238}
239
Chandler Carruth0f30a122012-03-30 19:44:53 +0000240/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
241/// global variable that has already been created for it. If the initializer
242/// has a different type than GV does, this may free GV and return a different
243/// one. Otherwise it just returns GV.
244llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000245CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000246 llvm::GlobalVariable *GV) {
247 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000248
Chris Lattner761acc12009-12-05 08:22:11 +0000249 // If constant emission failed, then this should be a C++ static
250 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000251 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000252 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000253 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000254 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000255 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000256 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000257 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000258
Chandler Carruth0f30a122012-03-30 19:44:53 +0000259 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000260 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000261 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000262 }
John McCallbf40cb52010-07-15 23:40:35 +0000263
Chris Lattner761acc12009-12-05 08:22:11 +0000264 // The initializer may differ in type from the global. Rewrite
265 // the global to match the initializer. (We have to do this
266 // because some types, like unions, can't be completely represented
267 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000268 if (GV->getType()->getElementType() != Init->getType()) {
269 llvm::GlobalVariable *OldGV = GV;
270
271 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
272 OldGV->isConstant(),
273 OldGV->getLinkage(), Init, "",
274 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000275 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000276 CGM.getContext().getTargetAddressSpace(D.getType()));
277 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000278
Chris Lattner761acc12009-12-05 08:22:11 +0000279 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000280 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000281
Chris Lattner761acc12009-12-05 08:22:11 +0000282 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000283 llvm::Constant *NewPtrForOldDecl =
284 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
285 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000286
Chris Lattner761acc12009-12-05 08:22:11 +0000287 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000288 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000289 }
Eric Christophere1f54902011-08-23 22:38:00 +0000290
Chandler Carruth0f30a122012-03-30 19:44:53 +0000291 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
292 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000293
294 if (hasNontrivialDestruction(D.getType())) {
295 // We have a constant initializer, but a nontrivial destructor. We still
296 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000297 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000298 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000299 }
300
Chandler Carruth0f30a122012-03-30 19:44:53 +0000301 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000302}
303
John McCallb6bbcc92010-10-15 04:57:14 +0000304void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000305 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000306 llvm::Value *&DMEntry = LocalDeclMap[&D];
307 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000308
John McCall355bba72012-03-30 21:00:39 +0000309 // Check to see if we already have a global variable for this
310 // declaration. This can happen when double-emitting function
311 // bodies, e.g. with complete and base constructors.
312 llvm::Constant *addr =
313 CGM.getStaticLocalDeclAddress(&D);
314
315 llvm::GlobalVariable *var;
316 if (addr) {
317 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
318 } else {
319 addr = var = CreateStaticVarDecl(D, ".", Linkage);
320 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000321
Daniel Dunbare5731f82009-02-25 20:08:33 +0000322 // Store into LocalDeclMap before generating initializer to handle
323 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000324 DMEntry = addr;
325 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000326
John McCallfe67f3b2010-05-04 20:45:42 +0000327 // We can't have a VLA here, but we can have a pointer to a VLA,
328 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000329 // Make sure to evaluate VLA bounds now so that we have them for later.
330 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000331 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000332
John McCall355bba72012-03-30 21:00:39 +0000333 // Save the type in case adding the initializer forces a type change.
334 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000335
Chris Lattner761acc12009-12-05 08:22:11 +0000336 // If this value has an initializer, emit it.
337 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000338 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000339
John McCall355bba72012-03-30 21:00:39 +0000340 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000341
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000342 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000343 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000344
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000345 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000346 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000348 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000349 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000350
Chandler Carruth0f30a122012-03-30 19:44:53 +0000351 // We may have to cast the constant because of the initializer
352 // mismatch above.
353 //
354 // FIXME: It is really dangerous to store this in the map; if anyone
355 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000356 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
357 DMEntry = castedAddr;
358 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000359
360 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000361 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000362 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000363 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000364 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000365 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000366 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000367}
Mike Stump1eb44332009-09-09 15:08:12 +0000368
John McCallda65ea82010-07-13 20:32:21 +0000369namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000370 struct DestroyObject : EHScopeStack::Cleanup {
371 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000372 CodeGenFunction::Destroyer *destroyer,
373 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000374 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000375 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000376
John McCallbdc4d802011-07-09 01:37:26 +0000377 llvm::Value *addr;
378 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000379 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000380 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000381
John McCallad346f42011-07-12 20:27:29 +0000382 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000383 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000384 bool useEHCleanupForArray =
385 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000386
387 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000388 }
389 };
390
John McCallbdc4d802011-07-09 01:37:26 +0000391 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
392 DestroyNRVOVariable(llvm::Value *addr,
393 const CXXDestructorDecl *Dtor,
394 llvm::Value *NRVOFlag)
395 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000396
397 const CXXDestructorDecl *Dtor;
398 llvm::Value *NRVOFlag;
399 llvm::Value *Loc;
400
John McCallad346f42011-07-12 20:27:29 +0000401 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000402 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000403 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000404
405 llvm::BasicBlock *SkipDtorBB = 0;
406 if (NRVO) {
407 // If we exited via NRVO, we skip the destructor call.
408 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
409 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
410 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
411 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
412 CGF.EmitBlock(RunDtorBB);
413 }
Eric Christophere1f54902011-08-23 22:38:00 +0000414
John McCallda65ea82010-07-13 20:32:21 +0000415 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000416 /*ForVirtualBase=*/false,
417 /*Delegating=*/false,
418 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000419
420 if (NRVO) CGF.EmitBlock(SkipDtorBB);
421 }
422 };
John McCallda65ea82010-07-13 20:32:21 +0000423
John McCall1f0fca52010-07-21 07:22:38 +0000424 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000425 llvm::Value *Stack;
426 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000427 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000428 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000429 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
430 CGF.Builder.CreateCall(F, V);
431 }
432 };
433
John McCall0c24c802011-06-24 23:21:27 +0000434 struct ExtendGCLifetime : EHScopeStack::Cleanup {
435 const VarDecl &Var;
436 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
437
John McCallad346f42011-07-12 20:27:29 +0000438 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000439 // Compute the address of the local variable, in case it's a
440 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000441 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
442 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000443 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
444 CGF.EmitExtendGCLifetime(value);
445 }
446 };
447
John McCall1f0fca52010-07-21 07:22:38 +0000448 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000449 llvm::Constant *CleanupFn;
450 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000451 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000452
John McCalld8715092010-07-21 06:13:08 +0000453 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000454 const VarDecl *Var)
455 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000456
John McCallad346f42011-07-12 20:27:29 +0000457 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000458 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
459 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000460 // Compute the address of the local variable, in case it's a byref
461 // or something.
462 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
463
John McCalld8715092010-07-21 06:13:08 +0000464 // In some cases, the type of the function argument will be different from
465 // the type of the pointer. An example of this is
466 // void f(void* arg);
467 // __attribute__((cleanup(f))) void *g;
468 //
469 // To fix this we insert a bitcast here.
470 QualType ArgTy = FnInfo.arg_begin()->type;
471 llvm::Value *Arg =
472 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
473
474 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000475 Args.add(RValue::get(Arg),
476 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000477 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
478 }
479 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000480
481 /// A cleanup to call @llvm.lifetime.end.
482 class CallLifetimeEnd : public EHScopeStack::Cleanup {
483 llvm::Value *Addr;
484 llvm::Value *Size;
485 public:
486 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
487 : Addr(addr), Size(size) {}
488
489 void Emit(CodeGenFunction &CGF, Flags flags) {
490 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
491 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
492 Size, castAddr)
493 ->setDoesNotThrow();
494 }
495 };
John McCalld8715092010-07-21 06:13:08 +0000496}
497
John McCallf85e1932011-06-15 23:02:42 +0000498/// EmitAutoVarWithLifetime - Does the setup required for an automatic
499/// variable with lifetime.
500static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
501 llvm::Value *addr,
502 Qualifiers::ObjCLifetime lifetime) {
503 switch (lifetime) {
504 case Qualifiers::OCL_None:
505 llvm_unreachable("present but none");
506
507 case Qualifiers::OCL_ExplicitNone:
508 // nothing to do
509 break;
510
511 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000512 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000513 (var.hasAttr<ObjCPreciseLifetimeAttr>()
514 ? CodeGenFunction::destroyARCStrongPrecise
515 : CodeGenFunction::destroyARCStrongImprecise);
516
517 CleanupKind cleanupKind = CGF.getARCCleanupKind();
518 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
519 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000520 break;
521 }
522 case Qualifiers::OCL_Autoreleasing:
523 // nothing to do
524 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000525
John McCallf85e1932011-06-15 23:02:42 +0000526 case Qualifiers::OCL_Weak:
527 // __weak objects always get EH cleanups; otherwise, exceptions
528 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000529 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
530 CodeGenFunction::destroyARCWeak,
531 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000532 break;
533 }
534}
535
536static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
537 if (const Expr *e = dyn_cast<Expr>(s)) {
538 // Skip the most common kinds of expressions that make
539 // hierarchy-walking expensive.
540 s = e = e->IgnoreParenCasts();
541
542 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
543 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000544 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
545 const BlockDecl *block = be->getBlockDecl();
546 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
547 e = block->capture_end(); i != e; ++i) {
548 if (i->getVariable() == &var)
549 return true;
550 }
551 }
John McCallf85e1932011-06-15 23:02:42 +0000552 }
553
554 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000555 // children might be null; as in missing decl or conditional of an if-stmt.
556 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000557 return true;
558
559 return false;
560}
561
562static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
563 if (!decl) return false;
564 if (!isa<VarDecl>(decl)) return false;
565 const VarDecl *var = cast<VarDecl>(decl);
566 return isAccessedBy(*var, e);
567}
568
John McCalla07398e2011-06-16 04:16:24 +0000569static void drillIntoBlockVariable(CodeGenFunction &CGF,
570 LValue &lvalue,
571 const VarDecl *var) {
572 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
573}
574
John McCallf85e1932011-06-15 23:02:42 +0000575void CodeGenFunction::EmitScalarInit(const Expr *init,
576 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000577 LValue lvalue,
578 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000579 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000580 if (!lifetime) {
581 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000582 if (capturedByInit)
583 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000584 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000585 return;
586 }
587
588 // If we're emitting a value with lifetime, we have to do the
589 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000590 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
591 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000592 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000593 }
594 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000595
596 // We have to maintain the illusion that the variable is
597 // zero-initialized. If the variable might be accessed in its
598 // initializer, zero-initialize before running the initializer, then
599 // actually perform the initialization with an assign.
600 bool accessedByInit = false;
601 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000602 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000603 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000604 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000605 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000606 if (capturedByInit) {
607 // We can use a simple GEP for this because it can't have been
608 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000609 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
610 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000611 }
612
Chris Lattner2acc6e32011-07-18 04:24:23 +0000613 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000614 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000615 ty = cast<llvm::PointerType>(ty->getElementType());
616
617 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000618
John McCallf85e1932011-06-15 23:02:42 +0000619 // If __weak, we want to use a barrier under certain conditions.
620 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000621 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000622
623 // Otherwise just do a simple store.
624 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000625 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000626 }
627
628 // Emit the initializer.
629 llvm::Value *value = 0;
630
631 switch (lifetime) {
632 case Qualifiers::OCL_None:
633 llvm_unreachable("present but none");
634
635 case Qualifiers::OCL_ExplicitNone:
636 // nothing to do
637 value = EmitScalarExpr(init);
638 break;
639
640 case Qualifiers::OCL_Strong: {
641 value = EmitARCRetainScalarExpr(init);
642 break;
643 }
644
645 case Qualifiers::OCL_Weak: {
646 // No way to optimize a producing initializer into this. It's not
647 // worth optimizing for, because the value will immediately
648 // disappear in the common case.
649 value = EmitScalarExpr(init);
650
John McCalla07398e2011-06-16 04:16:24 +0000651 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000652 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000653 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000654 else
John McCalla07398e2011-06-16 04:16:24 +0000655 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000656 return;
657 }
658
659 case Qualifiers::OCL_Autoreleasing:
660 value = EmitARCRetainAutoreleaseScalarExpr(init);
661 break;
662 }
663
John McCalla07398e2011-06-16 04:16:24 +0000664 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000665
666 // If the variable might have been accessed by its initializer, we
667 // might have to initialize with a barrier. We have to do this for
668 // both __weak and __strong, but __weak got filtered out above.
669 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000670 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000671 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000672 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000673 return;
674 }
675
David Chisnall7a7ee302012-01-16 17:27:18 +0000676 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000677}
Chris Lattner94cd0112010-12-01 02:05:19 +0000678
John McCall7acddac2011-06-17 06:42:21 +0000679/// EmitScalarInit - Initialize the given lvalue with the given object.
680void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
681 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
682 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000683 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000684
685 switch (lifetime) {
686 case Qualifiers::OCL_None:
687 llvm_unreachable("present but none");
688
689 case Qualifiers::OCL_ExplicitNone:
690 // nothing to do
691 break;
692
693 case Qualifiers::OCL_Strong:
694 init = EmitARCRetain(lvalue.getType(), init);
695 break;
696
697 case Qualifiers::OCL_Weak:
698 // Initialize and then skip the primitive store.
699 EmitARCInitWeak(lvalue.getAddress(), init);
700 return;
701
702 case Qualifiers::OCL_Autoreleasing:
703 init = EmitARCRetainAutorelease(lvalue.getType(), init);
704 break;
705 }
706
David Chisnall7a7ee302012-01-16 17:27:18 +0000707 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000708}
709
Chris Lattner94cd0112010-12-01 02:05:19 +0000710/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
711/// non-zero parts of the specified initializer with equal or fewer than
712/// NumStores scalar stores.
713static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
714 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000715 // Zero and Undef never requires any extra stores.
716 if (isa<llvm::ConstantAggregateZero>(Init) ||
717 isa<llvm::ConstantPointerNull>(Init) ||
718 isa<llvm::UndefValue>(Init))
719 return true;
720 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
721 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
722 isa<llvm::ConstantExpr>(Init))
723 return Init->isNullValue() || NumStores--;
724
725 // See if we can emit each element.
726 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
727 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
728 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
729 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
730 return false;
731 }
732 return true;
733 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000734
735 if (llvm::ConstantDataSequential *CDS =
736 dyn_cast<llvm::ConstantDataSequential>(Init)) {
737 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
738 llvm::Constant *Elt = CDS->getElementAsConstant(i);
739 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
740 return false;
741 }
742 return true;
743 }
Eric Christophere1f54902011-08-23 22:38:00 +0000744
Chris Lattner94cd0112010-12-01 02:05:19 +0000745 // Anything else is hard and scary.
746 return false;
747}
748
749/// emitStoresForInitAfterMemset - For inits that
750/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
751/// stores that would be required.
752static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000753 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000754 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
755 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000756
Chris Lattner70b02942010-12-02 01:58:41 +0000757 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
758 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
759 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000760 Builder.CreateStore(Init, Loc, isVolatile);
761 return;
762 }
763
764 if (llvm::ConstantDataSequential *CDS =
765 dyn_cast<llvm::ConstantDataSequential>(Init)) {
766 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
767 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000768
769 // If necessary, get a pointer to the element and emit it.
770 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
771 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
772 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000773 }
Chris Lattner70b02942010-12-02 01:58:41 +0000774 return;
775 }
Eric Christophere1f54902011-08-23 22:38:00 +0000776
Chris Lattner70b02942010-12-02 01:58:41 +0000777 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
778 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000779
Chris Lattner70b02942010-12-02 01:58:41 +0000780 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
781 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000782
783 // If necessary, get a pointer to the element and emit it.
784 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
785 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
786 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000787 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000788}
789
790
791/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
792/// plus some stores to initialize a local variable instead of using a memcpy
793/// from a constant global. It is beneficial to use memset if the global is all
794/// zeros, or mostly zeros and large.
795static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
796 uint64_t GlobalSize) {
797 // If a global is all zeros, always use a memset.
798 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
799
Chris Lattner94cd0112010-12-01 02:05:19 +0000800 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
801 // do it if it will require 6 or fewer scalar stores.
802 // TODO: Should budget depends on the size? Avoiding a large global warrants
803 // plopping in more stores.
804 unsigned StoreBudget = 6;
805 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000806
807 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000808 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
809}
810
Nadav Rotem495cfa42013-03-23 06:43:35 +0000811/// Should we use the LLVM lifetime intrinsics for the given local variable?
812static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
813 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000814 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
815 if (CGF.getLangOpts().Sanitize.UseAfterScope)
816 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000817 // For now, only in optimized builds.
818 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
819 return false;
820
821 // Limit the size of marked objects to 32 bytes. We don't want to increase
822 // compile time by marking tiny objects.
823 unsigned SizeThreshold = 32;
824
825 return Size > SizeThreshold;
826}
827
Chris Lattner94cd0112010-12-01 02:05:19 +0000828
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000829/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000830/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000831/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000832void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
833 AutoVarEmission emission = EmitAutoVarAlloca(D);
834 EmitAutoVarInit(emission);
835 EmitAutoVarCleanups(emission);
836}
Reid Spencer5f016e22007-07-11 17:01:13 +0000837
John McCall34695852011-02-22 06:44:22 +0000838/// EmitAutoVarAlloca - Emit the alloca and debug information for a
839/// local variable. Does not emit initalization or destruction.
840CodeGenFunction::AutoVarEmission
841CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
842 QualType Ty = D.getType();
843
844 AutoVarEmission emission(D);
845
846 bool isByRef = D.hasAttr<BlocksAttr>();
847 emission.IsByRef = isByRef;
848
849 CharUnits alignment = getContext().getDeclAlign(&D);
850 emission.Alignment = alignment;
851
John McCallbc8d40d2011-06-24 21:55:10 +0000852 // If the type is variably-modified, emit all the VLA sizes for it.
853 if (Ty->isVariablyModifiedType())
854 EmitVariablyModifiedType(Ty);
855
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000857 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000858 bool NRVO = getLangOpts().ElideConstructors &&
859 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000860
Richard Smithe67ca582013-06-02 00:09:52 +0000861 // If this value is an array or struct with a statically determinable
862 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000863 //
864 // TODO: We should constant-evaluate the initializer of any variable,
865 // as long as it is initialized by a constant expression. Currently,
866 // isConstantInitializer produces wrong answers for structs with
867 // reference or bitfield members, and a few other cases, and checking
868 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000869 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
870 (D.isConstexpr() ||
871 ((Ty.isPODType(getContext()) ||
872 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
873 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000874
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000875 // If the variable's a const type, and it's neither an NRVO
876 // candidate nor a __block variable and has no mutable members,
877 // emit it as a global instead.
878 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
879 CGM.isTypeConstant(Ty, true)) {
880 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000881
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000882 emission.Address = 0; // signal this condition to later callbacks
883 assert(emission.wasEmittedAsGlobal());
884 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000885 }
Eric Christophere1f54902011-08-23 22:38:00 +0000886
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000887 // Otherwise, tell the initialization code that we're in this case.
888 emission.IsConstantAggregate = true;
889 }
Eric Christophere1f54902011-08-23 22:38:00 +0000890
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000891 // A normal fixed sized variable becomes an alloca in the entry block,
892 // unless it's an NRVO variable.
893 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000894
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000895 if (NRVO) {
896 // The named return value optimization: allocate this variable in the
897 // return slot, so that we can elide the copy when returning this
898 // variable (C++0x [class.copy]p34).
899 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000900
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000901 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
902 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
903 // Create a flag that is used to indicate when the NRVO was applied
904 // to this variable. Set it to zero to indicate that NRVO was not
905 // applied.
906 llvm::Value *Zero = Builder.getFalse();
907 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
908 EnsureInsertPoint();
909 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000910
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000911 // Record the NRVO flag for this variable.
912 NRVOFlags[&D] = NRVOFlag;
913 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000914 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000915 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000916 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000917 if (isByRef)
918 LTy = BuildByRefType(&D);
919
920 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
921 Alloc->setName(D.getName());
922
923 CharUnits allocaAlignment = alignment;
924 if (isByRef)
925 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000926 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000927 Alloc->setAlignment(allocaAlignment.getQuantity());
928 DeclPtr = Alloc;
929
930 // Emit a lifetime intrinsic if meaningful. There's no point
931 // in doing this if we don't have a valid insertion point (?).
932 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
933 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
934 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
935
936 emission.SizeForLifetimeMarkers = sizeV;
937 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
938 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
939 ->setDoesNotThrow();
940 } else {
941 assert(!emission.useLifetimeMarkers());
942 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000943 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000945 EnsureInsertPoint();
946
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000947 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000948 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000949 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Anders Carlsson5d463152008-12-12 07:38:43 +0000951 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
952 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Anders Carlsson5d463152008-12-12 07:38:43 +0000954 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000955
956 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
John McCalld8715092010-07-21 06:13:08 +0000958 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000959 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000960 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000961 }
Mike Stump1eb44332009-09-09 15:08:12 +0000962
John McCallbc8d40d2011-06-24 21:55:10 +0000963 llvm::Value *elementCount;
964 QualType elementType;
965 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000966
Chris Lattner2acc6e32011-07-18 04:24:23 +0000967 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000968
969 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000970 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
971 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000972
John McCallbc8d40d2011-06-24 21:55:10 +0000973 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000975
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 llvm::Value *&DMEntry = LocalDeclMap[&D];
977 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
978 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000979 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000980
981 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000982 if (HaveInsertPoint())
983 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000984 if (CGM.getCodeGenOpts().getDebugInfo()
985 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000986 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000987 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000988 }
Devang Patelc594abd2011-06-03 19:21:47 +0000989 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000990
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000991 if (D.hasAttr<AnnotateAttr>())
992 EmitVarAnnotations(&D, emission.Address);
993
John McCall34695852011-02-22 06:44:22 +0000994 return emission;
995}
996
997/// Determines whether the given __block variable is potentially
998/// captured by the given expression.
999static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1000 // Skip the most common kinds of expressions that make
1001 // hierarchy-walking expensive.
1002 e = e->IgnoreParenCasts();
1003
1004 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1005 const BlockDecl *block = be->getBlockDecl();
1006 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
1007 e = block->capture_end(); i != e; ++i) {
1008 if (i->getVariable() == &var)
1009 return true;
1010 }
1011
1012 // No need to walk into the subexpressions.
1013 return false;
1014 }
1015
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001016 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1017 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001018 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1019 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001020 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001021 if (isCapturedBy(var, E))
1022 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001023 }
1024 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1025 // special case declarations
1026 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1027 I != E; ++I) {
1028 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1029 Expr *Init = VD->getInit();
1030 if (Init && isCapturedBy(var, Init))
1031 return true;
1032 }
1033 }
1034 }
1035 else
1036 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1037 // Later, provide code to poke into statements for capture analysis.
1038 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001039 return false;
1040 }
Eric Christophere1f54902011-08-23 22:38:00 +00001041
John McCall34695852011-02-22 06:44:22 +00001042 for (Stmt::const_child_range children = e->children(); children; ++children)
1043 if (isCapturedBy(var, cast<Expr>(*children)))
1044 return true;
1045
1046 return false;
1047}
1048
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001049/// \brief Determine whether the given initializer is trivial in the sense
1050/// that it requires no code to be generated.
1051static bool isTrivialInitializer(const Expr *Init) {
1052 if (!Init)
1053 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001054
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001055 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1056 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1057 if (Constructor->isTrivial() &&
1058 Constructor->isDefaultConstructor() &&
1059 !Construct->requiresZeroInitialization())
1060 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001061
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001062 return false;
1063}
John McCall34695852011-02-22 06:44:22 +00001064void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001065 assert(emission.Variable && "emission was not valid!");
1066
John McCall34695852011-02-22 06:44:22 +00001067 // If this was emitted as a global constant, we're done.
1068 if (emission.wasEmittedAsGlobal()) return;
1069
John McCall57b3b6a2011-02-22 07:16:58 +00001070 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001071 QualType type = D.getType();
1072
Chris Lattner19785962007-07-12 00:39:48 +00001073 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001074 const Expr *Init = D.getInit();
1075
1076 // If we are at an unreachable point, we don't need to emit the initializer
1077 // unless it contains a label.
1078 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001079 if (!Init || !ContainsLabel(Init)) return;
1080 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001081 }
1082
John McCall5af02db2011-03-31 01:59:53 +00001083 // Initialize the structure of a __block variable.
1084 if (emission.IsByRef)
1085 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001086
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001087 if (isTrivialInitializer(Init))
1088 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001089
John McCall5af02db2011-03-31 01:59:53 +00001090 CharUnits alignment = emission.Alignment;
1091
John McCall34695852011-02-22 06:44:22 +00001092 // Check whether this is a byref variable that's potentially
1093 // captured and moved by its own initializer. If so, we'll need to
1094 // emit the initializer first, then copy into the variable.
1095 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1096
1097 llvm::Value *Loc =
1098 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1099
Richard Smith51201882011-12-30 21:15:51 +00001100 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001101 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001102 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001103 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001104 }
1105
1106 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001107 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001108 lv.setNonGC(true);
1109 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1110 }
John McCall60d33652011-03-08 09:11:50 +00001111
Richard Smithe67ca582013-06-02 00:09:52 +00001112 if (!emission.IsConstantAggregate) {
1113 // For simple scalar/complex initialization, store the value directly.
1114 LValue lv = MakeAddrLValue(Loc, type, alignment);
1115 lv.setNonGC(true);
1116 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1117 }
1118
John McCall34695852011-02-22 06:44:22 +00001119 // If this is a simple aggregate initialization, we can optimize it
1120 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001121 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001122
John McCall60d33652011-03-08 09:11:50 +00001123 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001124 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001125 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001126
Chris Lattner2acc6e32011-07-18 04:24:23 +00001127 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001128 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001129 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001130
John McCall60d33652011-03-08 09:11:50 +00001131 // If the initializer is all or mostly zeros, codegen with memset then do
1132 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001133 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001134 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001135 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1136 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001137 // Zero and undef don't require a stores.
1138 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001139 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1140 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001141 }
John McCall60d33652011-03-08 09:11:50 +00001142 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001143 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001144 // memcpy from the global to the alloca.
1145 std::string Name = GetStaticDeclName(*this, D, ".");
1146 llvm::GlobalVariable *GV =
1147 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001148 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001149 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001150 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001151 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001152
John McCall60d33652011-03-08 09:11:50 +00001153 llvm::Value *SrcPtr = GV;
1154 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001155 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001156
1157 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1158 isVolatile);
1159 }
1160}
1161
1162/// Emit an expression as an initializer for a variable at the given
1163/// location. The expression is not necessarily the normal
1164/// initializer for the variable, and the address is not necessarily
1165/// its normal location.
1166///
1167/// \param init the initializing expression
1168/// \param var the variable to act as if we're initializing
1169/// \param loc the address to initialize; its type is a pointer
1170/// to the LLVM mapping of the variable's type
1171/// \param alignment the alignment of the address
1172/// \param capturedByInit true if the variable is a __block variable
1173/// whose address is potentially changed by the initializer
1174void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001175 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001176 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001177 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001178 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001179
1180 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001181 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001182 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001183 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001184 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001185 return;
1186 }
1187 switch (getEvaluationKind(type)) {
1188 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001189 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001190 return;
1191 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001192 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001193 if (capturedByInit)
1194 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001195 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1196 return;
1197 }
1198 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001199 if (type->isAtomicType()) {
1200 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1201 } else {
1202 // TODO: how can we delay here if D is captured by its initializer?
1203 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001204 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001205 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001206 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001207 }
John McCall9d232c82013-03-07 21:37:08 +00001208 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001209 }
John McCall9d232c82013-03-07 21:37:08 +00001210 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001211}
John McCallf1549f62010-07-06 01:34:17 +00001212
John McCallbdc4d802011-07-09 01:37:26 +00001213/// Enter a destroy cleanup for the given local variable.
1214void CodeGenFunction::emitAutoVarTypeCleanup(
1215 const CodeGenFunction::AutoVarEmission &emission,
1216 QualType::DestructionKind dtorKind) {
1217 assert(dtorKind != QualType::DK_none);
1218
1219 // Note that for __block variables, we want to destroy the
1220 // original stack object, not the possibly forwarded object.
1221 llvm::Value *addr = emission.getObjectAddress(*this);
1222
1223 const VarDecl *var = emission.Variable;
1224 QualType type = var->getType();
1225
1226 CleanupKind cleanupKind = NormalAndEHCleanup;
1227 CodeGenFunction::Destroyer *destroyer = 0;
1228
1229 switch (dtorKind) {
1230 case QualType::DK_none:
1231 llvm_unreachable("no cleanup for trivially-destructible variable");
1232
1233 case QualType::DK_cxx_destructor:
1234 // If there's an NRVO flag on the emission, we need a different
1235 // cleanup.
1236 if (emission.NRVOFlag) {
1237 assert(!type->isArrayType());
1238 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1239 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1240 emission.NRVOFlag);
1241 return;
1242 }
1243 break;
1244
1245 case QualType::DK_objc_strong_lifetime:
1246 // Suppress cleanups for pseudo-strong variables.
1247 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001248
John McCallbdc4d802011-07-09 01:37:26 +00001249 // Otherwise, consider whether to use an EH cleanup or not.
1250 cleanupKind = getARCCleanupKind();
1251
1252 // Use the imprecise destroyer by default.
1253 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1254 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1255 break;
1256
1257 case QualType::DK_objc_weak_lifetime:
1258 break;
1259 }
1260
1261 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001262 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001263
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001264 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001265 // is being pushed as an EH cleanup.
1266 bool useEHCleanup = (cleanupKind & EHCleanup);
1267 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1268 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001269}
1270
John McCall34695852011-02-22 06:44:22 +00001271void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001272 assert(emission.Variable && "emission was not valid!");
1273
John McCall34695852011-02-22 06:44:22 +00001274 // If this was emitted as a global constant, we're done.
1275 if (emission.wasEmittedAsGlobal()) return;
1276
John McCall38baeab2012-04-13 18:44:05 +00001277 // If we don't have an insertion point, we're done. Sema prevents
1278 // us from jumping into any of these scopes anyway.
1279 if (!HaveInsertPoint()) return;
1280
John McCall57b3b6a2011-02-22 07:16:58 +00001281 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001282
Nadav Rotem495cfa42013-03-23 06:43:35 +00001283 // Make sure we call @llvm.lifetime.end. This needs to happen
1284 // *last*, so the cleanup needs to be pushed *first*.
1285 if (emission.useLifetimeMarkers()) {
1286 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1287 emission.getAllocatedAddress(),
1288 emission.getSizeForLifetimeMarkers());
1289 }
1290
John McCallbdc4d802011-07-09 01:37:26 +00001291 // Check the type for a cleanup.
1292 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1293 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001294
John McCall0c24c802011-06-24 23:21:27 +00001295 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001296 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001297 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1298 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1299 }
1300
John McCall34695852011-02-22 06:44:22 +00001301 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001302 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001303 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001304
John McCall34695852011-02-22 06:44:22 +00001305 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001306 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001307
John McCallde5d3c72012-02-17 03:33:10 +00001308 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001309 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001310 }
Mike Stump797b6322009-03-05 01:23:13 +00001311
John McCall34695852011-02-22 06:44:22 +00001312 // If this is a block variable, call _Block_object_destroy
1313 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001314 if (emission.IsByRef)
1315 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001316}
1317
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001318CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001319CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1320 switch (kind) {
1321 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001322 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001323 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001324 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001325 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001326 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001327 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001328 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001329 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001330}
1331
John McCall074cae02013-02-01 05:11:40 +00001332/// pushEHDestroy - Push the standard destructor for the given type as
1333/// an EH-only cleanup.
1334void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1335 llvm::Value *addr, QualType type) {
1336 assert(dtorKind && "cannot push destructor for trivial type");
1337 assert(needsEHCleanup(dtorKind));
1338
1339 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1340}
1341
1342/// pushDestroy - Push the standard destructor for the given type as
1343/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001344void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1345 llvm::Value *addr, QualType type) {
1346 assert(dtorKind && "cannot push destructor for trivial type");
1347
1348 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1349 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1350 cleanupKind & EHCleanup);
1351}
1352
John McCallbdc4d802011-07-09 01:37:26 +00001353void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001354 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001355 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001356 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1357 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001358}
1359
Richard Smith8a07cd32013-06-12 20:42:33 +00001360void CodeGenFunction::pushLifetimeExtendedDestroy(
1361 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1362 Destroyer *destroyer, bool useEHCleanupForArray) {
1363 assert(!isInConditionalBranch() &&
1364 "performing lifetime extension from within conditional");
1365
1366 // Push an EH-only cleanup for the object now.
1367 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1368 // around in case a temporary's destructor throws an exception.
1369 if (cleanupKind & EHCleanup)
1370 EHStack.pushCleanup<DestroyObject>(
1371 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1372 destroyer, useEHCleanupForArray);
1373
1374 // Remember that we need to push a full cleanup for the object at the
1375 // end of the full-expression.
1376 pushCleanupAfterFullExpr<DestroyObject>(
1377 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1378}
1379
John McCall2673c682011-07-11 08:38:19 +00001380/// emitDestroy - Immediately perform the destruction of the given
1381/// object.
1382///
1383/// \param addr - the address of the object; a type*
1384/// \param type - the type of the object; if an array type, all
1385/// objects are destroyed in reverse order
1386/// \param destroyer - the function to call to destroy individual
1387/// elements
1388/// \param useEHCleanupForArray - whether an EH cleanup should be
1389/// used when destroying array elements, in case one of the
1390/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001391void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001392 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001393 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001394 const ArrayType *arrayType = getContext().getAsArrayType(type);
1395 if (!arrayType)
1396 return destroyer(*this, addr, type);
1397
1398 llvm::Value *begin = addr;
1399 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001400
1401 // Normally we have to check whether the array is zero-length.
1402 bool checkZeroLength = true;
1403
1404 // But if the array length is constant, we can suppress that.
1405 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1406 // ...and if it's constant zero, we can just skip the entire thing.
1407 if (constLength->isZero()) return;
1408 checkZeroLength = false;
1409 }
1410
John McCallbdc4d802011-07-09 01:37:26 +00001411 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001412 emitArrayDestroy(begin, end, type, destroyer,
1413 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001414}
1415
John McCall2673c682011-07-11 08:38:19 +00001416/// emitArrayDestroy - Destroys all the elements of the given array,
1417/// beginning from last to first. The array cannot be zero-length.
1418///
1419/// \param begin - a type* denoting the first element of the array
1420/// \param end - a type* denoting one past the end of the array
1421/// \param type - the element type of the array
1422/// \param destroyer - the function to call to destroy elements
1423/// \param useEHCleanup - whether to push an EH cleanup to destroy
1424/// the remaining elements in case the destruction of a single
1425/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001426void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1427 llvm::Value *end,
1428 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001429 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001430 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001431 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001432 assert(!type->isArrayType());
1433
1434 // The basic structure here is a do-while loop, because we don't
1435 // need to check for the zero-element case.
1436 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1437 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1438
John McCallfbf780a2011-07-13 08:09:46 +00001439 if (checkZeroLength) {
1440 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1441 "arraydestroy.isempty");
1442 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1443 }
1444
John McCallbdc4d802011-07-09 01:37:26 +00001445 // Enter the loop body, making that address the current address.
1446 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1447 EmitBlock(bodyBB);
1448 llvm::PHINode *elementPast =
1449 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1450 elementPast->addIncoming(end, entryBB);
1451
1452 // Shift the address back by one element.
1453 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1454 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1455 "arraydestroy.element");
1456
John McCall2673c682011-07-11 08:38:19 +00001457 if (useEHCleanup)
1458 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1459
John McCallbdc4d802011-07-09 01:37:26 +00001460 // Perform the actual destruction there.
1461 destroyer(*this, element, type);
1462
John McCall2673c682011-07-11 08:38:19 +00001463 if (useEHCleanup)
1464 PopCleanupBlock();
1465
John McCallbdc4d802011-07-09 01:37:26 +00001466 // Check whether we've reached the end.
1467 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1468 Builder.CreateCondBr(done, doneBB, bodyBB);
1469 elementPast->addIncoming(element, Builder.GetInsertBlock());
1470
1471 // Done.
1472 EmitBlock(doneBB);
1473}
1474
John McCall2673c682011-07-11 08:38:19 +00001475/// Perform partial array destruction as if in an EH cleanup. Unlike
1476/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001477static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1478 llvm::Value *begin, llvm::Value *end,
1479 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001480 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001481 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001482 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001483 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1484 // VLAs don't require a GEP index to walk into.
1485 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001486 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001487 type = arrayType->getElementType();
1488 }
John McCallfbf780a2011-07-13 08:09:46 +00001489
1490 if (arrayDepth) {
1491 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1492
Chris Lattner5f9e2722011-07-23 10:55:15 +00001493 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001494 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1495 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001496 }
1497
John McCallfbf780a2011-07-13 08:09:46 +00001498 // Destroy the array. We don't ever need an EH cleanup because we
1499 // assume that we're in an EH cleanup ourselves, so a throwing
1500 // destructor causes an immediate terminate.
1501 CGF.emitArrayDestroy(begin, end, type, destroyer,
1502 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001503}
1504
John McCallbdc4d802011-07-09 01:37:26 +00001505namespace {
John McCall2673c682011-07-11 08:38:19 +00001506 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1507 /// array destroy where the end pointer is regularly determined and
1508 /// does not need to be loaded from a local.
1509 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1510 llvm::Value *ArrayBegin;
1511 llvm::Value *ArrayEnd;
1512 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001513 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001514 public:
1515 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1516 QualType elementType,
1517 CodeGenFunction::Destroyer *destroyer)
1518 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001519 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001520
John McCallad346f42011-07-12 20:27:29 +00001521 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001522 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1523 ElementType, Destroyer);
1524 }
1525 };
1526
1527 /// IrregularPartialArrayDestroy - a cleanup which performs a
1528 /// partial array destroy where the end pointer is irregularly
1529 /// determined and must be loaded from a local.
1530 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001531 llvm::Value *ArrayBegin;
1532 llvm::Value *ArrayEndPointer;
1533 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001534 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001535 public:
John McCall2673c682011-07-11 08:38:19 +00001536 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1537 llvm::Value *arrayEndPointer,
1538 QualType elementType,
1539 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001540 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001541 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001542
John McCallad346f42011-07-12 20:27:29 +00001543 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001544 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001545 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1546 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001547 }
1548 };
1549}
1550
John McCall2673c682011-07-11 08:38:19 +00001551/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001552/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001553/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001554///
John McCallbdc4d802011-07-09 01:37:26 +00001555/// \param elementType - the immediate element type of the array;
1556/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001557void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001558 llvm::Value *arrayEndPointer,
1559 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001560 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001561 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1562 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001563 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001564}
1565
1566/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1567/// already-constructed elements of the given array. The cleanup
1568/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001569///
John McCall2673c682011-07-11 08:38:19 +00001570/// \param elementType - the immediate element type of the array;
1571/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001572void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1573 llvm::Value *arrayEnd,
1574 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001575 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001576 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001577 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001578 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001579}
1580
Nadav Rotem495cfa42013-03-23 06:43:35 +00001581/// Lazily declare the @llvm.lifetime.start intrinsic.
1582llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1583 if (LifetimeStartFn) return LifetimeStartFn;
1584 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1585 llvm::Intrinsic::lifetime_start);
1586 return LifetimeStartFn;
1587}
1588
1589/// Lazily declare the @llvm.lifetime.end intrinsic.
1590llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1591 if (LifetimeEndFn) return LifetimeEndFn;
1592 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1593 llvm::Intrinsic::lifetime_end);
1594 return LifetimeEndFn;
1595}
1596
John McCallf85e1932011-06-15 23:02:42 +00001597namespace {
1598 /// A cleanup to perform a release of an object at the end of a
1599 /// function. This is used to balance out the incoming +1 of a
1600 /// ns_consumed argument when we can't reasonably do that just by
1601 /// not doing the initial retain for a __block argument.
1602 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001603 ConsumeARCParameter(llvm::Value *param,
1604 ARCPreciseLifetime_t precise)
1605 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001606
1607 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001608 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001609
John McCallad346f42011-07-12 20:27:29 +00001610 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001611 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001612 }
1613 };
1614}
1615
Mike Stump1eb44332009-09-09 15:08:12 +00001616/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001617/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001618void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1619 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001620 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001621 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001622 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001623
1624 Arg->setName(D.getName());
1625
Adrian Prantl836e7c92013-03-14 17:53:33 +00001626 QualType Ty = D.getType();
1627
John McCall8178df32011-02-22 22:38:33 +00001628 // Use better IR generation for certain implicit parameters.
1629 if (isa<ImplicitParamDecl>(D)) {
1630 // The only implicit argument a block has is its literal.
1631 if (BlockInfo) {
1632 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001633 llvm::Value *LocalAddr = 0;
1634 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001635 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001636 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1637 D.getName() + ".addr");
1638 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1639 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1640 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1641 LocalAddr = Builder.CreateLoad(Alloc);
1642 }
John McCall8178df32011-02-22 22:38:33 +00001643
1644 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001645 if (CGM.getCodeGenOpts().getDebugInfo()
1646 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001647 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001648 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001649 }
John McCall8178df32011-02-22 22:38:33 +00001650 }
1651
1652 return;
1653 }
1654 }
1655
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001657 // If this is an aggregate or variable sized value, reuse the input pointer.
1658 if (!Ty->isConstantSizeType() ||
John McCall9d232c82013-03-07 21:37:08 +00001659 !CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001662 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001663 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1664 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001665 CharUnits Align = getContext().getDeclAlign(&D);
1666 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001667 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
John McCallf85e1932011-06-15 23:02:42 +00001669 bool doStore = true;
1670
1671 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001672 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001673 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1674 // We honor __attribute__((ns_consumed)) for types with lifetime.
1675 // For __strong, it's handled by just skipping the initial retain;
1676 // otherwise we have to balance out the initial +1 with an extra
1677 // cleanup to do the release at the end of the function.
1678 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1679
1680 // 'self' is always formally __strong, but if this is not an
1681 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001682 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001683 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1684 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001685 assert(lt == Qualifiers::OCL_Strong);
1686 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001687 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001688 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001689 lt = Qualifiers::OCL_ExplicitNone;
1690 }
1691
1692 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001693 if (!isConsumed) {
1694 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1695 // use objc_storeStrong(&dest, value) for retaining the
1696 // object. But first, store a null into 'dest' because
1697 // objc_storeStrong attempts to release its old value.
1698 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1699 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1700 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1701 doStore = false;
1702 }
1703 else
John McCallf85e1932011-06-15 23:02:42 +00001704 // Don't use objc_retainBlock for block pointers, because we
1705 // don't want to Block_copy something just because we got it
1706 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001707 Arg = EmitARCRetainNonBlock(Arg);
1708 }
John McCallf85e1932011-06-15 23:02:42 +00001709 } else {
1710 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001711 if (isConsumed) {
1712 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1713 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1714 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1715 precise);
1716 }
John McCallf85e1932011-06-15 23:02:42 +00001717
1718 if (lt == Qualifiers::OCL_Weak) {
1719 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001720 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001721 }
1722 }
1723
1724 // Enter the cleanup scope.
1725 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1726 }
1727
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001728 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001729 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001730 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 }
1732
1733 llvm::Value *&DMEntry = LocalDeclMap[&D];
1734 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1735 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001736
1737 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001738 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001739 if (CGM.getCodeGenOpts().getDebugInfo()
1740 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001741 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1742 }
1743 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001744
1745 if (D.hasAttr<AnnotateAttr>())
1746 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001747}