CGDecl.cpp revision e5731f81497d11f95027a500a3ee118f4fc9e1be
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Type.h"
25using namespace clang;
26using namespace CodeGen;
27
28
29void CodeGenFunction::EmitDecl(const Decl &D) {
30  switch (D.getKind()) {
31  default: assert(0 && "Unknown decl kind!");
32  case Decl::ParmVar:
33    assert(0 && "Parmdecls should not be in declstmts!");
34  case Decl::Function:  // void X();
35  case Decl::Record:    // struct/union/class X;
36  case Decl::Enum:      // enum X;
37  case Decl::EnumConstant: // enum ? { X = ? }
38  case Decl::CXXRecord: // struct/union/class X; [C++]
39    // None of these decls require codegen support.
40    return;
41
42  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);
47  }
48
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  }
56  }
57}
58
59/// EmitBlockVarDecl - This method handles emission of any variable declaration
60/// inside a function, including static vars etc.
61void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
62  switch (D.getStorageClass()) {
63  case VarDecl::Static:
64    return EmitStaticBlockVarDecl(D);
65  case VarDecl::Extern:
66    // Don't emit it now, allow it to be emitted lazily on its first use.
67    return;
68  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
77llvm::GlobalVariable *
78CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
79                                          const char *Separator,
80                                          llvm::GlobalValue::LinkageTypes
81                                          Linkage) {
82  QualType Ty = D.getType();
83  assert(Ty->isConstantSizeType() && "VLAs can't be static");
84
85  std::string ContextName;
86  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
87    ContextName = CGM.getMangledName(FD);
88  else if (isa<ObjCMethodDecl>(CurFuncDecl))
89    ContextName = std::string(CurFn->getNameStart(),
90                              CurFn->getNameStart() + CurFn->getNameLen());
91  else
92    assert(0 && "Unknown context for block var decl");
93
94  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
101void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
102
103  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
109  // Store into LocalDeclMap before generating initializer to handle
110  // circular references.
111  DMEntry = GV;
112
113  if (D.getInit()) {
114    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  }
153
154  // FIXME: Merge attribute handling.
155  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
156    SourceManager &SM = CGM.getContext().getSourceManager();
157    llvm::Constant *Ann =
158      CGM.EmitAnnotateAttr(GV, AA,
159                           SM.getInstantiationLineNumber(D.getLocation()));
160    CGM.AddAnnotation(Ann);
161  }
162
163  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
164    GV->setSection(SA->getName());
165
166  if (D.getAttr<UsedAttr>())
167    CGM.AddUsedGlobal(GV);
168
169  // 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.
174  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);
178
179  // Emit global variable debug descriptor for static vars.
180  CGDebugInfo *DI = getDebugInfo();
181  if (DI) {
182    DI->setLocation(D.getLocation());
183    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
184  }
185}
186
187/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
188/// variable declaration with auto, register, or no storage class specifier.
189/// These turn into simple stack objects, or GlobalValues depending on target.
190void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
191  QualType Ty = D.getType();
192
193  llvm::Value *DeclPtr;
194  if (Ty->isConstantSizeType()) {
195    if (!Target.useGlobalsForAutomaticVariables()) {
196      // A normal fixed sized variable becomes an alloca in the entry block.
197      const llvm::Type *LTy = ConvertType(Ty);
198      llvm::AllocaInst *Alloc =
199        CreateTempAlloca(LTy, CGM.getMangledName(&D));
200      Alloc->setAlignment(getContext().getDeclAlignInBytes(&D));
201      DeclPtr = Alloc;
202    } else {
203      // Targets that don't support recursion emit locals as globals.
204      const char *Class =
205        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
206      DeclPtr = CreateStaticBlockVarDecl(D, Class,
207                                         llvm::GlobalValue
208                                         ::InternalLinkage);
209    }
210
211    if (Ty->isVariablyModifiedType())
212      EmitVLASize(Ty);
213  } else {
214    if (!DidCallStackSave) {
215      // 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);
223
224      DidCallStackSave = true;
225
226      {
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      }
234    }
235
236    // 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
241    llvm::Value *VLASize = EmitVLASize(Ty);
242
243    // Downcast the VLA size expression
244    VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp");
245
246    // Allocate memory for the array.
247    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
248    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
249  }
250
251  llvm::Value *&DMEntry = LocalDeclMap[&D];
252  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
253  DMEntry = DeclPtr;
254
255  // Emit debug info for local var declaration.
256  if (CGDebugInfo *DI = getDebugInfo()) {
257    DI->setLocation(D.getLocation());
258    DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
259  }
260
261  // If this local has an initializer, emit it now.
262  if (const Expr *Init = D.getInit()) {
263    if (!hasAggregateLLVMType(Init->getType())) {
264      llvm::Value *V = EmitScalarExpr(Init);
265      Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified());
266    } else if (Init->getType()->isAnyComplexType()) {
267      EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified());
268    } else {
269      EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified());
270    }
271  }
272
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  }
288}
289
290/// Emit an alloca (or GlobalValue depending on target)
291/// for the specified parameter and set up LocalDeclMap.
292void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
293  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
294  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
295         "Invalid argument to EmitParmDecl");
296  QualType Ty = D.getType();
297
298  llvm::Value *DeclPtr;
299  if (!Ty->isConstantSizeType()) {
300    // Variable sized values always are passed by-reference.
301    DeclPtr = Arg;
302  } else if (Target.useGlobalsForAutomaticVariables()) {
303    // 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.
306    DeclPtr = CreateStaticBlockVarDecl(D, ".auto.",
307                                       llvm::GlobalValue::ExternalLinkage);
308  } else {
309    // A fixed sized single-value variable becomes an alloca in the entry block.
310    const llvm::Type *LTy = ConvertType(Ty);
311    if (LTy->isSingleValueType()) {
312      // TODO: Alignment
313      std::string Name = D.getNameAsString();
314      Name += ".addr";
315      DeclPtr = CreateTempAlloca(LTy, Name.c_str());
316
317      // Store the initial value into the alloca.
318      Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified());
319    } else {
320      // Otherwise, if this is an aggregate, just use the input pointer.
321      DeclPtr = Arg;
322    }
323    Arg->setName(D.getNameAsString());
324  }
325
326  llvm::Value *&DMEntry = LocalDeclMap[&D];
327  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
328  DMEntry = DeclPtr;
329
330  // Emit debug info for param declaration.
331  if (CGDebugInfo *DI = getDebugInfo()) {
332    DI->setLocation(D.getLocation());
333    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
334  }
335}
336
337