blob: 8115e384db845e82b09771761690775e714ee9a1 [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"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000020#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000022#include "clang/Basic/TargetInfo.h"
Chandler Carruth2811ccf2009-11-12 17:24:48 +000023#include "clang/CodeGen/CodeGenOptions.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson5d463152008-12-12 07:38:43 +000025#include "llvm/Intrinsics.h"
Mike Stumpdab514f2009-03-04 03:23:46 +000026#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Type.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000033 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000034 case Decl::TranslationUnit:
35 case Decl::Namespace:
36 case Decl::UnresolvedUsingTypename:
37 case Decl::ClassTemplateSpecialization:
38 case Decl::ClassTemplatePartialSpecialization:
39 case Decl::TemplateTypeParm:
40 case Decl::UnresolvedUsingValue:
41 case Decl::NonTypeTemplateParm:
42 case Decl::CXXMethod:
43 case Decl::CXXConstructor:
44 case Decl::CXXDestructor:
45 case Decl::CXXConversion:
46 case Decl::Field:
47 case Decl::ObjCIvar:
48 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000049 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ImplicitParam:
51 case Decl::ClassTemplate:
52 case Decl::FunctionTemplate:
53 case Decl::TemplateTemplateParm:
54 case Decl::ObjCMethod:
55 case Decl::ObjCCategory:
56 case Decl::ObjCProtocol:
57 case Decl::ObjCInterface:
58 case Decl::ObjCCategoryImpl:
59 case Decl::ObjCImplementation:
60 case Decl::ObjCProperty:
61 case Decl::ObjCCompatibleAlias:
62 case Decl::LinkageSpec:
63 case Decl::ObjCPropertyImpl:
64 case Decl::ObjCClass:
65 case Decl::ObjCForwardProtocol:
66 case Decl::FileScopeAsm:
67 case Decl::Friend:
68 case Decl::FriendTemplate:
69 case Decl::Block:
70
71 assert(0 && "Declaration not should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000072 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000073 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000074 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000075 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000076 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000077 case Decl::Using: // using X; [C++]
78 case Decl::UsingShadow:
79 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000080 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000081 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Reid Spencer5f016e22007-07-11 17:01:13 +000082 // None of these decls require codegen support.
83 return;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Daniel Dunbar662174c82008-08-29 17:28:43 +000085 case Decl::Var: {
86 const VarDecl &VD = cast<VarDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +000087 assert(VD.isBlockVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000088 "Should not see file-scope variables inside a function!");
89 return EmitBlockVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000090 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Anders Carlssonfcdbb932008-12-20 21:51:53 +000092 case Decl::Typedef: { // typedef int X;
93 const TypedefDecl &TD = cast<TypedefDecl>(D);
94 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +000095
Anders Carlssonfcdbb932008-12-20 21:51:53 +000096 if (Ty->isVariablyModifiedType())
97 EmitVLASize(Ty);
98 }
Daniel Dunbar662174c82008-08-29 17:28:43 +000099 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000100}
101
102/// EmitBlockVarDecl - This method handles emission of any variable declaration
103/// inside a function, including static vars etc.
Steve Naroff248a7532008-04-15 22:42:06 +0000104void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000105 if (D.hasAttr<AsmLabelAttr>())
Fariborz Jahanianba8639d2009-03-30 20:32:06 +0000106 CGM.ErrorUnsupported(&D, "__asm__");
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 switch (D.getStorageClass()) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000109 case VarDecl::None:
110 case VarDecl::Auto:
111 case VarDecl::Register:
112 return EmitLocalBlockVarDecl(D);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000113 case VarDecl::Static: {
114 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
126 return EmitStaticBlockVarDecl(D, Linkage);
127 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 case VarDecl::Extern:
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000129 case VarDecl::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) {
141 MangleBuffer Name;
142 CGM.getMangledName(Name, &D);
143 return Name.getString().str();
144 }
Chris Lattner761acc12009-12-05 08:22:11 +0000145
146 std::string ContextName;
John McCallf746aa62010-03-19 23:29:14 +0000147 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
148 MangleBuffer Name;
149 CGM.getMangledName(Name, FD);
150 ContextName = Name.getString().str();
151 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000152 ContextName = CGF.CurFn->getName();
153 else
154 // FIXME: What about in a block??
155 assert(0 && "Unknown context for block var decl");
156
157 return ContextName + Separator + D.getNameAsString();
158}
159
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000160llvm::GlobalVariable *
161CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
162 const char *Separator,
Chris Lattner761acc12009-12-05 08:22:11 +0000163 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000164 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000165 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000166
Chris Lattner761acc12009-12-05 08:22:11 +0000167 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000168
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000169 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlsson41f8a132009-09-26 18:16:06 +0000170 llvm::GlobalVariable *GV =
171 new llvm::GlobalVariable(CGM.getModule(), LTy,
172 Ty.isConstant(getContext()), Linkage,
173 CGM.EmitNullConstant(D.getType()), Name, 0,
174 D.isThreadSpecified(), Ty.getAddressSpace());
Ken Dyck8b752f12010-01-27 17:10:57 +0000175 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000176 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000177}
178
Chris Lattner761acc12009-12-05 08:22:11 +0000179/// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
180/// global variable that has already been created for it. If the initializer
181/// has a different type than GV does, this may free GV and return a different
182/// one. Otherwise it just returns GV.
183llvm::GlobalVariable *
184CodeGenFunction::AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
185 llvm::GlobalVariable *GV) {
186 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
187
188 // If constant emission failed, then this should be a C++ static
189 // initializer.
190 if (!Init) {
191 if (!getContext().getLangOptions().CPlusPlus)
192 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Anders Carlsson071c8102010-01-26 04:02:23 +0000193 else {
194 // Since we have a static initializer, this global variable can't
195 // be constant.
196 GV->setConstant(false);
197
Chris Lattner761acc12009-12-05 08:22:11 +0000198 EmitStaticCXXBlockVarDeclInit(D, GV);
Anders Carlsson071c8102010-01-26 04:02:23 +0000199 }
Chris Lattner761acc12009-12-05 08:22:11 +0000200 return GV;
201 }
202
203 // The initializer may differ in type from the global. Rewrite
204 // the global to match the initializer. (We have to do this
205 // because some types, like unions, can't be completely represented
206 // in the LLVM type system.)
207 if (GV->getType() != Init->getType()) {
208 llvm::GlobalVariable *OldGV = GV;
209
210 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
211 OldGV->isConstant(),
212 OldGV->getLinkage(), Init, "",
213 0, D.isThreadSpecified(),
214 D.getType().getAddressSpace());
215
216 // Steal the name of the old global
217 GV->takeName(OldGV);
218
219 // Replace all uses of the old global with the new global
220 llvm::Constant *NewPtrForOldDecl =
221 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
222 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
223
224 // Erase the old global, since it is no longer used.
225 OldGV->eraseFromParent();
226 }
227
228 GV->setInitializer(Init);
229 return GV;
230}
231
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000232void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D,
233 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara985b312009-02-25 19:45:19 +0000234 llvm::Value *&DMEntry = LocalDeclMap[&D];
235 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000237 llvm::GlobalVariable *GV = CreateStaticBlockVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000238
Daniel Dunbare5731f82009-02-25 20:08:33 +0000239 // Store into LocalDeclMap before generating initializer to handle
240 // circular references.
241 DMEntry = GV;
Fariborz Jahanian63326a52010-04-19 18:15:02 +0000242 if (getContext().getLangOptions().CPlusPlus)
243 CGM.setStaticLocalDeclAddress(&D, GV);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000244
John McCallfe67f3b2010-05-04 20:45:42 +0000245 // We can't have a VLA here, but we can have a pointer to a VLA,
246 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000247 // Make sure to evaluate VLA bounds now so that we have them for later.
248 if (D.getType()->isVariablyModifiedType())
249 EmitVLASize(D.getType());
250
Chris Lattner761acc12009-12-05 08:22:11 +0000251 // If this value has an initializer, emit it.
252 if (D.getInit())
253 GV = AddInitializerToGlobalBlockVarDecl(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000254
Chris Lattner0af95232010-03-10 23:59:59 +0000255 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
256
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000257 // FIXME: Merge attribute handling.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000258 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000259 SourceManager &SM = CGM.getContext().getSourceManager();
260 llvm::Constant *Ann =
Mike Stump1eb44332009-09-09 15:08:12 +0000261 CGM.EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000262 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000263 CGM.AddAnnotation(Ann);
264 }
265
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000266 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000267 GV->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000269 if (D.hasAttr<UsedAttr>())
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000270 CGM.AddUsedGlobal(GV);
271
Daniel Dunbare5731f82009-02-25 20:08:33 +0000272 // We may have to cast the constant because of the initializer
273 // mismatch above.
274 //
275 // FIXME: It is really dangerous to store this in the map; if anyone
276 // RAUW's the GV uses of this constant will be invalid.
Eli Friedman26590522008-06-08 01:23:18 +0000277 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
278 const llvm::Type *LPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000279 llvm::PointerType::get(LTy, D.getType().getAddressSpace());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000280 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000281
282 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000283 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000284 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000285 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000286 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
287 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000288}
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000290unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
291 assert(ByRefValueInfo.count(VD) && "Did not find value!");
292
293 return ByRefValueInfo.find(VD)->second.second;
294}
295
Mike Stumpdab514f2009-03-04 03:23:46 +0000296/// BuildByRefType - This routine changes a __block variable declared as T x
297/// into:
298///
299/// struct {
300/// void *__isa;
301/// void *__forwarding;
302/// int32_t __flags;
303/// int32_t __size;
Mike Stump39605b42009-09-22 02:12:52 +0000304/// void *__copy_helper; // only if needed
305/// void *__destroy_helper; // only if needed
306/// char padding[X]; // only if needed
Mike Stumpdab514f2009-03-04 03:23:46 +0000307/// T x;
308/// } x
309///
Anders Carlsson9ad55132009-09-09 02:51:03 +0000310const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000311 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
312 if (Info.first)
313 return Info.first;
314
Anders Carlsson9ad55132009-09-09 02:51:03 +0000315 QualType Ty = D->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Anders Carlsson18be84c2009-09-12 02:44:18 +0000317 std::vector<const llvm::Type *> Types;
Anders Carlsson36043862009-09-10 01:32:12 +0000318
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000319 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000320
Anders Carlsson36043862009-09-10 01:32:12 +0000321 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
322
Anders Carlsson18be84c2009-09-12 02:44:18 +0000323 // void *__isa;
324 Types.push_back(Int8PtrTy);
325
326 // void *__forwarding;
327 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
328
329 // int32_t __flags;
330 Types.push_back(llvm::Type::getInt32Ty(VMContext));
331
332 // int32_t __size;
333 Types.push_back(llvm::Type::getInt32Ty(VMContext));
334
335 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
336 if (HasCopyAndDispose) {
337 /// void *__copy_helper;
338 Types.push_back(Int8PtrTy);
339
340 /// void *__destroy_helper;
341 Types.push_back(Int8PtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +0000342 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000343
344 bool Packed = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000345 CharUnits Align = getContext().getDeclAlign(D);
346 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
Anders Carlsson18be84c2009-09-12 02:44:18 +0000347 // We have to insert padding.
348
349 // The struct above has 2 32-bit integers.
350 unsigned CurrentOffsetInBytes = 4 * 2;
351
352 // And either 2 or 4 pointers.
353 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
354 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
355
356 // Align the offset.
357 unsigned AlignedOffsetInBytes =
Ken Dyck8b752f12010-01-27 17:10:57 +0000358 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
Anders Carlsson18be84c2009-09-12 02:44:18 +0000359
360 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
Anders Carlssone0c88222009-09-13 17:55:13 +0000361 if (NumPaddingBytes > 0) {
362 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
Mike Stump04c688a2009-10-21 00:42:55 +0000363 // FIXME: We need a sema error for alignment larger than the minimum of
364 // the maximal stack alignmint and the alignment of malloc on the system.
Anders Carlssone0c88222009-09-13 17:55:13 +0000365 if (NumPaddingBytes > 1)
366 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000367
Anders Carlssone0c88222009-09-13 17:55:13 +0000368 Types.push_back(Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000369
Anders Carlssone0c88222009-09-13 17:55:13 +0000370 // We want a packed struct.
371 Packed = true;
372 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000373 }
374
375 // T x;
376 Types.push_back(ConvertType(Ty));
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000377
Anders Carlsson18be84c2009-09-12 02:44:18 +0000378 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
Anders Carlsson36043862009-09-10 01:32:12 +0000379
380 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
381 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
382 ByRefTypeHolder.get());
383
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000384 Info.first = ByRefTypeHolder.get();
Anders Carlsson18be84c2009-09-12 02:44:18 +0000385
386 Info.second = Types.size() - 1;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000387
388 return Info.first;
Mike Stumpdab514f2009-03-04 03:23:46 +0000389}
390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
392/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000393/// These turn into simple stack objects, or GlobalValues depending on target.
Steve Naroff248a7532008-04-15 22:42:06 +0000394void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000395 QualType Ty = D.getType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000396 bool isByRef = D.hasAttr<BlocksAttr>();
Mike Stump797b6322009-03-05 01:23:13 +0000397 bool needsDispose = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000398 CharUnits Align = CharUnits::Zero();
Chris Lattner761acc12009-12-05 08:22:11 +0000399 bool IsSimpleConstantInitializer = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000400
Douglas Gregord86c4772010-05-15 06:46:45 +0000401 bool NRVO = false;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000402 llvm::Value *NRVOFlag = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000404 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000405 if (!Target.useGlobalsForAutomaticVariables()) {
Douglas Gregord86c4772010-05-15 06:46:45 +0000406 NRVO = getContext().getLangOptions().ElideConstructors &&
407 D.isNRVOVariable();
Chris Lattnerff933b72009-12-05 06:49:57 +0000408 // If this value is an array or struct, is POD, and if the initializer is
Douglas Gregord86c4772010-05-15 06:46:45 +0000409 // a staticly determinable constant, try to optimize it (unless the NRVO
410 // is already optimizing this).
Chris Lattner761acc12009-12-05 08:22:11 +0000411 if (D.getInit() && !isByRef &&
Chris Lattnerff933b72009-12-05 06:49:57 +0000412 (Ty->isArrayType() || Ty->isRecordType()) &&
413 Ty->isPODType() &&
Douglas Gregord86c4772010-05-15 06:46:45 +0000414 D.getInit()->isConstantInitializer(getContext()) && !NRVO) {
Chris Lattnerff933b72009-12-05 06:49:57 +0000415 // If this variable is marked 'const', emit the value as a global.
416 if (CGM.getCodeGenOpts().MergeAllConstants &&
417 Ty.isConstant(getContext())) {
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000418 EmitStaticBlockVarDecl(D, llvm::GlobalValue::InternalLinkage);
Tanya Lattner59876c22009-11-04 01:18:09 +0000419 return;
420 }
Chris Lattner761acc12009-12-05 08:22:11 +0000421
422 IsSimpleConstantInitializer = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000423 }
424
Douglas Gregord86c4772010-05-15 06:46:45 +0000425 // A normal fixed sized variable becomes an alloca in the entry block,
426 // unless it's an NRVO variable.
Eli Friedmana3460ac2009-03-04 04:25:14 +0000427 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregord86c4772010-05-15 06:46:45 +0000428
429 if (NRVO) {
430 // The named return value optimization: allocate this variable in the
431 // return slot, so that we can elide the copy when returning this
432 // variable (C++0x [class.copy]p34).
433 DeclPtr = ReturnValue;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000434
435 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
436 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
437 // Create a flag that is used to indicate when the NRVO was applied
438 // to this variable. Set it to zero to indicate that NRVO was not
439 // applied.
440 const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
441 llvm::Value *Zero = llvm::ConstantInt::get(BoolTy, 0);
442 NRVOFlag = CreateTempAlloca(BoolTy, "nrvo");
443 Builder.CreateStore(Zero, NRVOFlag);
444
445 // Record the NRVO flag for this variable.
446 NRVOFlags[&D] = NRVOFlag;
447 }
448 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000449 } else {
450 if (isByRef)
451 LTy = BuildByRefType(&D);
452
453 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
454 Alloc->setName(D.getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregord86c4772010-05-15 06:46:45 +0000456 Align = getContext().getDeclAlign(&D);
457 if (isByRef)
458 Align = std::max(Align,
459 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
460 Alloc->setAlignment(Align.getQuantity());
461 DeclPtr = Alloc;
462 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000463 } else {
464 // Targets that don't support recursion emit locals as globals.
465 const char *Class =
466 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
Mike Stump1eb44332009-09-09 15:08:12 +0000467 DeclPtr = CreateStaticBlockVarDecl(D, Class,
Daniel Dunbara985b312009-02-25 19:45:19 +0000468 llvm::GlobalValue
469 ::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Daniel Dunbard286f052009-07-19 06:58:07 +0000472 // FIXME: Can this happen?
Anders Carlsson60d35412008-12-20 20:46:34 +0000473 if (Ty->isVariablyModifiedType())
474 EmitVLASize(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000476 EnsureInsertPoint();
477
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000478 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000479 // Save the stack.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000480 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson5d463152008-12-12 07:38:43 +0000481 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Anders Carlsson5d463152008-12-12 07:38:43 +0000483 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
484 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Anders Carlsson5d463152008-12-12 07:38:43 +0000486 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000487
488 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000490 {
491 // Push a cleanup block and restore the stack there.
Douglas Gregord5782d52009-11-24 16:21:10 +0000492 DelayedCleanupBlock scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000494 V = Builder.CreateLoad(Stack, "tmp");
495 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
496 Builder.CreateCall(F, V);
497 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Anders Carlsson5d463152008-12-12 07:38:43 +0000500 // Get the element type.
Mike Stump1eb44332009-09-09 15:08:12 +0000501 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000502 const llvm::Type *LElemPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000503 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
Anders Carlsson5d463152008-12-12 07:38:43 +0000504
Anders Carlsson60d35412008-12-20 20:46:34 +0000505 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000506
Anders Carlsson96f21472009-02-05 19:43:10 +0000507 // Downcast the VLA size expression
Owen Anderson0032b272009-08-13 21:57:51 +0000508 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
509 false, "tmp");
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Anders Carlsson5d463152008-12-12 07:38:43 +0000511 // Allocate memory for the array.
Anders Carlsson41f8a132009-09-26 18:16:06 +0000512 llvm::AllocaInst *VLA =
513 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
Ken Dyck8b752f12010-01-27 17:10:57 +0000514 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000515
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000516 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 llvm::Value *&DMEntry = LocalDeclMap[&D];
520 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
521 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000522
523 // Emit debug info for local var declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000524 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000525 assert(HaveInsertPoint() && "Unexpected unreachable point!");
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Daniel Dunbar66031a52008-10-17 16:15:48 +0000527 DI->setLocation(D.getLocation());
Sanjiv Gupta4381d4b2009-05-22 13:54:25 +0000528 if (Target.useGlobalsForAutomaticVariables()) {
529 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
Mike Stumpdab514f2009-03-04 03:23:46 +0000530 } else
531 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000532 }
533
Chris Lattner19785962007-07-12 00:39:48 +0000534 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +0000535 const Expr *Init = D.getInit();
536
537 // If we are at an unreachable point, we don't need to emit the initializer
538 // unless it contains a label.
539 if (!HaveInsertPoint()) {
540 if (!ContainsLabel(Init))
541 Init = 0;
542 else
543 EnsureInsertPoint();
544 }
545
Mike Stumpdab514f2009-03-04 03:23:46 +0000546 if (isByRef) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000547 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
Mike Stumpdab514f2009-03-04 03:23:46 +0000548
Daniel Dunbard286f052009-07-19 06:58:07 +0000549 EnsureInsertPoint();
Mike Stumpdab514f2009-03-04 03:23:46 +0000550 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
551 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
552 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
553 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
554 llvm::Value *V;
555 int flag = 0;
556 int flags = 0;
557
Mike Stumpf4bc3122009-03-07 06:04:31 +0000558 needsDispose = true;
Mike Stump00470a12009-03-05 08:32:30 +0000559
Mike Stumpdab514f2009-03-04 03:23:46 +0000560 if (Ty->isBlockPointerType()) {
561 flag |= BLOCK_FIELD_IS_BLOCK;
562 flags |= BLOCK_HAS_COPY_DISPOSE;
563 } else if (BlockRequiresCopying(Ty)) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000564 flag |= BLOCK_FIELD_IS_OBJECT;
Mike Stump1851b682009-03-06 04:53:30 +0000565 flags |= BLOCK_HAS_COPY_DISPOSE;
Mike Stumpdab514f2009-03-04 03:23:46 +0000566 }
Mike Stumpf4bc3122009-03-07 06:04:31 +0000567
568 // FIXME: Someone double check this.
569 if (Ty.isObjCGCWeak())
570 flag |= BLOCK_FIELD_IS_WEAK;
Mike Stumpdab514f2009-03-04 03:23:46 +0000571
572 int isa = 0;
573 if (flag&BLOCK_FIELD_IS_WEAK)
574 isa = 1;
Owen Anderson0032b272009-08-13 21:57:51 +0000575 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000576 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
Mike Stumpdab514f2009-03-04 03:23:46 +0000577 Builder.CreateStore(V, isa_field);
578
Anders Carlsson36043862009-09-10 01:32:12 +0000579 Builder.CreateStore(DeclPtr, forwarding_field);
Mike Stumpdab514f2009-03-04 03:23:46 +0000580
Owen Anderson0032b272009-08-13 21:57:51 +0000581 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
Mike Stumpdab514f2009-03-04 03:23:46 +0000582 Builder.CreateStore(V, flags_field);
583
Mike Stump00470a12009-03-05 08:32:30 +0000584 const llvm::Type *V1;
585 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
Owen Anderson0032b272009-08-13 21:57:51 +0000586 V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Ken Dyck687cc4a2010-01-26 13:48:07 +0000587 CGM.GetTargetTypeStoreSize(V1).getQuantity());
Mike Stumpdab514f2009-03-04 03:23:46 +0000588 Builder.CreateStore(V, size_field);
589
590 if (flags & BLOCK_HAS_COPY_DISPOSE) {
Mike Stump00470a12009-03-05 08:32:30 +0000591 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000592 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
Ken Dyck8b752f12010-01-27 17:10:57 +0000593 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
594 Align.getQuantity()),
Mike Stumpee094222009-03-06 06:12:24 +0000595 copy_helper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000596
Mike Stump1851b682009-03-06 04:53:30 +0000597 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
Mike Stump3899a7f2009-06-05 23:26:36 +0000598 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
Ken Dyck8b752f12010-01-27 17:10:57 +0000599 Align.getQuantity()),
Mike Stump1851b682009-03-06 04:53:30 +0000600 destroy_helper);
Chris Lattner9a19edf2007-08-26 05:13:54 +0000601 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000602 }
Anders Carlsson69c68b72009-02-07 23:51:38 +0000603
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000604 if (Init) {
605 llvm::Value *Loc = DeclPtr;
606 if (isByRef)
607 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
608 D.getNameAsString());
609
610 bool isVolatile =
611 getContext().getCanonicalType(D.getType()).isVolatileQualified();
612
613 // If the initializer was a simple constant initializer, we can optimize it
614 // in various ways.
615 if (IsSimpleConstantInitializer) {
616 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(),D.getType(),this);
617 assert(Init != 0 && "Wasn't a simple constant init?");
618
619 llvm::Value *AlignVal =
620 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
621 Align.getQuantity());
622 const llvm::Type *IntPtr =
623 llvm::IntegerType::get(VMContext, LLVMPointerWidth);
624 llvm::Value *SizeVal =
625 llvm::ConstantInt::get(IntPtr,
626 getContext().getTypeSizeInChars(Ty).getQuantity());
627
628 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
629 if (Loc->getType() != BP)
630 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
631
Mon P Wang3ecd7852010-04-04 03:10:52 +0000632 llvm::Value *NotVolatile =
633 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), 0);
634
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000635 // If the initializer is all zeros, codegen with memset.
636 if (isa<llvm::ConstantAggregateZero>(Init)) {
637 llvm::Value *Zero =
Mon P Wang3ecd7852010-04-04 03:10:52 +0000638 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0);
639 Builder.CreateCall5(CGM.getMemSetFn(Loc->getType(), SizeVal->getType()),
640 Loc, Zero, SizeVal, AlignVal, NotVolatile);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000641 } else {
642 // Otherwise, create a temporary global with the initializer then
643 // memcpy from the global to the alloca.
644 std::string Name = GetStaticDeclName(*this, D, ".");
645 llvm::GlobalVariable *GV =
646 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
647 llvm::GlobalValue::InternalLinkage,
648 Init, Name, 0, false, 0);
649 GV->setAlignment(Align.getQuantity());
650
651 llvm::Value *SrcPtr = GV;
652 if (SrcPtr->getType() != BP)
653 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
Mon P Wang3ecd7852010-04-04 03:10:52 +0000654
655 Builder.CreateCall5(CGM.getMemCpyFn(Loc->getType(), SrcPtr->getType(),
656 SizeVal->getType()),
657 Loc, SrcPtr, SizeVal, AlignVal, NotVolatile);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000658 }
659 } else if (Ty->isReferenceType()) {
660 RValue RV = EmitReferenceBindingToExpr(Init, /*IsInitializer=*/true);
661 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty);
662 } else if (!hasAggregateLLVMType(Init->getType())) {
663 llvm::Value *V = EmitScalarExpr(Init);
664 EmitStoreOfScalar(V, Loc, isVolatile, D.getType());
665 } else if (Init->getType()->isAnyComplexType()) {
666 EmitComplexExprIntoAddr(Init, Loc, isVolatile);
667 } else {
668 EmitAggExpr(Init, Loc, isVolatile);
669 }
670 }
671
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000672 // Handle CXX destruction of variables.
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000673 QualType DtorTy(Ty);
Douglas Gregor89c49f02009-11-09 22:08:55 +0000674 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000675 DtorTy = getContext().getBaseElementType(Array);
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000676 if (const RecordType *RT = DtorTy->getAs<RecordType>())
Douglas Gregord86c4772010-05-15 06:46:45 +0000677 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000678 if (!ClassDecl->hasTrivialDestructor()) {
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000679 // Note: We suppress the destructor call when the corresponding NRVO
680 // flag has been set.
Douglas Gregord86c4772010-05-15 06:46:45 +0000681 llvm::Value *Loc = DeclPtr;
682 if (isByRef)
683 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
684 D.getNameAsString());
685
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000686 const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
687 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000688
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000689 if (const ConstantArrayType *Array =
690 getContext().getAsConstantArrayType(Ty)) {
Mike Stumpd88ea562009-12-09 03:35:49 +0000691 {
692 DelayedCleanupBlock Scope(*this);
693 QualType BaseElementTy = getContext().getBaseElementType(Array);
694 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
695 BasePtr = llvm::PointerType::getUnqual(BasePtr);
696 llvm::Value *BaseAddrPtr =
Fariborz Jahanian3c347f22010-05-04 00:26:07 +0000697 Builder.CreateBitCast(Loc, BasePtr);
Mike Stumpd88ea562009-12-09 03:35:49 +0000698 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000699
Mike Stumpd88ea562009-12-09 03:35:49 +0000700 // Make sure to jump to the exit block.
701 EmitBranch(Scope.getCleanupExitBlock());
702 }
703 if (Exceptions) {
704 EHCleanupBlock Cleanup(*this);
705 QualType BaseElementTy = getContext().getBaseElementType(Array);
706 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
707 BasePtr = llvm::PointerType::getUnqual(BasePtr);
708 llvm::Value *BaseAddrPtr =
Fariborz Jahanian3c347f22010-05-04 00:26:07 +0000709 Builder.CreateBitCast(Loc, BasePtr);
Mike Stumpd88ea562009-12-09 03:35:49 +0000710 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
711 }
Fariborz Jahanian77996212009-11-04 17:57:40 +0000712 } else {
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000713 {
714 // Normal destruction.
715 DelayedCleanupBlock Scope(*this);
716
717 if (NRVO) {
718 // If we exited via NRVO, we skip the destructor call.
719 llvm::BasicBlock *NoNRVO = createBasicBlock("nrvo.unused");
720 Builder.CreateCondBr(Builder.CreateLoad(NRVOFlag, "nrvo.val"),
721 Scope.getCleanupExitBlock(),
722 NoNRVO);
723 EmitBlock(NoNRVO);
724 }
725
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000726 // We don't call the destructor along the normal edge if we're
727 // applying the NRVO.
Anders Carlsson8e6404c2010-05-02 23:29:11 +0000728 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false,
Fariborz Jahanian3c347f22010-05-04 00:26:07 +0000729 Loc);
Mike Stump73020302009-12-02 23:28:08 +0000730
Mike Stumpd88ea562009-12-09 03:35:49 +0000731 // Make sure to jump to the exit block.
732 EmitBranch(Scope.getCleanupExitBlock());
733 }
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000734
Mike Stumpd88ea562009-12-09 03:35:49 +0000735 if (Exceptions) {
736 EHCleanupBlock Cleanup(*this);
Anders Carlsson8e6404c2010-05-02 23:29:11 +0000737 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false,
Fariborz Jahanian3c347f22010-05-04 00:26:07 +0000738 Loc);
Mike Stumpd88ea562009-12-09 03:35:49 +0000739 }
Fariborz Jahanian77996212009-11-04 17:57:40 +0000740 }
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000741 }
742 }
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Anders Carlsson69c68b72009-02-07 23:51:38 +0000744 // Handle the cleanup attribute
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000745 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +0000746 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000748 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000749 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Anders Carlssoncabec032009-04-26 00:34:20 +0000751 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
752
753 // In some cases, the type of the function argument will be different from
754 // the type of the pointer. An example of this is
755 // void f(void* arg);
756 // __attribute__((cleanup(f))) void *g;
Mike Stump1eb44332009-09-09 15:08:12 +0000757 //
Anders Carlssoncabec032009-04-26 00:34:20 +0000758 // To fix this we insert a bitcast here.
759 QualType ArgTy = Info.arg_begin()->type;
Mike Stumpd88ea562009-12-09 03:35:49 +0000760 {
761 DelayedCleanupBlock scope(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Mike Stumpd88ea562009-12-09 03:35:49 +0000763 CallArgList Args;
764 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
765 ConvertType(ArgTy))),
766 getContext().getPointerType(D.getType())));
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000767 EmitCall(Info, F, ReturnValueSlot(), Args);
Mike Stumpd88ea562009-12-09 03:35:49 +0000768 }
769 if (Exceptions) {
770 EHCleanupBlock Cleanup(*this);
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Mike Stumpd88ea562009-12-09 03:35:49 +0000772 CallArgList Args;
773 Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
774 ConvertType(ArgTy))),
775 getContext().getPointerType(D.getType())));
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000776 EmitCall(Info, F, ReturnValueSlot(), Args);
Mike Stumpd88ea562009-12-09 03:35:49 +0000777 }
Anders Carlsson69c68b72009-02-07 23:51:38 +0000778 }
Mike Stump797b6322009-03-05 01:23:13 +0000779
Mike Stumpd9e0fae2009-03-05 02:34:38 +0000780 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
Mike Stumpd88ea562009-12-09 03:35:49 +0000781 {
782 DelayedCleanupBlock scope(*this);
783 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
784 V = Builder.CreateLoad(V);
785 BuildBlockRelease(V);
786 }
787 // FIXME: Turn this on and audit the codegen
788 if (0 && Exceptions) {
789 EHCleanupBlock Cleanup(*this);
790 llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
791 V = Builder.CreateLoad(V);
792 BuildBlockRelease(V);
793 }
Mike Stump797b6322009-03-05 01:23:13 +0000794 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000795}
796
Mike Stump1eb44332009-09-09 15:08:12 +0000797/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +0000798/// for the specified parameter and set up LocalDeclMap.
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000799void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
800 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000801 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000802 "Invalid argument to EmitParmDecl");
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000803 QualType Ty = D.getType();
Mike Stumpdf317bf2009-11-03 23:25:48 +0000804 CanQualType CTy = getContext().getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000807 // If this is an aggregate or variable sized value, reuse the input pointer.
808 if (!Ty->isConstantSizeType() ||
809 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000812 // Otherwise, create a temporary to hold the value.
Daniel Dunbar195337d2010-02-09 02:48:28 +0000813 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000815 // Store the initial value into the alloca.
816 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 }
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000818 Arg->setName(D.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000819
820 llvm::Value *&DMEntry = LocalDeclMap[&D];
821 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
822 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000823
824 // Emit debug info for param declaration.
Devang Patelfee53aa2009-10-09 22:06:15 +0000825 if (CGDebugInfo *DI = getDebugInfo()) {
826 DI->setLocation(D.getLocation());
Chris Lattner9c85ba32008-11-10 06:08:34 +0000827 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
Devang Patelfee53aa2009-10-09 22:06:15 +0000828 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000829}