blob: ee2516a850857ab5956cc0eb65f3fbbe1782de56 [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"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000019#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000021#include "clang/Basic/TargetInfo.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000022#include "llvm/GlobalVariable.h"
Anders Carlsson5d463152008-12-12 07:38:43 +000023#include "llvm/Intrinsics.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/Type.h"
25using namespace clang;
26using namespace CodeGen;
27
28
29void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000030 switch (D.getKind()) {
31 default: assert(0 && "Unknown decl kind!");
Chris Lattneraa9fc462007-10-08 21:37:32 +000032 case Decl::ParmVar:
Reid Spencer5f016e22007-07-11 17:01:13 +000033 assert(0 && "Parmdecls should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000034 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000035 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000036 case Decl::Enum: // enum X;
Daniel Dunbar662174c82008-08-29 17:28:43 +000037 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000038 case Decl::CXXRecord: // struct/union/class X; [C++]
Reid Spencer5f016e22007-07-11 17:01:13 +000039 // None of these decls require codegen support.
40 return;
41
Daniel Dunbar662174c82008-08-29 17:28:43 +000042 case Decl::Var: {
43 const VarDecl &VD = cast<VarDecl>(D);
44 assert(VD.isBlockVarDecl() &&
45 "Should not see file-scope variables inside a function!");
46 return EmitBlockVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000047 }
Anders Carlssonfcdbb932008-12-20 21:51:53 +000048
49 case Decl::Typedef: { // typedef int X;
50 const TypedefDecl &TD = cast<TypedefDecl>(D);
51 QualType Ty = TD.getUnderlyingType();
52
53 if (Ty->isVariablyModifiedType())
54 EmitVLASize(Ty);
55 }
Daniel Dunbar662174c82008-08-29 17:28:43 +000056 }
Reid Spencer5f016e22007-07-11 17:01:13 +000057}
58
59/// EmitBlockVarDecl - This method handles emission of any variable declaration
60/// inside a function, including static vars etc.
Steve Naroff248a7532008-04-15 22:42:06 +000061void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000062 switch (D.getStorageClass()) {
63 case VarDecl::Static:
Anders Carlsson1a86b332007-10-17 00:52:43 +000064 return EmitStaticBlockVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +000065 case VarDecl::Extern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +000066 // Don't emit it now, allow it to be emitted lazily on its first use.
67 return;
Reid Spencer5f016e22007-07-11 17:01:13 +000068 default:
69 assert((D.getStorageClass() == VarDecl::None ||
70 D.getStorageClass() == VarDecl::Auto ||
71 D.getStorageClass() == VarDecl::Register) &&
72 "Unknown storage class");
73 return EmitLocalBlockVarDecl(D);
74 }
75}
76
Daniel Dunbar0096acf2009-02-25 19:24:29 +000077llvm::GlobalVariable *
78CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
79 const char *Separator,
80 llvm::GlobalValue::LinkageTypes
81 Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +000082 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +000083 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +000084
Chris Lattner352ffde22008-02-06 04:54:32 +000085 std::string ContextName;
Anders Carlsson19567ee2008-08-25 01:38:19 +000086 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
Douglas Gregor6ec36682009-02-18 23:53:56 +000087 ContextName = CGM.getMangledName(FD);
Anders Carlsson19567ee2008-08-25 01:38:19 +000088 else if (isa<ObjCMethodDecl>(CurFuncDecl))
89 ContextName = std::string(CurFn->getNameStart(),
90 CurFn->getNameStart() + CurFn->getNameLen());
Chris Lattner352ffde22008-02-06 04:54:32 +000091 else
Anders Carlsson19567ee2008-08-25 01:38:19 +000092 assert(0 && "Unknown context for block var decl");
Nate Begeman8bd4afe2008-04-19 04:17:09 +000093
Daniel Dunbar0096acf2009-02-25 19:24:29 +000094 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
95 return new llvm::GlobalVariable(LTy, Ty.isConstant(getContext()), Linkage,
96 llvm::Constant::getNullValue(LTy),
97 ContextName + Separator + D.getNameAsString(),
98 &CGM.getModule(), 0, Ty.getAddressSpace());
99}
100
Daniel Dunbara985b312009-02-25 19:45:19 +0000101void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000102
Daniel Dunbara985b312009-02-25 19:45:19 +0000103 llvm::Value *&DMEntry = LocalDeclMap[&D];
104 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
105
106 llvm::GlobalVariable *GV =
107 CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
108
Daniel Dunbare5731f82009-02-25 20:08:33 +0000109 // Store into LocalDeclMap before generating initializer to handle
110 // circular references.
111 DMEntry = GV;
112
Daniel Dunbara985b312009-02-25 19:45:19 +0000113 if (D.getInit()) {
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000114 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), this);
115
116 // If constant emission failed, then this should be a C++ static
117 // initializer.
118 if (!Init) {
119 if (!getContext().getLangOptions().CPlusPlus)
120 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
121 else
122 GenerateStaticCXXBlockVarDeclInit(D, GV);
123 } else {
124 // The initializer may differ in type from the global. Rewrite
125 // the global to match the initializer!?
126 //
127 // FIXME: This matches what we have been doing historically, but
128 // it seems bad. Shouldn't the init expression have the right
129 // type?
130 if (GV->getType() != Init->getType()) {
131 llvm::GlobalVariable *OldGV = GV;
132
133 GV = new llvm::GlobalVariable(Init->getType(), OldGV->isConstant(),
134 OldGV->getLinkage(), Init, "",
135 &CGM.getModule(), 0,
136 D.getType().getAddressSpace());
137
138 // Steal the name of the old global
139 GV->takeName(OldGV);
140
141 // Replace all uses of the old global with the new global
142 llvm::Constant *NewPtrForOldDecl =
143 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
144 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
145
146 // Erase the old global, since it is no longer used.
147 OldGV->eraseFromParent();
148 }
149
150 GV->setInitializer(Init);
151 }
152 }
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000153
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000154 // FIXME: Merge attribute handling.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000155 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
156 SourceManager &SM = CGM.getContext().getSourceManager();
157 llvm::Constant *Ann =
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000158 CGM.EmitAnnotateAttr(GV, AA,
159 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000160 CGM.AddAnnotation(Ann);
161 }
162
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000163 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
164 GV->setSection(SA->getName());
165
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000166 if (D.getAttr<UsedAttr>())
167 CGM.AddUsedGlobal(GV);
168
Daniel Dunbare5731f82009-02-25 20:08:33 +0000169 // We may have to cast the constant because of the initializer
170 // mismatch above.
171 //
172 // FIXME: It is really dangerous to store this in the map; if anyone
173 // RAUW's the GV uses of this constant will be invalid.
Eli Friedman26590522008-06-08 01:23:18 +0000174 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
175 const llvm::Type *LPtrTy =
176 llvm::PointerType::get(LTy, D.getType().getAddressSpace());
177 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000178
179 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000180 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000181 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000182 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000183 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
184 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000185}
186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
188/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000189/// These turn into simple stack objects, or GlobalValues depending on target.
Steve Naroff248a7532008-04-15 22:42:06 +0000190void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000191 QualType Ty = D.getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000192
193 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000194 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000195 if (!Target.useGlobalsForAutomaticVariables()) {
196 // A normal fixed sized variable becomes an alloca in the entry block.
197 const llvm::Type *LTy = ConvertType(Ty);
Chris Lattner8ec03f52008-11-24 03:54:41 +0000198 llvm::AllocaInst *Alloc =
Douglas Gregor6ec36682009-02-18 23:53:56 +0000199 CreateTempAlloca(LTy, CGM.getMangledName(&D));
Eli Friedman9c2f06b2009-02-22 03:23:43 +0000200 Alloc->setAlignment(getContext().getDeclAlignInBytes(&D));
Eli Friedman77eedd62008-05-31 21:20:41 +0000201 DeclPtr = Alloc;
Chris Lattner2621fd12008-05-08 05:58:21 +0000202 } else {
203 // Targets that don't support recursion emit locals as globals.
204 const char *Class =
205 D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
Daniel Dunbara985b312009-02-25 19:45:19 +0000206 DeclPtr = CreateStaticBlockVarDecl(D, Class,
207 llvm::GlobalValue
208 ::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000209 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000210
211 if (Ty->isVariablyModifiedType())
212 EmitVLASize(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 } else {
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000214 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000215 // Save the stack.
216 const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
217 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
218
219 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
220 llvm::Value *V = Builder.CreateCall(F);
221
222 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000223
224 DidCallStackSave = true;
Anders Carlsson5d463152008-12-12 07:38:43 +0000225
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000226 {
227 // Push a cleanup block and restore the stack there.
228 CleanupScope scope(*this);
229
230 V = Builder.CreateLoad(Stack, "tmp");
231 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
232 Builder.CreateCall(F, V);
233 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000234 }
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000235
Anders Carlsson5d463152008-12-12 07:38:43 +0000236 // Get the element type.
237 const llvm::Type *LElemTy = ConvertType(Ty);
238 const llvm::Type *LElemPtrTy =
239 llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
240
Anders Carlsson60d35412008-12-20 20:46:34 +0000241 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000242
Anders Carlsson96f21472009-02-05 19:43:10 +0000243 // Downcast the VLA size expression
244 VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp");
245
Anders Carlsson5d463152008-12-12 07:38:43 +0000246 // Allocate memory for the array.
247 llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000248 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000250
Reid Spencer5f016e22007-07-11 17:01:13 +0000251 llvm::Value *&DMEntry = LocalDeclMap[&D];
252 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
253 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000254
255 // Emit debug info for local var declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000256 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000257 DI->setLocation(D.getLocation());
Chris Lattner9c85ba32008-11-10 06:08:34 +0000258 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000259 }
260
Chris Lattner19785962007-07-12 00:39:48 +0000261 // If this local has an initializer, emit it now.
Chris Lattner7f02f722007-08-24 05:35:26 +0000262 if (const Expr *Init = D.getInit()) {
Chris Lattnerd31beb12007-08-26 07:29:23 +0000263 if (!hasAggregateLLVMType(Init->getType())) {
264 llvm::Value *V = EmitScalarExpr(Init);
Chris Lattner8b2f3b72007-08-26 07:30:49 +0000265 Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified());
Chris Lattner9b2dc282008-04-04 16:54:41 +0000266 } else if (Init->getType()->isAnyComplexType()) {
Chris Lattner190dbe22007-08-26 16:22:13 +0000267 EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified());
Chris Lattner9a19edf2007-08-26 05:13:54 +0000268 } else {
Chris Lattner8b2f3b72007-08-26 07:30:49 +0000269 EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified());
Chris Lattner9a19edf2007-08-26 05:13:54 +0000270 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000271 }
Anders Carlsson69c68b72009-02-07 23:51:38 +0000272
273 // Handle the cleanup attribute
274 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
275 const FunctionDecl *FD = CA->getFunctionDecl();
276
277 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
278 assert(F && "Could not find function!");
279
280 CleanupScope scope(*this);
281
282 CallArgList Args;
283 Args.push_back(std::make_pair(RValue::get(DeclPtr),
284 getContext().getPointerType(D.getType())));
285
286 EmitCall(CGM.getTypes().getFunctionInfo(FD), F, Args);
287 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000288}
289
Chris Lattner2621fd12008-05-08 05:58:21 +0000290/// Emit an alloca (or GlobalValue depending on target)
291/// for the specified parameter and set up LocalDeclMap.
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000292void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
293 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000294 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000295 "Invalid argument to EmitParmDecl");
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000296 QualType Ty = D.getType();
Reid Spencer5f016e22007-07-11 17:01:13 +0000297
298 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000299 if (!Ty->isConstantSizeType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 // Variable sized values always are passed by-reference.
301 DeclPtr = Arg;
Chris Lattner2621fd12008-05-08 05:58:21 +0000302 } else if (Target.useGlobalsForAutomaticVariables()) {
Sanjiv Gupta45206ec2009-02-03 18:07:49 +0000303 // Targets that don't have stack use global address space for parameters.
304 // Specify external linkage for such globals so that llvm optimizer do
305 // not assume there values initialized as zero.
Daniel Dunbara985b312009-02-25 19:45:19 +0000306 DeclPtr = CreateStaticBlockVarDecl(D, ".auto.",
307 llvm::GlobalValue::ExternalLinkage);
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 } else {
Dan Gohmand79a7262008-05-22 22:12:56 +0000309 // A fixed sized single-value variable becomes an alloca in the entry block.
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 const llvm::Type *LTy = ConvertType(Ty);
Dan Gohmand79a7262008-05-22 22:12:56 +0000311 if (LTy->isSingleValueType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // TODO: Alignment
Chris Lattner39f34e92008-11-24 04:00:27 +0000313 std::string Name = D.getNameAsString();
Daniel Dunbar56273772008-09-17 00:51:38 +0000314 Name += ".addr";
315 DeclPtr = CreateTempAlloca(LTy, Name.c_str());
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
317 // Store the initial value into the alloca.
Eli Friedman1e692ac2008-06-13 23:01:12 +0000318 Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified());
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 } else {
320 // Otherwise, if this is an aggregate, just use the input pointer.
321 DeclPtr = Arg;
322 }
Chris Lattner39f34e92008-11-24 04:00:27 +0000323 Arg->setName(D.getNameAsString());
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 }
325
326 llvm::Value *&DMEntry = LocalDeclMap[&D];
327 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
328 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000329
330 // Emit debug info for param declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000331 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000332 DI->setLocation(D.getLocation());
Chris Lattner9c85ba32008-11-10 06:08:34 +0000333 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000334 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000335}
336