blob: c31840a78e2a8f4e824f1c191158b1d993501eef [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"
John McCalld16c2cf2011-02-08 08:22:06 +000017#include "CGBlocks.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:
50 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:
55 case Decl::TemplateTemplateParm:
56 case Decl::ObjCMethod:
57 case Decl::ObjCCategory:
58 case Decl::ObjCProtocol:
59 case Decl::ObjCInterface:
60 case Decl::ObjCCategoryImpl:
61 case Decl::ObjCImplementation:
62 case Decl::ObjCProperty:
63 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000064 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000065 case Decl::LinkageSpec:
66 case Decl::ObjCPropertyImpl:
67 case Decl::ObjCClass:
68 case Decl::ObjCForwardProtocol:
69 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
73
74 assert(0 && "Declaration not should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000075 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000076 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000077 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000078 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000079 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000080 case Decl::Using: // using X; [C++]
81 case Decl::UsingShadow:
82 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000083 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000084 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Reid Spencer5f016e22007-07-11 17:01:13 +000085 // None of these decls require codegen support.
86 return;
Mike Stump1eb44332009-09-09 15:08:12 +000087
Daniel Dunbar662174c82008-08-29 17:28:43 +000088 case Decl::Var: {
89 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +000090 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000091 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +000092 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000093 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Anders Carlssonfcdbb932008-12-20 21:51:53 +000095 case Decl::Typedef: { // typedef int X;
96 const TypedefDecl &TD = cast<TypedefDecl>(D);
97 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +000098
Anders Carlssonfcdbb932008-12-20 21:51:53 +000099 if (Ty->isVariablyModifiedType())
100 EmitVLASize(Ty);
101 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000102 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000103}
104
John McCallb6bbcc92010-10-15 04:57:14 +0000105/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000106/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000107void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000109 case SC_None:
110 case SC_Auto:
111 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000112 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000113 case SC_Static: {
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000114 llvm::GlobalValue::LinkageTypes Linkage =
115 llvm::GlobalValue::InternalLinkage;
116
John McCall8b242332010-05-25 04:30:21 +0000117 // If the function definition has some sort of weak linkage, its
118 // static variables should also be weak so that they get properly
119 // uniqued. We can't do this in C, though, because there's no
120 // standard way to agree on which variables are the same (i.e.
121 // there's no mangling).
122 if (getContext().getLangOptions().CPlusPlus)
123 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
124 Linkage = CurFn->getLinkage();
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000125
John McCallb6bbcc92010-10-15 04:57:14 +0000126 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000127 }
John McCalld931b082010-08-26 03:08:43 +0000128 case SC_Extern:
129 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000130 // Don't emit it now, allow it to be emitted lazily on its first use.
131 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000133
134 assert(0 && "Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000135}
136
Chris Lattner761acc12009-12-05 08:22:11 +0000137static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
138 const char *Separator) {
139 CodeGenModule &CGM = CGF.CGM;
John McCallf746aa62010-03-19 23:29:14 +0000140 if (CGF.getContext().getLangOptions().CPlusPlus) {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000141 llvm::StringRef Name = CGM.getMangledName(&D);
142 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000143 }
Chris Lattner761acc12009-12-05 08:22:11 +0000144
145 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000146 if (!CGF.CurFuncDecl) {
147 // Better be in a block declared in global scope.
148 const NamedDecl *ND = cast<NamedDecl>(&D);
149 const DeclContext *DC = ND->getDeclContext();
150 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
151 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000152 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000153 ContextName = Name.getString();
154 }
155 else
156 assert(0 && "Unknown context for block static var decl");
157 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000158 llvm::StringRef Name = CGM.getMangledName(FD);
159 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000160 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000161 ContextName = CGF.CurFn->getName();
162 else
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000163 assert(0 && "Unknown context for static var decl");
Chris Lattner761acc12009-12-05 08:22:11 +0000164
165 return ContextName + Separator + D.getNameAsString();
166}
167
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000168llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000169CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
170 const char *Separator,
171 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000172 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000173 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000174
Chris Lattner761acc12009-12-05 08:22:11 +0000175 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000176
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000177 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlsson41f8a132009-09-26 18:16:06 +0000178 llvm::GlobalVariable *GV =
179 new llvm::GlobalVariable(CGM.getModule(), LTy,
180 Ty.isConstant(getContext()), Linkage,
181 CGM.EmitNullConstant(D.getType()), Name, 0,
182 D.isThreadSpecified(), Ty.getAddressSpace());
Ken Dyck8b752f12010-01-27 17:10:57 +0000183 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000184 if (Linkage != llvm::GlobalValue::InternalLinkage)
185 GV->setVisibility(CurFn->getVisibility());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000186 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000187}
188
John McCallb6bbcc92010-10-15 04:57:14 +0000189/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
Chris Lattner761acc12009-12-05 08:22:11 +0000190/// global variable that has already been created for it. If the initializer
191/// has a different type than GV does, this may free GV and return a different
192/// one. Otherwise it just returns GV.
193llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000194CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
195 llvm::GlobalVariable *GV) {
Chris Lattner761acc12009-12-05 08:22:11 +0000196 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
John McCallbf40cb52010-07-15 23:40:35 +0000197
Chris Lattner761acc12009-12-05 08:22:11 +0000198 // If constant emission failed, then this should be a C++ static
199 // initializer.
200 if (!Init) {
201 if (!getContext().getLangOptions().CPlusPlus)
202 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000203 else if (Builder.GetInsertBlock()) {
Anders Carlsson071c8102010-01-26 04:02:23 +0000204 // Since we have a static initializer, this global variable can't
205 // be constant.
206 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000207
John McCall3030eb82010-11-06 09:44:32 +0000208 EmitCXXGuardedInit(D, GV);
Anders Carlsson071c8102010-01-26 04:02:23 +0000209 }
Chris Lattner761acc12009-12-05 08:22:11 +0000210 return GV;
211 }
John McCallbf40cb52010-07-15 23:40:35 +0000212
Chris Lattner761acc12009-12-05 08:22:11 +0000213 // The initializer may differ in type from the global. Rewrite
214 // the global to match the initializer. (We have to do this
215 // because some types, like unions, can't be completely represented
216 // in the LLVM type system.)
John McCall9c20fa92010-09-03 18:58:50 +0000217 if (GV->getType()->getElementType() != Init->getType()) {
Chris Lattner761acc12009-12-05 08:22:11 +0000218 llvm::GlobalVariable *OldGV = GV;
219
220 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
221 OldGV->isConstant(),
222 OldGV->getLinkage(), Init, "",
John McCall112c9672010-11-02 21:04:24 +0000223 /*InsertBefore*/ OldGV,
224 D.isThreadSpecified(),
Chris Lattner761acc12009-12-05 08:22:11 +0000225 D.getType().getAddressSpace());
John McCall112c9672010-11-02 21:04:24 +0000226 GV->setVisibility(OldGV->getVisibility());
Chris Lattner761acc12009-12-05 08:22:11 +0000227
228 // Steal the name of the old global
229 GV->takeName(OldGV);
230
231 // Replace all uses of the old global with the new global
232 llvm::Constant *NewPtrForOldDecl =
233 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
234 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
235
236 // Erase the old global, since it is no longer used.
237 OldGV->eraseFromParent();
238 }
239
240 GV->setInitializer(Init);
241 return GV;
242}
243
John McCallb6bbcc92010-10-15 04:57:14 +0000244void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000245 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara985b312009-02-25 19:45:19 +0000246 llvm::Value *&DMEntry = LocalDeclMap[&D];
247 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000248
John McCallb6bbcc92010-10-15 04:57:14 +0000249 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000250
Daniel Dunbare5731f82009-02-25 20:08:33 +0000251 // Store into LocalDeclMap before generating initializer to handle
252 // circular references.
253 DMEntry = GV;
254
John McCallfe67f3b2010-05-04 20:45:42 +0000255 // We can't have a VLA here, but we can have a pointer to a VLA,
256 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000257 // Make sure to evaluate VLA bounds now so that we have them for later.
258 if (D.getType()->isVariablyModifiedType())
259 EmitVLASize(D.getType());
Fariborz Jahanian09349142010-09-07 23:26:17 +0000260
261 // Local static block variables must be treated as globals as they may be
262 // referenced in their RHS initializer block-literal expresion.
263 CGM.setStaticLocalDeclAddress(&D, GV);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000264
Chris Lattner761acc12009-12-05 08:22:11 +0000265 // If this value has an initializer, emit it.
266 if (D.getInit())
John McCallb6bbcc92010-10-15 04:57:14 +0000267 GV = AddInitializerToStaticVarDecl(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000268
Chris Lattner0af95232010-03-10 23:59:59 +0000269 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
270
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000271 // FIXME: Merge attribute handling.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000272 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000273 SourceManager &SM = CGM.getContext().getSourceManager();
274 llvm::Constant *Ann =
Mike Stump1eb44332009-09-09 15:08:12 +0000275 CGM.EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000276 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000277 CGM.AddAnnotation(Ann);
278 }
279
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000280 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000281 GV->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000283 if (D.hasAttr<UsedAttr>())
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000284 CGM.AddUsedGlobal(GV);
285
Daniel Dunbare5731f82009-02-25 20:08:33 +0000286 // We may have to cast the constant because of the initializer
287 // mismatch above.
288 //
289 // FIXME: It is really dangerous to store this in the map; if anyone
290 // RAUW's the GV uses of this constant will be invalid.
Eli Friedman26590522008-06-08 01:23:18 +0000291 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000292 const llvm::Type *LPtrTy = LTy->getPointerTo(D.getType().getAddressSpace());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000293 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000294
295 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000296 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000297 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000298 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000299 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
300 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000301}
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000303unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
304 assert(ByRefValueInfo.count(VD) && "Did not find value!");
305
306 return ByRefValueInfo.find(VD)->second.second;
307}
308
Fariborz Jahanian52a80e12011-01-26 23:08:27 +0000309llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
310 const VarDecl *V) {
311 llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
312 Loc = Builder.CreateLoad(Loc);
313 Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
314 V->getNameAsString());
315 return Loc;
316}
317
Mike Stumpdab514f2009-03-04 03:23:46 +0000318/// BuildByRefType - This routine changes a __block variable declared as T x
319/// into:
320///
321/// struct {
322/// void *__isa;
323/// void *__forwarding;
324/// int32_t __flags;
325/// int32_t __size;
Mike Stump39605b42009-09-22 02:12:52 +0000326/// void *__copy_helper; // only if needed
327/// void *__destroy_helper; // only if needed
328/// char padding[X]; // only if needed
Mike Stumpdab514f2009-03-04 03:23:46 +0000329/// T x;
330/// } x
331///
John McCall6b5a61b2011-02-07 10:33:21 +0000332const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000333 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
334 if (Info.first)
335 return Info.first;
336
Anders Carlsson9ad55132009-09-09 02:51:03 +0000337 QualType Ty = D->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Anders Carlsson18be84c2009-09-12 02:44:18 +0000339 std::vector<const llvm::Type *> Types;
Anders Carlsson36043862009-09-10 01:32:12 +0000340
John McCalld16c2cf2011-02-08 08:22:06 +0000341 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
Anders Carlsson36043862009-09-10 01:32:12 +0000342
Anders Carlsson18be84c2009-09-12 02:44:18 +0000343 // void *__isa;
344 Types.push_back(Int8PtrTy);
345
346 // void *__forwarding;
347 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
348
349 // int32_t __flags;
Chris Lattner77b89b82010-06-27 07:15:29 +0000350 Types.push_back(Int32Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000351
352 // int32_t __size;
Chris Lattner77b89b82010-06-27 07:15:29 +0000353 Types.push_back(Int32Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000354
John McCall6b5a61b2011-02-07 10:33:21 +0000355 bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000356 if (HasCopyAndDispose) {
357 /// void *__copy_helper;
358 Types.push_back(Int8PtrTy);
359
360 /// void *__destroy_helper;
361 Types.push_back(Int8PtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +0000362 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000363
364 bool Packed = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000365 CharUnits Align = getContext().getDeclAlign(D);
Ken Dyck06f486e2011-01-18 02:01:14 +0000366 if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
Anders Carlsson18be84c2009-09-12 02:44:18 +0000367 // We have to insert padding.
368
369 // The struct above has 2 32-bit integers.
370 unsigned CurrentOffsetInBytes = 4 * 2;
371
372 // And either 2 or 4 pointers.
373 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
374 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
375
376 // Align the offset.
377 unsigned AlignedOffsetInBytes =
Ken Dyck8b752f12010-01-27 17:10:57 +0000378 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
Anders Carlsson18be84c2009-09-12 02:44:18 +0000379
380 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
Anders Carlssone0c88222009-09-13 17:55:13 +0000381 if (NumPaddingBytes > 0) {
John McCalld16c2cf2011-02-08 08:22:06 +0000382 const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
Mike Stump04c688a2009-10-21 00:42:55 +0000383 // FIXME: We need a sema error for alignment larger than the minimum of
384 // the maximal stack alignmint and the alignment of malloc on the system.
Anders Carlssone0c88222009-09-13 17:55:13 +0000385 if (NumPaddingBytes > 1)
386 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000387
Anders Carlssone0c88222009-09-13 17:55:13 +0000388 Types.push_back(Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000389
Anders Carlssone0c88222009-09-13 17:55:13 +0000390 // We want a packed struct.
391 Packed = true;
392 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000393 }
394
395 // T x;
Fariborz Jahanian469a20d2010-09-03 23:07:53 +0000396 Types.push_back(ConvertTypeForMem(Ty));
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000397
John McCalld16c2cf2011-02-08 08:22:06 +0000398 const llvm::Type *T = llvm::StructType::get(getLLVMContext(), Types, Packed);
Anders Carlsson36043862009-09-10 01:32:12 +0000399
400 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
401 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
402 ByRefTypeHolder.get());
403
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000404 Info.first = ByRefTypeHolder.get();
Anders Carlsson18be84c2009-09-12 02:44:18 +0000405
406 Info.second = Types.size() - 1;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000407
408 return Info.first;
Mike Stumpdab514f2009-03-04 03:23:46 +0000409}
410
John McCallda65ea82010-07-13 20:32:21 +0000411namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000412 struct CallArrayDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000413 CallArrayDtor(const CXXDestructorDecl *Dtor,
414 const ConstantArrayType *Type,
415 llvm::Value *Loc)
416 : Dtor(Dtor), Type(Type), Loc(Loc) {}
417
418 const CXXDestructorDecl *Dtor;
419 const ConstantArrayType *Type;
420 llvm::Value *Loc;
421
422 void Emit(CodeGenFunction &CGF, bool IsForEH) {
423 QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
424 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
425 BasePtr = llvm::PointerType::getUnqual(BasePtr);
426 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
427 CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
428 }
429 };
430
John McCall1f0fca52010-07-21 07:22:38 +0000431 struct CallVarDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000432 CallVarDtor(const CXXDestructorDecl *Dtor,
433 llvm::Value *NRVOFlag,
434 llvm::Value *Loc)
435 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
436
437 const CXXDestructorDecl *Dtor;
438 llvm::Value *NRVOFlag;
439 llvm::Value *Loc;
440
441 void Emit(CodeGenFunction &CGF, bool IsForEH) {
442 // Along the exceptions path we always execute the dtor.
443 bool NRVO = !IsForEH && NRVOFlag;
444
445 llvm::BasicBlock *SkipDtorBB = 0;
446 if (NRVO) {
447 // If we exited via NRVO, we skip the destructor call.
448 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
449 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
450 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
451 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
452 CGF.EmitBlock(RunDtorBB);
453 }
454
455 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
456 /*ForVirtualBase=*/false, Loc);
457
458 if (NRVO) CGF.EmitBlock(SkipDtorBB);
459 }
460 };
461}
462
John McCalld8715092010-07-21 06:13:08 +0000463namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000464 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000465 llvm::Value *Stack;
466 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
467 void Emit(CodeGenFunction &CGF, bool IsForEH) {
468 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
469 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
470 CGF.Builder.CreateCall(F, V);
471 }
472 };
473
John McCall1f0fca52010-07-21 07:22:38 +0000474 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000475 llvm::Constant *CleanupFn;
476 const CGFunctionInfo &FnInfo;
477 llvm::Value *Addr;
478 const VarDecl &Var;
479
480 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
481 llvm::Value *Addr, const VarDecl *Var)
482 : CleanupFn(CleanupFn), FnInfo(*Info), Addr(Addr), Var(*Var) {}
483
484 void Emit(CodeGenFunction &CGF, bool IsForEH) {
485 // In some cases, the type of the function argument will be different from
486 // the type of the pointer. An example of this is
487 // void f(void* arg);
488 // __attribute__((cleanup(f))) void *g;
489 //
490 // To fix this we insert a bitcast here.
491 QualType ArgTy = FnInfo.arg_begin()->type;
492 llvm::Value *Arg =
493 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
494
495 CallArgList Args;
496 Args.push_back(std::make_pair(RValue::get(Arg),
497 CGF.getContext().getPointerType(Var.getType())));
498 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
499 }
500 };
501
John McCall1f0fca52010-07-21 07:22:38 +0000502 struct CallBlockRelease : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000503 llvm::Value *Addr;
504 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
505
506 void Emit(CodeGenFunction &CGF, bool IsForEH) {
507 llvm::Value *V = CGF.Builder.CreateStructGEP(Addr, 1, "forwarding");
508 V = CGF.Builder.CreateLoad(V);
John McCalld16c2cf2011-02-08 08:22:06 +0000509 CGF.BuildBlockRelease(V, BLOCK_FIELD_IS_BYREF);
John McCalld8715092010-07-21 06:13:08 +0000510 }
511 };
512}
513
Chris Lattner94cd0112010-12-01 02:05:19 +0000514
515/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
516/// non-zero parts of the specified initializer with equal or fewer than
517/// NumStores scalar stores.
518static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
519 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000520 // Zero and Undef never requires any extra stores.
521 if (isa<llvm::ConstantAggregateZero>(Init) ||
522 isa<llvm::ConstantPointerNull>(Init) ||
523 isa<llvm::UndefValue>(Init))
524 return true;
525 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
526 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
527 isa<llvm::ConstantExpr>(Init))
528 return Init->isNullValue() || NumStores--;
529
530 // See if we can emit each element.
531 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
532 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
533 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
534 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
535 return false;
536 }
537 return true;
538 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000539
540 // Anything else is hard and scary.
541 return false;
542}
543
544/// emitStoresForInitAfterMemset - For inits that
545/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
546/// stores that would be required.
547static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
548 CGBuilderTy &Builder) {
549 // Zero doesn't require any stores.
Chris Lattner70b02942010-12-02 01:58:41 +0000550 if (isa<llvm::ConstantAggregateZero>(Init) ||
551 isa<llvm::ConstantPointerNull>(Init) ||
552 isa<llvm::UndefValue>(Init))
553 return;
Chris Lattner94cd0112010-12-01 02:05:19 +0000554
Chris Lattner70b02942010-12-02 01:58:41 +0000555 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
556 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
557 isa<llvm::ConstantExpr>(Init)) {
558 if (!Init->isNullValue())
559 Builder.CreateStore(Init, Loc);
560 return;
561 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000562
Chris Lattner70b02942010-12-02 01:58:41 +0000563 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
564 "Unknown value type!");
565
566 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
567 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
568 if (Elt->isNullValue()) continue;
569
570 // Otherwise, get a pointer to the element and emit it.
571 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
572 Builder);
573 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000574}
575
576
577/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
578/// plus some stores to initialize a local variable instead of using a memcpy
579/// from a constant global. It is beneficial to use memset if the global is all
580/// zeros, or mostly zeros and large.
581static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
582 uint64_t GlobalSize) {
583 // If a global is all zeros, always use a memset.
584 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
585
586
587 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
588 // do it if it will require 6 or fewer scalar stores.
589 // TODO: Should budget depends on the size? Avoiding a large global warrants
590 // plopping in more stores.
591 unsigned StoreBudget = 6;
592 uint64_t SizeLimit = 32;
593
594 return GlobalSize > SizeLimit &&
595 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
596}
597
598
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000599/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000600/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000601/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallb6bbcc92010-10-15 04:57:14 +0000602void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D,
603 SpecialInitFn *SpecialInit) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000604 QualType Ty = D.getType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000605 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000606 bool isByRef = D.hasAttr<BlocksAttr>();
Mike Stump797b6322009-03-05 01:23:13 +0000607 bool needsDispose = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000608 CharUnits Align = CharUnits::Zero();
Chris Lattner761acc12009-12-05 08:22:11 +0000609 bool IsSimpleConstantInitializer = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000610
Douglas Gregord86c4772010-05-15 06:46:45 +0000611 bool NRVO = false;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000612 llvm::Value *NRVOFlag = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000613 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000614 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000615 if (!Target.useGlobalsForAutomaticVariables()) {
Douglas Gregord86c4772010-05-15 06:46:45 +0000616 NRVO = getContext().getLangOptions().ElideConstructors &&
617 D.isNRVOVariable();
Chris Lattnerff933b72009-12-05 06:49:57 +0000618 // If this value is an array or struct, is POD, and if the initializer is
Douglas Gregord86c4772010-05-15 06:46:45 +0000619 // a staticly determinable constant, try to optimize it (unless the NRVO
620 // is already optimizing this).
John McCall4204f072010-08-02 21:13:48 +0000621 if (!NRVO && D.getInit() && !isByRef &&
Chris Lattnerff933b72009-12-05 06:49:57 +0000622 (Ty->isArrayType() || Ty->isRecordType()) &&
623 Ty->isPODType() &&
John McCall4204f072010-08-02 21:13:48 +0000624 D.getInit()->isConstantInitializer(getContext(), false)) {
Chris Lattnerff933b72009-12-05 06:49:57 +0000625 // If this variable is marked 'const', emit the value as a global.
626 if (CGM.getCodeGenOpts().MergeAllConstants &&
627 Ty.isConstant(getContext())) {
John McCallb6bbcc92010-10-15 04:57:14 +0000628 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
Tanya Lattner59876c22009-11-04 01:18:09 +0000629 return;
630 }
Chris Lattner761acc12009-12-05 08:22:11 +0000631
632 IsSimpleConstantInitializer = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000633 }
634
Douglas Gregord86c4772010-05-15 06:46:45 +0000635 // A normal fixed sized variable becomes an alloca in the entry block,
636 // unless it's an NRVO variable.
Eli Friedmana3460ac2009-03-04 04:25:14 +0000637 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregord86c4772010-05-15 06:46:45 +0000638
639 if (NRVO) {
640 // The named return value optimization: allocate this variable in the
641 // return slot, so that we can elide the copy when returning this
642 // variable (C++0x [class.copy]p34).
643 DeclPtr = ReturnValue;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000644
645 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
646 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
647 // Create a flag that is used to indicate when the NRVO was applied
648 // to this variable. Set it to zero to indicate that NRVO was not
649 // applied.
Chris Lattner4c53dc12010-12-01 01:47:15 +0000650 llvm::Value *Zero = Builder.getFalse();
651 NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000652 Builder.CreateStore(Zero, NRVOFlag);
653
654 // Record the NRVO flag for this variable.
655 NRVOFlags[&D] = NRVOFlag;
656 }
657 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000658 } else {
659 if (isByRef)
660 LTy = BuildByRefType(&D);
661
662 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
663 Alloc->setName(D.getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Douglas Gregord86c4772010-05-15 06:46:45 +0000665 Align = getContext().getDeclAlign(&D);
666 if (isByRef)
667 Align = std::max(Align,
Ken Dyck06f486e2011-01-18 02:01:14 +0000668 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
Douglas Gregord86c4772010-05-15 06:46:45 +0000669 Alloc->setAlignment(Align.getQuantity());
670 DeclPtr = Alloc;
671 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000672 } else {
673 // Targets that don't support recursion emit locals as globals.
674 const char *Class =
John McCalld931b082010-08-26 03:08:43 +0000675 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCallb6bbcc92010-10-15 04:57:14 +0000676 DeclPtr = CreateStaticVarDecl(D, Class,
677 llvm::GlobalValue::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Daniel Dunbard286f052009-07-19 06:58:07 +0000680 // FIXME: Can this happen?
Anders Carlsson60d35412008-12-20 20:46:34 +0000681 if (Ty->isVariablyModifiedType())
682 EmitVLASize(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000683 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000684 EnsureInsertPoint();
685
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000686 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000687 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000688 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000689
Anders Carlsson5d463152008-12-12 07:38:43 +0000690 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
691 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Anders Carlsson5d463152008-12-12 07:38:43 +0000693 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000694
695 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000696
John McCalld8715092010-07-21 06:13:08 +0000697 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000698 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000699 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000700 }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Anders Carlsson5d463152008-12-12 07:38:43 +0000702 // Get the element type.
Mike Stump1eb44332009-09-09 15:08:12 +0000703 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
Chris Lattner1b726772010-12-02 07:07:26 +0000704 const llvm::Type *LElemPtrTy = LElemTy->getPointerTo(Ty.getAddressSpace());
Anders Carlsson5d463152008-12-12 07:38:43 +0000705
Anders Carlsson60d35412008-12-20 20:46:34 +0000706 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000707
708 // Allocate memory for the array.
Anders Carlsson41f8a132009-09-26 18:16:06 +0000709 llvm::AllocaInst *VLA =
John McCalld16c2cf2011-02-08 08:22:06 +0000710 Builder.CreateAlloca(llvm::Type::getInt8Ty(getLLVMContext()), VLASize, "vla");
Ken Dyck8b752f12010-01-27 17:10:57 +0000711 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000712
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000713 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716 llvm::Value *&DMEntry = LocalDeclMap[&D];
717 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
718 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000719
720 // Emit debug info for local var declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000721 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000722 assert(HaveInsertPoint() && "Unexpected unreachable point!");
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Daniel Dunbar66031a52008-10-17 16:15:48 +0000724 DI->setLocation(D.getLocation());
Sanjiv Gupta4381d4b2009-05-22 13:54:25 +0000725 if (Target.useGlobalsForAutomaticVariables()) {
726 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
Mike Stumpdab514f2009-03-04 03:23:46 +0000727 } else
728 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000729 }
730
Chris Lattner19785962007-07-12 00:39:48 +0000731 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +0000732 const Expr *Init = D.getInit();
733
734 // If we are at an unreachable point, we don't need to emit the initializer
735 // unless it contains a label.
736 if (!HaveInsertPoint()) {
737 if (!ContainsLabel(Init))
738 Init = 0;
739 else
740 EnsureInsertPoint();
741 }
742
Mike Stumpdab514f2009-03-04 03:23:46 +0000743 if (isByRef) {
Daniel Dunbard286f052009-07-19 06:58:07 +0000744 EnsureInsertPoint();
Mike Stumpdab514f2009-03-04 03:23:46 +0000745 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
746 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
747 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
748 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
749 llvm::Value *V;
John McCalld16c2cf2011-02-08 08:22:06 +0000750
751 BlockFieldFlags fieldFlags;
752 bool fieldNeedsCopyDispose = false;
Mike Stumpdab514f2009-03-04 03:23:46 +0000753
Mike Stumpf4bc3122009-03-07 06:04:31 +0000754 needsDispose = true;
Mike Stump00470a12009-03-05 08:32:30 +0000755
Mike Stumpdab514f2009-03-04 03:23:46 +0000756 if (Ty->isBlockPointerType()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000757 fieldFlags |= BLOCK_FIELD_IS_BLOCK;
758 fieldNeedsCopyDispose = true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +0000759 } else if (getContext().isObjCNSObjectType(Ty) ||
760 Ty->isObjCObjectPointerType()) {
John McCalld16c2cf2011-02-08 08:22:06 +0000761 fieldFlags |= BLOCK_FIELD_IS_OBJECT;
762 fieldNeedsCopyDispose = true;
763 } else if (getLangOptions().CPlusPlus) {
764 if (getContext().getBlockVarCopyInits(&D))
765 fieldNeedsCopyDispose = true;
766 else if (const CXXRecordDecl *record = D.getType()->getAsCXXRecordDecl())
767 fieldNeedsCopyDispose = !record->hasTrivialDestructor();
Mike Stumpdab514f2009-03-04 03:23:46 +0000768 }
Mike Stumpf4bc3122009-03-07 06:04:31 +0000769
770 // FIXME: Someone double check this.
771 if (Ty.isObjCGCWeak())
John McCalld16c2cf2011-02-08 08:22:06 +0000772 fieldFlags |= BLOCK_FIELD_IS_WEAK;
Mike Stumpdab514f2009-03-04 03:23:46 +0000773
774 int isa = 0;
John McCalld16c2cf2011-02-08 08:22:06 +0000775 if (fieldFlags & BLOCK_FIELD_IS_WEAK)
Mike Stumpdab514f2009-03-04 03:23:46 +0000776 isa = 1;
John McCalld16c2cf2011-02-08 08:22:06 +0000777 V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
Mike Stumpdab514f2009-03-04 03:23:46 +0000778 Builder.CreateStore(V, isa_field);
779
Anders Carlsson36043862009-09-10 01:32:12 +0000780 Builder.CreateStore(DeclPtr, forwarding_field);
Mike Stumpdab514f2009-03-04 03:23:46 +0000781
John McCalld16c2cf2011-02-08 08:22:06 +0000782 Builder.CreateStore(Builder.getInt32(fieldFlags.getBitMask()), flags_field);
Mike Stumpdab514f2009-03-04 03:23:46 +0000783
Mike Stump00470a12009-03-05 08:32:30 +0000784 const llvm::Type *V1;
785 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
Chris Lattner4c53dc12010-12-01 01:47:15 +0000786 V = Builder.getInt32(CGM.GetTargetTypeStoreSize(V1).getQuantity());
Mike Stumpdab514f2009-03-04 03:23:46 +0000787 Builder.CreateStore(V, size_field);
788
John McCalld16c2cf2011-02-08 08:22:06 +0000789 if (fieldNeedsCopyDispose) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000790 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
John McCalld16c2cf2011-02-08 08:22:06 +0000791 Builder.CreateStore(CGM.BuildbyrefCopyHelper(DeclPtr->getType(),
792 fieldFlags,
793 Align.getQuantity(), &D),
Mike Stumpee094222009-03-06 06:12:24 +0000794 copy_helper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000795
Mike Stump1851b682009-03-06 04:53:30 +0000796 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
John McCalld16c2cf2011-02-08 08:22:06 +0000797 Builder.CreateStore(CGM.BuildbyrefDestroyHelper(DeclPtr->getType(),
798 fieldFlags,
799 Align.getQuantity(), &D),
Mike Stump1851b682009-03-06 04:53:30 +0000800 destroy_helper);
Chris Lattner9a19edf2007-08-26 05:13:54 +0000801 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000802 }
Anders Carlsson69c68b72009-02-07 23:51:38 +0000803
John McCallf1549f62010-07-06 01:34:17 +0000804 if (SpecialInit) {
805 SpecialInit(*this, D, DeclPtr);
806 } else if (Init) {
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000807 llvm::Value *Loc = DeclPtr;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000808
Daniel Dunbar4cac2a12010-08-21 02:17:08 +0000809 bool isVolatile = getContext().getCanonicalType(Ty).isVolatileQualified();
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000810
811 // If the initializer was a simple constant initializer, we can optimize it
812 // in various ways.
813 if (IsSimpleConstantInitializer) {
Daniel Dunbar4cac2a12010-08-21 02:17:08 +0000814 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), Ty,this);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000815 assert(Init != 0 && "Wasn't a simple constant init?");
816
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000817 llvm::Value *SizeVal =
John McCalld16c2cf2011-02-08 08:22:06 +0000818 llvm::ConstantInt::get(IntPtrTy,
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000819 getContext().getTypeSizeInChars(Ty).getQuantity());
820
John McCalld16c2cf2011-02-08 08:22:06 +0000821 const llvm::Type *BP = Int8PtrTy;
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000822 if (Loc->getType() != BP)
823 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
Mon P Wang3ecd7852010-04-04 03:10:52 +0000824
Chris Lattner94cd0112010-12-01 02:05:19 +0000825 // If the initializer is all or mostly zeros, codegen with memset then do
826 // a few stores afterward.
827 if (shouldUseMemSetPlusStoresToInitialize(Init,
828 CGM.getTargetData().getTypeAllocSize(Init->getType()))) {
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000829 Builder.CreateMemSet(Loc, Builder.getInt8(0), SizeVal,
830 Align.getQuantity(), false);
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000831 if (!Init->isNullValue()) {
832 Loc = Builder.CreateBitCast(Loc, Init->getType()->getPointerTo());
833 emitStoresForInitAfterMemset(Init, Loc, Builder);
834 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000835
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000836 } else {
837 // Otherwise, create a temporary global with the initializer then
838 // memcpy from the global to the alloca.
839 std::string Name = GetStaticDeclName(*this, D, ".");
840 llvm::GlobalVariable *GV =
841 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
842 llvm::GlobalValue::InternalLinkage,
843 Init, Name, 0, false, 0);
844 GV->setAlignment(Align.getQuantity());
845
846 llvm::Value *SrcPtr = GV;
847 if (SrcPtr->getType() != BP)
848 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
Mon P Wang3ecd7852010-04-04 03:10:52 +0000849
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000850 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, Align.getQuantity(), false);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000851 }
852 } else if (Ty->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000853 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Fariborz Jahanian52a80e12011-01-26 23:08:27 +0000854 if (isByRef)
855 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
856 D.getNameAsString());
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000857 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Alignment, Ty);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000858 } else if (!hasAggregateLLVMType(Init->getType())) {
859 llvm::Value *V = EmitScalarExpr(Init);
Fariborz Jahanian52a80e12011-01-26 23:08:27 +0000860 if (isByRef) {
861 // When RHS has side-effect, must go through "forwarding' field
862 // to get to the address of the __block variable descriptor.
863 if (Init->HasSideEffects(getContext()))
864 Loc = BuildBlockByrefAddress(DeclPtr, &D);
865 else
866 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
867 D.getNameAsString());
868 }
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000869 EmitStoreOfScalar(V, Loc, isVolatile, Alignment, Ty);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000870 } else if (Init->getType()->isAnyComplexType()) {
Fariborz Jahanian52a80e12011-01-26 23:08:27 +0000871 if (isByRef)
872 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
873 D.getNameAsString());
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000874 EmitComplexExprIntoAddr(Init, Loc, isVolatile);
875 } else {
Fariborz Jahanian52a80e12011-01-26 23:08:27 +0000876 if (isByRef)
877 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
878 D.getNameAsString());
Chris Lattner1b726772010-12-02 07:07:26 +0000879 EmitAggExpr(Init, AggValueSlot::forAddr(Loc, isVolatile, true, false));
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000880 }
881 }
John McCallf1549f62010-07-06 01:34:17 +0000882
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000883 // Handle CXX destruction of variables.
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000884 QualType DtorTy(Ty);
Douglas Gregor89c49f02009-11-09 22:08:55 +0000885 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000886 DtorTy = getContext().getBaseElementType(Array);
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000887 if (const RecordType *RT = DtorTy->getAs<RecordType>())
Douglas Gregord86c4772010-05-15 06:46:45 +0000888 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000889 if (!ClassDecl->hasTrivialDestructor()) {
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000890 // Note: We suppress the destructor call when the corresponding NRVO
891 // flag has been set.
Douglas Gregord86c4772010-05-15 06:46:45 +0000892 llvm::Value *Loc = DeclPtr;
893 if (isByRef)
894 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
895 D.getNameAsString());
896
Douglas Gregor1d110e02010-07-01 14:13:13 +0000897 const CXXDestructorDecl *D = ClassDecl->getDestructor();
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000898 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000899
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000900 if (const ConstantArrayType *Array =
901 getContext().getAsConstantArrayType(Ty)) {
John McCall1f0fca52010-07-21 07:22:38 +0000902 EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
903 D, Array, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000904 } else {
John McCall1f0fca52010-07-21 07:22:38 +0000905 EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
906 D, NRVOFlag, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000907 }
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000908 }
909 }
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Anders Carlsson69c68b72009-02-07 23:51:38 +0000911 // Handle the cleanup attribute
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000912 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +0000913 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000915 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000916 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Anders Carlssoncabec032009-04-26 00:34:20 +0000918 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCall1f0fca52010-07-21 07:22:38 +0000919 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup,
920 F, &Info, DeclPtr, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000921 }
Mike Stump797b6322009-03-05 01:23:13 +0000922
John McCalldb2cfec2010-07-22 21:25:44 +0000923 // If this is a block variable, clean it up.
John McCalld8715092010-07-21 06:13:08 +0000924 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly)
John McCall34fdee32010-10-06 18:56:43 +0000925 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000926}
927
Mike Stump1eb44332009-09-09 15:08:12 +0000928/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +0000929/// for the specified parameter and set up LocalDeclMap.
Devang Patel34753802011-02-16 01:11:51 +0000930void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000931 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000932 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000933 "Invalid argument to EmitParmDecl");
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000934 QualType Ty = D.getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000937 // If this is an aggregate or variable sized value, reuse the input pointer.
938 if (!Ty->isConstantSizeType() ||
939 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000942 // Otherwise, create a temporary to hold the value.
Daniel Dunbar195337d2010-02-09 02:48:28 +0000943 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000945 // Store the initial value into the alloca.
John McCall5936e332011-02-15 09:22:45 +0000946 EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(),
947 getContext().getDeclAlign(&D).getQuantity(), Ty,
948 CGM.getTBAAInfo(Ty));
Reid Spencer5f016e22007-07-11 17:01:13 +0000949 }
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000950 Arg->setName(D.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000951
952 llvm::Value *&DMEntry = LocalDeclMap[&D];
953 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
954 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000955
956 // Emit debug info for param declaration.
Devang Patelfee53aa2009-10-09 22:06:15 +0000957 if (CGDebugInfo *DI = getDebugInfo()) {
958 DI->setLocation(D.getLocation());
Devang Patel34753802011-02-16 01:11:51 +0000959 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
Devang Patelfee53aa2009-10-09 22:06:15 +0000960 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000961}