blob: 7cd02d8d86aa76cb0d1b82beb9ca39ba173ba444 [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
Sanjiv Guptacc9b1632008-05-30 10:30:31 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenFunction.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000016#include "CodeGenModule.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.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"
Anders Carlsson1a86b332007-10-17 00:52:43 +000025#include "llvm/GlobalVariable.h"
Anders Carlsson5d463152008-12-12 07:38:43 +000026#include "llvm/Intrinsics.h"
Mike Stumpdab514f2009-03-04 03:23:46 +000027#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/Type.h"
29using 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:
Francois Pichet41f5e662010-11-21 06:49:41 +000048 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000049 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000050 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000051 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000052 case Decl::ImplicitParam:
53 case Decl::ClassTemplate:
54 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000055 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000056 case Decl::TemplateTemplateParm:
57 case Decl::ObjCMethod:
58 case Decl::ObjCCategory:
59 case Decl::ObjCProtocol:
60 case Decl::ObjCInterface:
61 case Decl::ObjCCategoryImpl:
62 case Decl::ObjCImplementation:
63 case Decl::ObjCProperty:
64 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000065 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000066 case Decl::LinkageSpec:
67 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000068 case Decl::FileScopeAsm:
69 case Decl::Friend:
70 case Decl::FriendTemplate:
71 case Decl::Block:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000072 case Decl::ClassScopeFunctionSpecialization:
David Blaikieb219cfc2011-09-23 05:06:16 +000073 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000074 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000075 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000076 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000077 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000079 case Decl::Using: // using X; [C++]
80 case Decl::UsingShadow:
81 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000082 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000083 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000084 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000085 case Decl::Import:
Reid Spencer5f016e22007-07-11 17:01:13 +000086 // None of these decls require codegen support.
87 return;
Mike Stump1eb44332009-09-09 15:08:12 +000088
Daniel Dunbar662174c82008-08-29 17:28:43 +000089 case Decl::Var: {
90 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +000091 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000092 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +000093 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000094 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Richard Smith162e1c12011-04-15 14:24:37 +000096 case Decl::Typedef: // typedef int X;
97 case Decl::TypeAlias: { // using X = int; [C++0x]
98 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +000099 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000101 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000102 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000103 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000104 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000105}
106
John McCallb6bbcc92010-10-15 04:57:14 +0000107/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000108/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000109void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000111 case SC_None:
112 case SC_Auto:
113 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000114 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000115 case SC_Static: {
Eric Christophere1f54902011-08-23 22:38:00 +0000116 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000117 llvm::GlobalValue::InternalLinkage;
118
John McCall8b242332010-05-25 04:30:21 +0000119 // If the function definition has some sort of weak linkage, its
120 // static variables should also be weak so that they get properly
121 // uniqued. We can't do this in C, though, because there's no
122 // standard way to agree on which variables are the same (i.e.
123 // there's no mangling).
David Blaikie4e4d0842012-03-11 07:00:24 +0000124 if (getContext().getLangOpts().CPlusPlus)
John McCall8b242332010-05-25 04:30:21 +0000125 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126 Linkage = CurFn->getLinkage();
Eric Christophere1f54902011-08-23 22:38:00 +0000127
John McCallb6bbcc92010-10-15 04:57:14 +0000128 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000129 }
John McCalld931b082010-08-26 03:08:43 +0000130 case SC_Extern:
131 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000132 // Don't emit it now, allow it to be emitted lazily on its first use.
133 return;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000134 case SC_OpenCLWorkGroupLocal:
135 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000137
David Blaikieb219cfc2011-09-23 05:06:16 +0000138 llvm_unreachable("Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000139}
140
Chris Lattner761acc12009-12-05 08:22:11 +0000141static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
142 const char *Separator) {
143 CodeGenModule &CGM = CGF.CGM;
David Blaikie4e4d0842012-03-11 07:00:24 +0000144 if (CGF.getContext().getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000145 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000146 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000147 }
Eric Christophere1f54902011-08-23 22:38:00 +0000148
Chris Lattner761acc12009-12-05 08:22:11 +0000149 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000150 if (!CGF.CurFuncDecl) {
151 // Better be in a block declared in global scope.
152 const NamedDecl *ND = cast<NamedDecl>(&D);
153 const DeclContext *DC = ND->getDeclContext();
154 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
155 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000156 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000157 ContextName = Name.getString();
158 }
159 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000160 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000161 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000162 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000163 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000164 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000165 ContextName = CGF.CurFn->getName();
166 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000167 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000168
Chris Lattner761acc12009-12-05 08:22:11 +0000169 return ContextName + Separator + D.getNameAsString();
170}
171
John McCall49d26d22012-03-30 07:09:50 +0000172/// We wanted to make a variable of one type, but the variable already
173/// exists with another. Is that type good enough?
174///
175/// The problem we're working around here is that giving a global
176/// variable an initializer can require changing its type in some
177/// convoluted circumstances.
178static bool isExistingVarAdequate(CodeGenModule &CGM,
179 llvm::Type *existing, llvm::Type *desired) {
180 // Equality makes for a good fast path.
181 if (existing == desired) return true;
182
183 // Otherwise, just require them to have the same size.
184 return (CGM.getTargetData().getTypeStoreSize(existing)
185 == CGM.getTargetData().getTypeStoreSize(desired));
186}
187
188
189llvm::Constant *
John McCallb6bbcc92010-10-15 04:57:14 +0000190CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
191 const char *Separator,
192 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000193 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000194 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000195
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000196 // Use the label if the variable is renamed with the asm-label extension.
197 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000198 if (D.hasAttr<AsmLabelAttr>())
199 Name = CGM.getMangledName(&D);
200 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000201 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000202
Chris Lattner2acc6e32011-07-18 04:24:23 +0000203 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
John McCall49d26d22012-03-30 07:09:50 +0000204 unsigned addrspace = CGM.getContext().getTargetAddressSpace(Ty);
John McCall9993cc72012-03-30 04:25:14 +0000205
206 // In C++, there are strange possibilities here involving the
207 // double-emission of constructors and destructors.
208 if (CGM.getLangOpts().CPlusPlus) {
209 llvm::GlobalValue *value = CGM.getModule().getNamedValue(Name);
John McCall49d26d22012-03-30 07:09:50 +0000210 if (value && isa<llvm::GlobalVariable>(value)) {
211 // Check that the type is compatible with the type we want. The
212 // simple equality check isn't good enough because initializers
213 // can force the changing of a type (e.g. with unions).
214 if (value->getType()->getAddressSpace() == addrspace &&
215 isExistingVarAdequate(CGM, value->getType()->getElementType(), LTy))
216 return llvm::ConstantExpr::getBitCast(value,
217 LTy->getPointerTo(addrspace));
218 }
John McCall9993cc72012-03-30 04:25:14 +0000219
220 if (value) {
221 CGM.Error(D.getLocation(),
John McCall49d26d22012-03-30 07:09:50 +0000222 "problem emitting static variable '" + Name +
223 "': already present as different kind of symbol");
224
John McCall9993cc72012-03-30 04:25:14 +0000225 // Fall through and implicitly give it a uniqued name.
226 }
227 }
228
Anders Carlsson41f8a132009-09-26 18:16:06 +0000229 llvm::GlobalVariable *GV =
230 new llvm::GlobalVariable(CGM.getModule(), LTy,
231 Ty.isConstant(getContext()), Linkage,
232 CGM.EmitNullConstant(D.getType()), Name, 0,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000233 D.isThreadSpecified(),
John McCall49d26d22012-03-30 07:09:50 +0000234 addrspace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000235 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000236 if (Linkage != llvm::GlobalValue::InternalLinkage)
237 GV->setVisibility(CurFn->getVisibility());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000238 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000239}
240
Richard Smith7ca48502012-02-13 22:16:19 +0000241/// hasNontrivialDestruction - Determine whether a type's destruction is
242/// non-trivial. If so, and the variable uses static initialization, we must
243/// register its destructor to run on exit.
244static bool hasNontrivialDestruction(QualType T) {
245 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
246 return RD && !RD->hasTrivialDestructor();
247}
248
John McCall49d26d22012-03-30 07:09:50 +0000249/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to
250/// the global variable that has already been created for it. If
251/// the initializer has a different type than GV does, this may
252/// force the underlying variable to change. Otherwise it just
253/// returns it.
254///
255/// The argument must be a (potentially casted) global variable,
256/// and the result will be one, too.
257llvm::Constant *
John McCallb6bbcc92010-10-15 04:57:14 +0000258CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
John McCall49d26d22012-03-30 07:09:50 +0000259 llvm::Constant *addr) {
260 llvm::Constant *init = CGM.EmitConstantInit(D, this);
261
262 llvm::GlobalVariable *var =
263 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
John McCallbf40cb52010-07-15 23:40:35 +0000264
Chris Lattner761acc12009-12-05 08:22:11 +0000265 // If constant emission failed, then this should be a C++ static
266 // initializer.
John McCall49d26d22012-03-30 07:09:50 +0000267 if (!init) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000268 if (!getContext().getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000269 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000270 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000271 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000272 // be constant.
John McCall49d26d22012-03-30 07:09:50 +0000273 var->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000274
John McCall49d26d22012-03-30 07:09:50 +0000275 EmitCXXGuardedInit(D, addr, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000276 }
John McCall49d26d22012-03-30 07:09:50 +0000277 return addr;
Chris Lattner761acc12009-12-05 08:22:11 +0000278 }
John McCallbf40cb52010-07-15 23:40:35 +0000279
Chris Lattner761acc12009-12-05 08:22:11 +0000280 // The initializer may differ in type from the global. Rewrite
281 // the global to match the initializer. (We have to do this
282 // because some types, like unions, can't be completely represented
283 // in the LLVM type system.)
John McCall49d26d22012-03-30 07:09:50 +0000284 if (var->getType()->getElementType() != init->getType()) {
285 llvm::GlobalVariable *newVar
286 = new llvm::GlobalVariable(CGM.getModule(), init->getType(),
287 var->isConstant(),
288 var->getLinkage(), init, "",
289 /*InsertBefore*/ var,
290 D.isThreadSpecified(),
291 var->getType()->getAddressSpace());
292 newVar->setVisibility(var->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000293
Chris Lattner761acc12009-12-05 08:22:11 +0000294 // Steal the name of the old global
John McCall49d26d22012-03-30 07:09:50 +0000295 newVar->takeName(var);
Eric Christophere1f54902011-08-23 22:38:00 +0000296
Chris Lattner761acc12009-12-05 08:22:11 +0000297 // Replace all uses of the old global with the new global
John McCall49d26d22012-03-30 07:09:50 +0000298 addr = llvm::ConstantExpr::getBitCast(newVar, addr->getType());
299 var->replaceAllUsesWith(addr);
Eric Christophere1f54902011-08-23 22:38:00 +0000300
Chris Lattner761acc12009-12-05 08:22:11 +0000301 // Erase the old global, since it is no longer used.
John McCall49d26d22012-03-30 07:09:50 +0000302 var->eraseFromParent();
303 var = newVar;
Chris Lattner761acc12009-12-05 08:22:11 +0000304 }
Eric Christophere1f54902011-08-23 22:38:00 +0000305
John McCall49d26d22012-03-30 07:09:50 +0000306 var->setConstant(CGM.isTypeConstant(D.getType(), true));
307 var->setInitializer(init);
Richard Smith7ca48502012-02-13 22:16:19 +0000308
309 if (hasNontrivialDestruction(D.getType())) {
310 // We have a constant initializer, but a nontrivial destructor. We still
311 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000312 // destructor.
John McCall49d26d22012-03-30 07:09:50 +0000313 EmitCXXGuardedInit(D, addr, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000314 }
315
John McCall49d26d22012-03-30 07:09:50 +0000316 return addr;
Chris Lattner761acc12009-12-05 08:22:11 +0000317}
318
John McCallb6bbcc92010-10-15 04:57:14 +0000319void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000320 llvm::GlobalValue::LinkageTypes Linkage) {
Mike Stump1eb44332009-09-09 15:08:12 +0000321
John McCall49d26d22012-03-30 07:09:50 +0000322 llvm::Constant *addr = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000323
Daniel Dunbare5731f82009-02-25 20:08:33 +0000324 // Store into LocalDeclMap before generating initializer to handle
325 // circular references.
John McCall49d26d22012-03-30 07:09:50 +0000326 assert(!LocalDeclMap.count(&D) && "Decl already exists in localdeclmap!");
327 LocalDeclMap[&D] = addr;
Daniel Dunbare5731f82009-02-25 20:08:33 +0000328
John McCallfe67f3b2010-05-04 20:45:42 +0000329 // We can't have a VLA here, but we can have a pointer to a VLA,
330 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000331 // Make sure to evaluate VLA bounds now so that we have them for later.
332 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000333 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000334
Fariborz Jahanian09349142010-09-07 23:26:17 +0000335 // Local static block variables must be treated as globals as they may be
336 // referenced in their RHS initializer block-literal expresion.
John McCall49d26d22012-03-30 07:09:50 +0000337 CGM.setStaticLocalDeclAddress(&D, addr);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000338
Chris Lattner761acc12009-12-05 08:22:11 +0000339 // If this value has an initializer, emit it.
John McCall49d26d22012-03-30 07:09:50 +0000340 // This can leave us with a casted pointer.
Chris Lattner761acc12009-12-05 08:22:11 +0000341 if (D.getInit())
John McCall49d26d22012-03-30 07:09:50 +0000342 addr = AddInitializerToStaticVarDecl(D, addr);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000343
John McCall49d26d22012-03-30 07:09:50 +0000344 llvm::GlobalVariable *var =
345 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
346 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000347
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000348 if (D.hasAttr<AnnotateAttr>())
John McCall49d26d22012-03-30 07:09:50 +0000349 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000350
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000351 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall49d26d22012-03-30 07:09:50 +0000352 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000354 if (D.hasAttr<UsedAttr>())
John McCall49d26d22012-03-30 07:09:50 +0000355 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000356
John McCall49d26d22012-03-30 07:09:50 +0000357 LocalDeclMap[&D] = addr;
358 CGM.setStaticLocalDeclAddress(&D, addr);
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();
Mike Stump4451bd92009-02-20 00:19:45 +0000362 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000363 DI->setLocation(D.getLocation());
John McCall49d26d22012-03-30 07:09:50 +0000364 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000365 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000366}
Mike Stump1eb44332009-09-09 15:08:12 +0000367
John McCallda65ea82010-07-13 20:32:21 +0000368namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000369 struct DestroyObject : EHScopeStack::Cleanup {
370 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000371 CodeGenFunction::Destroyer *destroyer,
372 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000373 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000374 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000375
John McCallbdc4d802011-07-09 01:37:26 +0000376 llvm::Value *addr;
377 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000378 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000379 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000380
John McCallad346f42011-07-12 20:27:29 +0000381 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000382 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000383 bool useEHCleanupForArray =
384 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000385
386 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000387 }
388 };
389
John McCallbdc4d802011-07-09 01:37:26 +0000390 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
391 DestroyNRVOVariable(llvm::Value *addr,
392 const CXXDestructorDecl *Dtor,
393 llvm::Value *NRVOFlag)
394 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000395
396 const CXXDestructorDecl *Dtor;
397 llvm::Value *NRVOFlag;
398 llvm::Value *Loc;
399
John McCallad346f42011-07-12 20:27:29 +0000400 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000401 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000402 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000403
404 llvm::BasicBlock *SkipDtorBB = 0;
405 if (NRVO) {
406 // If we exited via NRVO, we skip the destructor call.
407 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
408 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
409 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
410 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
411 CGF.EmitBlock(RunDtorBB);
412 }
Eric Christophere1f54902011-08-23 22:38:00 +0000413
John McCallda65ea82010-07-13 20:32:21 +0000414 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
415 /*ForVirtualBase=*/false, Loc);
416
417 if (NRVO) CGF.EmitBlock(SkipDtorBB);
418 }
419 };
John McCallda65ea82010-07-13 20:32:21 +0000420
John McCall1f0fca52010-07-21 07:22:38 +0000421 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000422 llvm::Value *Stack;
423 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000424 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000425 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000426 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
427 CGF.Builder.CreateCall(F, V);
428 }
429 };
430
John McCall0c24c802011-06-24 23:21:27 +0000431 struct ExtendGCLifetime : EHScopeStack::Cleanup {
432 const VarDecl &Var;
433 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
434
John McCallad346f42011-07-12 20:27:29 +0000435 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000436 // Compute the address of the local variable, in case it's a
437 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000438 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
439 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000440 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
441 CGF.EmitExtendGCLifetime(value);
442 }
443 };
444
John McCall1f0fca52010-07-21 07:22:38 +0000445 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000446 llvm::Constant *CleanupFn;
447 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000448 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000449
John McCalld8715092010-07-21 06:13:08 +0000450 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000451 const VarDecl *Var)
452 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000453
John McCallad346f42011-07-12 20:27:29 +0000454 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000455 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
456 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000457 // Compute the address of the local variable, in case it's a byref
458 // or something.
459 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
460
John McCalld8715092010-07-21 06:13:08 +0000461 // In some cases, the type of the function argument will be different from
462 // the type of the pointer. An example of this is
463 // void f(void* arg);
464 // __attribute__((cleanup(f))) void *g;
465 //
466 // To fix this we insert a bitcast here.
467 QualType ArgTy = FnInfo.arg_begin()->type;
468 llvm::Value *Arg =
469 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
470
471 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000472 Args.add(RValue::get(Arg),
473 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000474 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
475 }
476 };
John McCalld8715092010-07-21 06:13:08 +0000477}
478
John McCallf85e1932011-06-15 23:02:42 +0000479/// EmitAutoVarWithLifetime - Does the setup required for an automatic
480/// variable with lifetime.
481static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
482 llvm::Value *addr,
483 Qualifiers::ObjCLifetime lifetime) {
484 switch (lifetime) {
485 case Qualifiers::OCL_None:
486 llvm_unreachable("present but none");
487
488 case Qualifiers::OCL_ExplicitNone:
489 // nothing to do
490 break;
491
492 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000493 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000494 (var.hasAttr<ObjCPreciseLifetimeAttr>()
495 ? CodeGenFunction::destroyARCStrongPrecise
496 : CodeGenFunction::destroyARCStrongImprecise);
497
498 CleanupKind cleanupKind = CGF.getARCCleanupKind();
499 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
500 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000501 break;
502 }
503 case Qualifiers::OCL_Autoreleasing:
504 // nothing to do
505 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000506
John McCallf85e1932011-06-15 23:02:42 +0000507 case Qualifiers::OCL_Weak:
508 // __weak objects always get EH cleanups; otherwise, exceptions
509 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000510 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
511 CodeGenFunction::destroyARCWeak,
512 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000513 break;
514 }
515}
516
517static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
518 if (const Expr *e = dyn_cast<Expr>(s)) {
519 // Skip the most common kinds of expressions that make
520 // hierarchy-walking expensive.
521 s = e = e->IgnoreParenCasts();
522
523 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
524 return (ref->getDecl() == &var);
525 }
526
527 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000528 // children might be null; as in missing decl or conditional of an if-stmt.
529 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000530 return true;
531
532 return false;
533}
534
535static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
536 if (!decl) return false;
537 if (!isa<VarDecl>(decl)) return false;
538 const VarDecl *var = cast<VarDecl>(decl);
539 return isAccessedBy(*var, e);
540}
541
John McCalla07398e2011-06-16 04:16:24 +0000542static void drillIntoBlockVariable(CodeGenFunction &CGF,
543 LValue &lvalue,
544 const VarDecl *var) {
545 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
546}
547
John McCallf85e1932011-06-15 23:02:42 +0000548void CodeGenFunction::EmitScalarInit(const Expr *init,
549 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000550 LValue lvalue,
551 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000552 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000553 if (!lifetime) {
554 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000555 if (capturedByInit)
556 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000557 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000558 return;
559 }
560
561 // If we're emitting a value with lifetime, we have to do the
562 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000563 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
564 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000565 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000566 }
567 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000568
569 // We have to maintain the illusion that the variable is
570 // zero-initialized. If the variable might be accessed in its
571 // initializer, zero-initialize before running the initializer, then
572 // actually perform the initialization with an assign.
573 bool accessedByInit = false;
574 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000575 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000576 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000577 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000578 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000579 if (capturedByInit) {
580 // We can use a simple GEP for this because it can't have been
581 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000582 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
583 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000584 }
585
Chris Lattner2acc6e32011-07-18 04:24:23 +0000586 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000587 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000588 ty = cast<llvm::PointerType>(ty->getElementType());
589
590 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000591
John McCallf85e1932011-06-15 23:02:42 +0000592 // If __weak, we want to use a barrier under certain conditions.
593 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000594 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000595
596 // Otherwise just do a simple store.
597 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000598 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000599 }
600
601 // Emit the initializer.
602 llvm::Value *value = 0;
603
604 switch (lifetime) {
605 case Qualifiers::OCL_None:
606 llvm_unreachable("present but none");
607
608 case Qualifiers::OCL_ExplicitNone:
609 // nothing to do
610 value = EmitScalarExpr(init);
611 break;
612
613 case Qualifiers::OCL_Strong: {
614 value = EmitARCRetainScalarExpr(init);
615 break;
616 }
617
618 case Qualifiers::OCL_Weak: {
619 // No way to optimize a producing initializer into this. It's not
620 // worth optimizing for, because the value will immediately
621 // disappear in the common case.
622 value = EmitScalarExpr(init);
623
John McCalla07398e2011-06-16 04:16:24 +0000624 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000625 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000626 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000627 else
John McCalla07398e2011-06-16 04:16:24 +0000628 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000629 return;
630 }
631
632 case Qualifiers::OCL_Autoreleasing:
633 value = EmitARCRetainAutoreleaseScalarExpr(init);
634 break;
635 }
636
John McCalla07398e2011-06-16 04:16:24 +0000637 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000638
639 // If the variable might have been accessed by its initializer, we
640 // might have to initialize with a barrier. We have to do this for
641 // both __weak and __strong, but __weak got filtered out above.
642 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000643 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000644 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000645 EmitARCRelease(oldValue, /*precise*/ false);
646 return;
647 }
648
David Chisnall7a7ee302012-01-16 17:27:18 +0000649 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000650}
Chris Lattner94cd0112010-12-01 02:05:19 +0000651
John McCall7acddac2011-06-17 06:42:21 +0000652/// EmitScalarInit - Initialize the given lvalue with the given object.
653void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
654 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
655 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000656 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000657
658 switch (lifetime) {
659 case Qualifiers::OCL_None:
660 llvm_unreachable("present but none");
661
662 case Qualifiers::OCL_ExplicitNone:
663 // nothing to do
664 break;
665
666 case Qualifiers::OCL_Strong:
667 init = EmitARCRetain(lvalue.getType(), init);
668 break;
669
670 case Qualifiers::OCL_Weak:
671 // Initialize and then skip the primitive store.
672 EmitARCInitWeak(lvalue.getAddress(), init);
673 return;
674
675 case Qualifiers::OCL_Autoreleasing:
676 init = EmitARCRetainAutorelease(lvalue.getType(), init);
677 break;
678 }
679
David Chisnall7a7ee302012-01-16 17:27:18 +0000680 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000681}
682
Chris Lattner94cd0112010-12-01 02:05:19 +0000683/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
684/// non-zero parts of the specified initializer with equal or fewer than
685/// NumStores scalar stores.
686static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
687 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000688 // Zero and Undef never requires any extra stores.
689 if (isa<llvm::ConstantAggregateZero>(Init) ||
690 isa<llvm::ConstantPointerNull>(Init) ||
691 isa<llvm::UndefValue>(Init))
692 return true;
693 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
694 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
695 isa<llvm::ConstantExpr>(Init))
696 return Init->isNullValue() || NumStores--;
697
698 // See if we can emit each element.
699 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
700 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
701 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
702 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
703 return false;
704 }
705 return true;
706 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000707
708 if (llvm::ConstantDataSequential *CDS =
709 dyn_cast<llvm::ConstantDataSequential>(Init)) {
710 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
711 llvm::Constant *Elt = CDS->getElementAsConstant(i);
712 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
713 return false;
714 }
715 return true;
716 }
Eric Christophere1f54902011-08-23 22:38:00 +0000717
Chris Lattner94cd0112010-12-01 02:05:19 +0000718 // Anything else is hard and scary.
719 return false;
720}
721
722/// emitStoresForInitAfterMemset - For inits that
723/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
724/// stores that would be required.
725static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000726 bool isVolatile, CGBuilderTy &Builder) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000727 // Zero doesn't require a store.
728 if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
Chris Lattner70b02942010-12-02 01:58:41 +0000729 return;
Eric Christophere1f54902011-08-23 22:38:00 +0000730
Chris Lattner70b02942010-12-02 01:58:41 +0000731 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
732 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
733 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000734 Builder.CreateStore(Init, Loc, isVolatile);
735 return;
736 }
737
738 if (llvm::ConstantDataSequential *CDS =
739 dyn_cast<llvm::ConstantDataSequential>(Init)) {
740 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
741 llvm::Constant *Elt = CDS->getElementAsConstant(i);
742
743 // Get a pointer to the element and emit it.
744 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
745 isVolatile, Builder);
746 }
Chris Lattner70b02942010-12-02 01:58:41 +0000747 return;
748 }
Eric Christophere1f54902011-08-23 22:38:00 +0000749
Chris Lattner70b02942010-12-02 01:58:41 +0000750 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
751 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000752
Chris Lattner70b02942010-12-02 01:58:41 +0000753 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
754 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Chris Lattnerf492cb12012-01-31 04:36:19 +0000755 // Get a pointer to the element and emit it.
Chris Lattner70b02942010-12-02 01:58:41 +0000756 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
John McCall34695852011-02-22 06:44:22 +0000757 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000758 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000759}
760
761
762/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
763/// plus some stores to initialize a local variable instead of using a memcpy
764/// from a constant global. It is beneficial to use memset if the global is all
765/// zeros, or mostly zeros and large.
766static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
767 uint64_t GlobalSize) {
768 // If a global is all zeros, always use a memset.
769 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
770
771
772 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
773 // do it if it will require 6 or fewer scalar stores.
774 // TODO: Should budget depends on the size? Avoiding a large global warrants
775 // plopping in more stores.
776 unsigned StoreBudget = 6;
777 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000778
779 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000780 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
781}
782
783
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000784/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000785/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000786/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000787void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
788 AutoVarEmission emission = EmitAutoVarAlloca(D);
789 EmitAutoVarInit(emission);
790 EmitAutoVarCleanups(emission);
791}
Reid Spencer5f016e22007-07-11 17:01:13 +0000792
John McCall34695852011-02-22 06:44:22 +0000793/// EmitAutoVarAlloca - Emit the alloca and debug information for a
794/// local variable. Does not emit initalization or destruction.
795CodeGenFunction::AutoVarEmission
796CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
797 QualType Ty = D.getType();
798
799 AutoVarEmission emission(D);
800
801 bool isByRef = D.hasAttr<BlocksAttr>();
802 emission.IsByRef = isByRef;
803
804 CharUnits alignment = getContext().getDeclAlign(&D);
805 emission.Alignment = alignment;
806
John McCallbc8d40d2011-06-24 21:55:10 +0000807 // If the type is variably-modified, emit all the VLA sizes for it.
808 if (Ty->isVariablyModifiedType())
809 EmitVariablyModifiedType(Ty);
810
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000812 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000813 if (!Target.useGlobalsForAutomaticVariables()) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000814 bool NRVO = getContext().getLangOpts().ElideConstructors &&
John McCall34695852011-02-22 06:44:22 +0000815 D.isNRVOVariable();
816
817 // If this value is a POD array or struct with a statically
Richard Smith4bb66862011-12-02 00:30:33 +0000818 // determinable constant initializer, there are optimizations we can do.
819 //
Richard Smitha9b21d22012-02-17 06:48:11 +0000820 // TODO: We should constant-evaluate the initializer of any variable,
Richard Smith4bb66862011-12-02 00:30:33 +0000821 // as long as it is initialized by a constant expression. Currently,
822 // isConstantInitializer produces wrong answers for structs with
823 // reference or bitfield members, and a few other cases, and checking
824 // for POD-ness protects us from some of these.
John McCall34695852011-02-22 06:44:22 +0000825 if (D.getInit() &&
Eric Christophere1f54902011-08-23 22:38:00 +0000826 (Ty->isArrayType() || Ty->isRecordType()) &&
John McCallf85e1932011-06-15 23:02:42 +0000827 (Ty.isPODType(getContext()) ||
828 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
John McCall4204f072010-08-02 21:13:48 +0000829 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCall34695852011-02-22 06:44:22 +0000830
831 // If the variable's a const type, and it's neither an NRVO
Richard Smith4bb66862011-12-02 00:30:33 +0000832 // candidate nor a __block variable and has no mutable members,
833 // emit it as a global instead.
Richard Smitha9b21d22012-02-17 06:48:11 +0000834 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
835 CGM.isTypeConstant(Ty, true)) {
836 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000837
Richard Smitha9b21d22012-02-17 06:48:11 +0000838 emission.Address = 0; // signal this condition to later callbacks
839 assert(emission.wasEmittedAsGlobal());
840 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000841 }
John McCall34695852011-02-22 06:44:22 +0000842
843 // Otherwise, tell the initialization code that we're in this case.
844 emission.IsConstantAggregate = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000845 }
Eric Christophere1f54902011-08-23 22:38:00 +0000846
Douglas Gregord86c4772010-05-15 06:46:45 +0000847 // A normal fixed sized variable becomes an alloca in the entry block,
848 // unless it's an NRVO variable.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000849 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000850
Douglas Gregord86c4772010-05-15 06:46:45 +0000851 if (NRVO) {
852 // The named return value optimization: allocate this variable in the
853 // return slot, so that we can elide the copy when returning this
854 // variable (C++0x [class.copy]p34).
855 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000856
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000857 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
858 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
859 // Create a flag that is used to indicate when the NRVO was applied
Eric Christophere1f54902011-08-23 22:38:00 +0000860 // to this variable. Set it to zero to indicate that NRVO was not
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000861 // applied.
Chris Lattner4c53dc12010-12-01 01:47:15 +0000862 llvm::Value *Zero = Builder.getFalse();
John McCall34695852011-02-22 06:44:22 +0000863 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Nick Lewyckya03733b2011-02-16 23:59:08 +0000864 EnsureInsertPoint();
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000865 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000866
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000867 // Record the NRVO flag for this variable.
868 NRVOFlags[&D] = NRVOFlag;
John McCall34695852011-02-22 06:44:22 +0000869 emission.NRVOFlag = NRVOFlag;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000870 }
871 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000872 } else {
873 if (isByRef)
874 LTy = BuildByRefType(&D);
Eric Christophere1f54902011-08-23 22:38:00 +0000875
Douglas Gregord86c4772010-05-15 06:46:45 +0000876 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
Benjamin Kramer7a715242011-11-29 14:46:55 +0000877 Alloc->setName(D.getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000878
John McCall34695852011-02-22 06:44:22 +0000879 CharUnits allocaAlignment = alignment;
Douglas Gregord86c4772010-05-15 06:46:45 +0000880 if (isByRef)
Eric Christophere1f54902011-08-23 22:38:00 +0000881 allocaAlignment = std::max(allocaAlignment,
Ken Dyck06f486e2011-01-18 02:01:14 +0000882 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
John McCall34695852011-02-22 06:44:22 +0000883 Alloc->setAlignment(allocaAlignment.getQuantity());
Douglas Gregord86c4772010-05-15 06:46:45 +0000884 DeclPtr = Alloc;
885 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000886 } else {
887 // Targets that don't support recursion emit locals as globals.
888 const char *Class =
John McCalld931b082010-08-26 03:08:43 +0000889 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCallb6bbcc92010-10-15 04:57:14 +0000890 DeclPtr = CreateStaticVarDecl(D, Class,
891 llvm::GlobalValue::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000892 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000893 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000894 EnsureInsertPoint();
895
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000896 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000897 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000898 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Anders Carlsson5d463152008-12-12 07:38:43 +0000900 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
901 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Anders Carlsson5d463152008-12-12 07:38:43 +0000903 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000904
905 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
John McCalld8715092010-07-21 06:13:08 +0000907 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000908 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000909 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000910 }
Mike Stump1eb44332009-09-09 15:08:12 +0000911
John McCallbc8d40d2011-06-24 21:55:10 +0000912 llvm::Value *elementCount;
913 QualType elementType;
914 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000915
Chris Lattner2acc6e32011-07-18 04:24:23 +0000916 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000917
918 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000919 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
920 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000921
John McCallbc8d40d2011-06-24 21:55:10 +0000922 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000924
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 llvm::Value *&DMEntry = LocalDeclMap[&D];
926 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
927 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000928 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000929
930 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000931 if (HaveInsertPoint())
932 if (CGDebugInfo *DI = getDebugInfo()) {
933 DI->setLocation(D.getLocation());
Devang Patelc594abd2011-06-03 19:21:47 +0000934 if (Target.useGlobalsForAutomaticVariables()) {
935 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
936 } else
937 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
938 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000939
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000940 if (D.hasAttr<AnnotateAttr>())
941 EmitVarAnnotations(&D, emission.Address);
942
John McCall34695852011-02-22 06:44:22 +0000943 return emission;
944}
945
946/// Determines whether the given __block variable is potentially
947/// captured by the given expression.
948static bool isCapturedBy(const VarDecl &var, const Expr *e) {
949 // Skip the most common kinds of expressions that make
950 // hierarchy-walking expensive.
951 e = e->IgnoreParenCasts();
952
953 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
954 const BlockDecl *block = be->getBlockDecl();
955 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
956 e = block->capture_end(); i != e; ++i) {
957 if (i->getVariable() == &var)
958 return true;
959 }
960
961 // No need to walk into the subexpressions.
962 return false;
963 }
964
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000965 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
966 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +0000967 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
968 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +0000969 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000970 if (isCapturedBy(var, E))
971 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +0000972 }
973 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
974 // special case declarations
975 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
976 I != E; ++I) {
977 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
978 Expr *Init = VD->getInit();
979 if (Init && isCapturedBy(var, Init))
980 return true;
981 }
982 }
983 }
984 else
985 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
986 // Later, provide code to poke into statements for capture analysis.
987 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000988 return false;
989 }
Eric Christophere1f54902011-08-23 22:38:00 +0000990
John McCall34695852011-02-22 06:44:22 +0000991 for (Stmt::const_child_range children = e->children(); children; ++children)
992 if (isCapturedBy(var, cast<Expr>(*children)))
993 return true;
994
995 return false;
996}
997
Douglas Gregorbcc3e662011-07-01 21:08:19 +0000998/// \brief Determine whether the given initializer is trivial in the sense
999/// that it requires no code to be generated.
1000static bool isTrivialInitializer(const Expr *Init) {
1001 if (!Init)
1002 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001003
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001004 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1005 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1006 if (Constructor->isTrivial() &&
1007 Constructor->isDefaultConstructor() &&
1008 !Construct->requiresZeroInitialization())
1009 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001010
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001011 return false;
1012}
John McCall34695852011-02-22 06:44:22 +00001013void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001014 assert(emission.Variable && "emission was not valid!");
1015
John McCall34695852011-02-22 06:44:22 +00001016 // If this was emitted as a global constant, we're done.
1017 if (emission.wasEmittedAsGlobal()) return;
1018
John McCall57b3b6a2011-02-22 07:16:58 +00001019 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001020 QualType type = D.getType();
1021
Chris Lattner19785962007-07-12 00:39:48 +00001022 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001023 const Expr *Init = D.getInit();
1024
1025 // If we are at an unreachable point, we don't need to emit the initializer
1026 // unless it contains a label.
1027 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001028 if (!Init || !ContainsLabel(Init)) return;
1029 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001030 }
1031
John McCall5af02db2011-03-31 01:59:53 +00001032 // Initialize the structure of a __block variable.
1033 if (emission.IsByRef)
1034 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001035
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001036 if (isTrivialInitializer(Init))
1037 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001038
John McCall5af02db2011-03-31 01:59:53 +00001039 CharUnits alignment = emission.Alignment;
1040
John McCall34695852011-02-22 06:44:22 +00001041 // Check whether this is a byref variable that's potentially
1042 // captured and moved by its own initializer. If so, we'll need to
1043 // emit the initializer first, then copy into the variable.
1044 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1045
1046 llvm::Value *Loc =
1047 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1048
Richard Smith51201882011-12-30 21:15:51 +00001049 llvm::Constant *constant = 0;
1050 if (emission.IsConstantAggregate) {
1051 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001052 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001053 }
1054
1055 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001056 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001057 lv.setNonGC(true);
1058 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1059 }
John McCall60d33652011-03-08 09:11:50 +00001060
John McCall34695852011-02-22 06:44:22 +00001061 // If this is a simple aggregate initialization, we can optimize it
1062 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001063 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001064
John McCall60d33652011-03-08 09:11:50 +00001065 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001066 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001067 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001068
Chris Lattner2acc6e32011-07-18 04:24:23 +00001069 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001070 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001071 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001072
John McCall60d33652011-03-08 09:11:50 +00001073 // If the initializer is all or mostly zeros, codegen with memset then do
1074 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001075 if (shouldUseMemSetPlusStoresToInitialize(constant,
John McCall60d33652011-03-08 09:11:50 +00001076 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
1077 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1078 alignment.getQuantity(), isVolatile);
1079 if (!constant->isNullValue()) {
1080 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1081 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001082 }
John McCall60d33652011-03-08 09:11:50 +00001083 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001084 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001085 // memcpy from the global to the alloca.
1086 std::string Name = GetStaticDeclName(*this, D, ".");
1087 llvm::GlobalVariable *GV =
1088 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001089 llvm::GlobalValue::PrivateLinkage,
John McCall60d33652011-03-08 09:11:50 +00001090 constant, Name, 0, false, 0);
1091 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001092 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001093
John McCall60d33652011-03-08 09:11:50 +00001094 llvm::Value *SrcPtr = GV;
1095 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001096 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001097
1098 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1099 isVolatile);
1100 }
1101}
1102
1103/// Emit an expression as an initializer for a variable at the given
1104/// location. The expression is not necessarily the normal
1105/// initializer for the variable, and the address is not necessarily
1106/// its normal location.
1107///
1108/// \param init the initializing expression
1109/// \param var the variable to act as if we're initializing
1110/// \param loc the address to initialize; its type is a pointer
1111/// to the LLVM mapping of the variable's type
1112/// \param alignment the alignment of the address
1113/// \param capturedByInit true if the variable is a __block variable
1114/// whose address is potentially changed by the initializer
1115void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001116 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001117 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001118 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001119 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001120
1121 if (type->isReferenceType()) {
John McCalla07398e2011-06-16 04:16:24 +00001122 RValue rvalue = EmitReferenceBindingToExpr(init, D);
Eric Christophere1f54902011-08-23 22:38:00 +00001123 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001124 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001125 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall34695852011-02-22 06:44:22 +00001126 } else if (!hasAggregateLLVMType(type)) {
John McCalla07398e2011-06-16 04:16:24 +00001127 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall34695852011-02-22 06:44:22 +00001128 } else if (type->isAnyComplexType()) {
John McCall60d33652011-03-08 09:11:50 +00001129 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001130 if (capturedByInit)
1131 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1132 StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
John McCall34695852011-02-22 06:44:22 +00001133 } else {
1134 // TODO: how can we delay here if D is captured by its initializer?
John McCall7c2349b2011-08-25 20:40:09 +00001135 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001136 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001137 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001138 AggValueSlot::IsNotAliased));
Sebastian Redl972edf02012-02-19 16:03:09 +00001139 MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001140 }
John McCall34695852011-02-22 06:44:22 +00001141}
John McCallf1549f62010-07-06 01:34:17 +00001142
John McCallbdc4d802011-07-09 01:37:26 +00001143/// Enter a destroy cleanup for the given local variable.
1144void CodeGenFunction::emitAutoVarTypeCleanup(
1145 const CodeGenFunction::AutoVarEmission &emission,
1146 QualType::DestructionKind dtorKind) {
1147 assert(dtorKind != QualType::DK_none);
1148
1149 // Note that for __block variables, we want to destroy the
1150 // original stack object, not the possibly forwarded object.
1151 llvm::Value *addr = emission.getObjectAddress(*this);
1152
1153 const VarDecl *var = emission.Variable;
1154 QualType type = var->getType();
1155
1156 CleanupKind cleanupKind = NormalAndEHCleanup;
1157 CodeGenFunction::Destroyer *destroyer = 0;
1158
1159 switch (dtorKind) {
1160 case QualType::DK_none:
1161 llvm_unreachable("no cleanup for trivially-destructible variable");
1162
1163 case QualType::DK_cxx_destructor:
1164 // If there's an NRVO flag on the emission, we need a different
1165 // cleanup.
1166 if (emission.NRVOFlag) {
1167 assert(!type->isArrayType());
1168 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1169 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1170 emission.NRVOFlag);
1171 return;
1172 }
1173 break;
1174
1175 case QualType::DK_objc_strong_lifetime:
1176 // Suppress cleanups for pseudo-strong variables.
1177 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001178
John McCallbdc4d802011-07-09 01:37:26 +00001179 // Otherwise, consider whether to use an EH cleanup or not.
1180 cleanupKind = getARCCleanupKind();
1181
1182 // Use the imprecise destroyer by default.
1183 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1184 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1185 break;
1186
1187 case QualType::DK_objc_weak_lifetime:
1188 break;
1189 }
1190
1191 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001192 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001193
1194 // Use an EH cleanup in array destructors iff the destructor itself
1195 // is being pushed as an EH cleanup.
1196 bool useEHCleanup = (cleanupKind & EHCleanup);
1197 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1198 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001199}
1200
John McCall34695852011-02-22 06:44:22 +00001201void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001202 assert(emission.Variable && "emission was not valid!");
1203
John McCall34695852011-02-22 06:44:22 +00001204 // If this was emitted as a global constant, we're done.
1205 if (emission.wasEmittedAsGlobal()) return;
1206
John McCall57b3b6a2011-02-22 07:16:58 +00001207 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001208
John McCallbdc4d802011-07-09 01:37:26 +00001209 // Check the type for a cleanup.
1210 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1211 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001212
John McCall0c24c802011-06-24 23:21:27 +00001213 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001214 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001215 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1216 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1217 }
1218
John McCall34695852011-02-22 06:44:22 +00001219 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001220 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001221 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001222
John McCall34695852011-02-22 06:44:22 +00001223 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001224 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001225
John McCallde5d3c72012-02-17 03:33:10 +00001226 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001227 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001228 }
Mike Stump797b6322009-03-05 01:23:13 +00001229
John McCall34695852011-02-22 06:44:22 +00001230 // If this is a block variable, call _Block_object_destroy
1231 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001232 if (emission.IsByRef)
1233 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001234}
1235
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001236CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001237CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1238 switch (kind) {
1239 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001240 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001241 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001242 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001243 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001244 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001245 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001246 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001247 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001248}
1249
John McCall9928c482011-07-12 16:41:08 +00001250/// pushDestroy - Push the standard destructor for the given type.
1251void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1252 llvm::Value *addr, QualType type) {
1253 assert(dtorKind && "cannot push destructor for trivial type");
1254
1255 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1256 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1257 cleanupKind & EHCleanup);
1258}
1259
John McCallbdc4d802011-07-09 01:37:26 +00001260void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001261 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001262 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001263 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1264 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001265}
1266
John McCall2673c682011-07-11 08:38:19 +00001267/// emitDestroy - Immediately perform the destruction of the given
1268/// object.
1269///
1270/// \param addr - the address of the object; a type*
1271/// \param type - the type of the object; if an array type, all
1272/// objects are destroyed in reverse order
1273/// \param destroyer - the function to call to destroy individual
1274/// elements
1275/// \param useEHCleanupForArray - whether an EH cleanup should be
1276/// used when destroying array elements, in case one of the
1277/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001278void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001279 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001280 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001281 const ArrayType *arrayType = getContext().getAsArrayType(type);
1282 if (!arrayType)
1283 return destroyer(*this, addr, type);
1284
1285 llvm::Value *begin = addr;
1286 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001287
1288 // Normally we have to check whether the array is zero-length.
1289 bool checkZeroLength = true;
1290
1291 // But if the array length is constant, we can suppress that.
1292 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1293 // ...and if it's constant zero, we can just skip the entire thing.
1294 if (constLength->isZero()) return;
1295 checkZeroLength = false;
1296 }
1297
John McCallbdc4d802011-07-09 01:37:26 +00001298 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001299 emitArrayDestroy(begin, end, type, destroyer,
1300 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001301}
1302
John McCall2673c682011-07-11 08:38:19 +00001303/// emitArrayDestroy - Destroys all the elements of the given array,
1304/// beginning from last to first. The array cannot be zero-length.
1305///
1306/// \param begin - a type* denoting the first element of the array
1307/// \param end - a type* denoting one past the end of the array
1308/// \param type - the element type of the array
1309/// \param destroyer - the function to call to destroy elements
1310/// \param useEHCleanup - whether to push an EH cleanup to destroy
1311/// the remaining elements in case the destruction of a single
1312/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001313void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1314 llvm::Value *end,
1315 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001316 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001317 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001318 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001319 assert(!type->isArrayType());
1320
1321 // The basic structure here is a do-while loop, because we don't
1322 // need to check for the zero-element case.
1323 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1324 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1325
John McCallfbf780a2011-07-13 08:09:46 +00001326 if (checkZeroLength) {
1327 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1328 "arraydestroy.isempty");
1329 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1330 }
1331
John McCallbdc4d802011-07-09 01:37:26 +00001332 // Enter the loop body, making that address the current address.
1333 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1334 EmitBlock(bodyBB);
1335 llvm::PHINode *elementPast =
1336 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1337 elementPast->addIncoming(end, entryBB);
1338
1339 // Shift the address back by one element.
1340 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1341 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1342 "arraydestroy.element");
1343
John McCall2673c682011-07-11 08:38:19 +00001344 if (useEHCleanup)
1345 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1346
John McCallbdc4d802011-07-09 01:37:26 +00001347 // Perform the actual destruction there.
1348 destroyer(*this, element, type);
1349
John McCall2673c682011-07-11 08:38:19 +00001350 if (useEHCleanup)
1351 PopCleanupBlock();
1352
John McCallbdc4d802011-07-09 01:37:26 +00001353 // Check whether we've reached the end.
1354 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1355 Builder.CreateCondBr(done, doneBB, bodyBB);
1356 elementPast->addIncoming(element, Builder.GetInsertBlock());
1357
1358 // Done.
1359 EmitBlock(doneBB);
1360}
1361
John McCall2673c682011-07-11 08:38:19 +00001362/// Perform partial array destruction as if in an EH cleanup. Unlike
1363/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001364static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1365 llvm::Value *begin, llvm::Value *end,
1366 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001367 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001368 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001369 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001370 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1371 // VLAs don't require a GEP index to walk into.
1372 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001373 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001374 type = arrayType->getElementType();
1375 }
John McCallfbf780a2011-07-13 08:09:46 +00001376
1377 if (arrayDepth) {
1378 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1379
Chris Lattner5f9e2722011-07-23 10:55:15 +00001380 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001381 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1382 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001383 }
1384
John McCallfbf780a2011-07-13 08:09:46 +00001385 // Destroy the array. We don't ever need an EH cleanup because we
1386 // assume that we're in an EH cleanup ourselves, so a throwing
1387 // destructor causes an immediate terminate.
1388 CGF.emitArrayDestroy(begin, end, type, destroyer,
1389 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001390}
1391
John McCallbdc4d802011-07-09 01:37:26 +00001392namespace {
John McCall2673c682011-07-11 08:38:19 +00001393 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1394 /// array destroy where the end pointer is regularly determined and
1395 /// does not need to be loaded from a local.
1396 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1397 llvm::Value *ArrayBegin;
1398 llvm::Value *ArrayEnd;
1399 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001400 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001401 public:
1402 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1403 QualType elementType,
1404 CodeGenFunction::Destroyer *destroyer)
1405 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001406 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001407
John McCallad346f42011-07-12 20:27:29 +00001408 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001409 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1410 ElementType, Destroyer);
1411 }
1412 };
1413
1414 /// IrregularPartialArrayDestroy - a cleanup which performs a
1415 /// partial array destroy where the end pointer is irregularly
1416 /// determined and must be loaded from a local.
1417 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001418 llvm::Value *ArrayBegin;
1419 llvm::Value *ArrayEndPointer;
1420 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001421 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001422 public:
John McCall2673c682011-07-11 08:38:19 +00001423 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1424 llvm::Value *arrayEndPointer,
1425 QualType elementType,
1426 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001427 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001428 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001429
John McCallad346f42011-07-12 20:27:29 +00001430 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001431 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001432 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1433 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001434 }
1435 };
1436}
1437
John McCall2673c682011-07-11 08:38:19 +00001438/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001439/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001440/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001441///
John McCallbdc4d802011-07-09 01:37:26 +00001442/// \param elementType - the immediate element type of the array;
1443/// possibly still an array type
1444/// \param array - a value of type elementType*
1445/// \param destructionKind - the kind of destruction required
1446/// \param initializedElementCount - a value of type size_t* holding
1447/// the number of successfully-constructed elements
John McCall9928c482011-07-12 16:41:08 +00001448void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001449 llvm::Value *arrayEndPointer,
1450 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001451 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001452 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1453 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001454 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001455}
1456
1457/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1458/// already-constructed elements of the given array. The cleanup
1459/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001460///
John McCall2673c682011-07-11 08:38:19 +00001461/// \param elementType - the immediate element type of the array;
1462/// possibly still an array type
1463/// \param array - a value of type elementType*
1464/// \param destructionKind - the kind of destruction required
1465/// \param initializedElementCount - a value of type size_t* holding
1466/// the number of successfully-constructed elements
1467void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1468 llvm::Value *arrayEnd,
1469 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001470 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001471 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001472 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001473 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001474}
1475
John McCallf85e1932011-06-15 23:02:42 +00001476namespace {
1477 /// A cleanup to perform a release of an object at the end of a
1478 /// function. This is used to balance out the incoming +1 of a
1479 /// ns_consumed argument when we can't reasonably do that just by
1480 /// not doing the initial retain for a __block argument.
1481 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1482 ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1483
1484 llvm::Value *Param;
1485
John McCallad346f42011-07-12 20:27:29 +00001486 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001487 CGF.EmitARCRelease(Param, /*precise*/ false);
1488 }
1489 };
1490}
1491
Mike Stump1eb44332009-09-09 15:08:12 +00001492/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001493/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001494void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1495 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001496 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001497 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001498 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001499
1500 Arg->setName(D.getName());
1501
1502 // Use better IR generation for certain implicit parameters.
1503 if (isa<ImplicitParamDecl>(D)) {
1504 // The only implicit argument a block has is its literal.
1505 if (BlockInfo) {
1506 LocalDeclMap[&D] = Arg;
1507
1508 if (CGDebugInfo *DI = getDebugInfo()) {
1509 DI->setLocation(D.getLocation());
1510 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1511 }
1512
1513 return;
1514 }
1515 }
1516
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001517 QualType Ty = D.getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001520 // If this is an aggregate or variable sized value, reuse the input pointer.
1521 if (!Ty->isConstantSizeType() ||
1522 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001525 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001526 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1527 D.getName() + ".addr");
1528 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1529 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
John McCallf85e1932011-06-15 23:02:42 +00001531 bool doStore = true;
1532
1533 Qualifiers qs = Ty.getQualifiers();
1534
1535 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1536 // We honor __attribute__((ns_consumed)) for types with lifetime.
1537 // For __strong, it's handled by just skipping the initial retain;
1538 // otherwise we have to balance out the initial +1 with an extra
1539 // cleanup to do the release at the end of the function.
1540 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1541
1542 // 'self' is always formally __strong, but if this is not an
1543 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001544 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001545 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1546 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001547 assert(lt == Qualifiers::OCL_Strong);
1548 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001549 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001550 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001551 lt = Qualifiers::OCL_ExplicitNone;
1552 }
1553
1554 if (lt == Qualifiers::OCL_Strong) {
1555 if (!isConsumed)
1556 // Don't use objc_retainBlock for block pointers, because we
1557 // don't want to Block_copy something just because we got it
1558 // as a parameter.
1559 Arg = EmitARCRetainNonBlock(Arg);
1560 } else {
1561 // Push the cleanup for a consumed parameter.
1562 if (isConsumed)
1563 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1564
1565 if (lt == Qualifiers::OCL_Weak) {
1566 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001567 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001568 }
1569 }
1570
1571 // Enter the cleanup scope.
1572 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1573 }
1574
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001575 // Store the initial value into the alloca.
John McCall545d9962011-06-25 02:11:03 +00001576 if (doStore) {
1577 LValue lv = MakeAddrLValue(DeclPtr, Ty,
Eli Friedman6da2c712011-12-03 04:14:32 +00001578 getContext().getDeclAlign(&D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001579 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
John McCall545d9962011-06-25 02:11:03 +00001580 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 }
1582
1583 llvm::Value *&DMEntry = LocalDeclMap[&D];
1584 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1585 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001586
1587 // Emit debug info for param declaration.
Devang Patel98703d32011-06-15 17:57:08 +00001588 if (CGDebugInfo *DI = getDebugInfo())
Devang Patel093ac462011-03-03 20:13:15 +00001589 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001590
1591 if (D.hasAttr<AnnotateAttr>())
1592 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593}