CGDecl.cpp revision 8f39f5e96ce4a5f401f431f61db7df1cf05dce6f
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::GlobalValue *
78CodeGenFunction::GenerateStaticBlockVarDecl(const VarDecl &D,
79                                            bool NoInit,
80                                            const char *Separator) {
81  QualType Ty = D.getType();
82  assert(Ty->isConstantSizeType() && "VLAs can't be static");
83
84  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
85  llvm::Constant *Init = 0;
86  if ((D.getInit() == 0) || NoInit) {
87    Init = llvm::Constant::getNullValue(LTy);
88  } else {
89    if (D.getInit()->isConstantExpr(getContext(), 0))
90      Init = CGM.EmitConstantExpr(D.getInit(), this);
91    else {
92      assert(getContext().getLangOptions().CPlusPlus &&
93             "only C++ supports non-constant static initializers!");
94      return GenerateStaticCXXBlockVarDecl(D);
95    }
96  }
97
98  assert(Init && "Unable to create initialiser for static decl");
99
100  std::string ContextName;
101  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
102    ContextName = FD->getNameAsString();
103  else if (isa<ObjCMethodDecl>(CurFuncDecl))
104    ContextName = std::string(CurFn->getNameStart(),
105                              CurFn->getNameStart() + CurFn->getNameLen());
106  else
107    assert(0 && "Unknown context for block var decl");
108
109  llvm::GlobalValue *GV =
110    new llvm::GlobalVariable(Init->getType(), false,
111                             llvm::GlobalValue::InternalLinkage,
112                             Init, ContextName + Separator +D.getNameAsString(),
113                             &CGM.getModule(), 0, Ty.getAddressSpace());
114
115  return GV;
116}
117
118void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
119
120  llvm::Value *&DMEntry = LocalDeclMap[&D];
121  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
122
123  llvm::GlobalValue *GV = GenerateStaticBlockVarDecl(D, false, ".");
124
125  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
126    SourceManager &SM = CGM.getContext().getSourceManager();
127    llvm::Constant *Ann =
128      CGM.EmitAnnotateAttr(GV, AA, SM.getLogicalLineNumber(D.getLocation()));
129    CGM.AddAnnotation(Ann);
130  }
131
132  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
133  const llvm::Type *LPtrTy =
134    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
135  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
136
137  // Emit global variable debug descriptor for static vars.
138  CGDebugInfo *DI = CGM.getDebugInfo();
139  if(DI) {
140    DI->setLocation(D.getLocation());
141    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
142  }
143
144}
145
146/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
147/// variable declaration with auto, register, or no storage class specifier.
148/// These turn into simple stack objects, or GlobalValues depending on target.
149void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
150  QualType Ty = D.getType();
151
152  llvm::Value *DeclPtr;
153  if (Ty->isConstantSizeType()) {
154    if (!Target.useGlobalsForAutomaticVariables()) {
155      // A normal fixed sized variable becomes an alloca in the entry block.
156      const llvm::Type *LTy = ConvertType(Ty);
157      llvm::AllocaInst *Alloc =
158        CreateTempAlloca(LTy, D.getIdentifier()->getName());
159      unsigned align = getContext().getTypeAlign(Ty);
160      if (const AlignedAttr* AA = D.getAttr<AlignedAttr>())
161        align = std::max(align, AA->getAlignment());
162      Alloc->setAlignment(align >> 3);
163      DeclPtr = Alloc;
164    } else {
165      // Targets that don't support recursion emit locals as globals.
166      const char *Class =
167        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
168      DeclPtr = GenerateStaticBlockVarDecl(D, true, Class);
169    }
170
171    if (Ty->isVariablyModifiedType())
172      EmitVLASize(Ty);
173  } else {
174    if (!StackSaveValues.back()) {
175      // Save the stack.
176      const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
177      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
178
179      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
180      llvm::Value *V = Builder.CreateCall(F);
181
182      Builder.CreateStore(V, Stack);
183
184      StackSaveValues.back() = Stack;
185    }
186    // Get the element type.
187    const llvm::Type *LElemTy = ConvertType(Ty);
188    const llvm::Type *LElemPtrTy =
189      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
190
191    llvm::Value *VLASize = EmitVLASize(Ty);
192
193    // Allocate memory for the array.
194    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
195    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
196  }
197
198  llvm::Value *&DMEntry = LocalDeclMap[&D];
199  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
200  DMEntry = DeclPtr;
201
202  // Emit debug info for local var declaration.
203  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
204    DI->setLocation(D.getLocation());
205    DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
206  }
207
208  // If this local has an initializer, emit it now.
209  if (const Expr *Init = D.getInit()) {
210    if (!hasAggregateLLVMType(Init->getType())) {
211      llvm::Value *V = EmitScalarExpr(Init);
212      Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified());
213    } else if (Init->getType()->isAnyComplexType()) {
214      EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified());
215    } else {
216      EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified());
217    }
218  }
219}
220
221/// Emit an alloca (or GlobalValue depending on target)
222/// for the specified parameter and set up LocalDeclMap.
223void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
224  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
225  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
226         "Invalid argument to EmitParmDecl");
227  QualType Ty = D.getType();
228
229  llvm::Value *DeclPtr;
230  if (!Ty->isConstantSizeType()) {
231    // Variable sized values always are passed by-reference.
232    DeclPtr = Arg;
233  } else if (Target.useGlobalsForAutomaticVariables()) {
234    DeclPtr = GenerateStaticBlockVarDecl(D, true, ".arg.");
235  } else {
236    // A fixed sized single-value variable becomes an alloca in the entry block.
237    const llvm::Type *LTy = ConvertType(Ty);
238    if (LTy->isSingleValueType()) {
239      // TODO: Alignment
240      std::string Name = D.getNameAsString();
241      Name += ".addr";
242      DeclPtr = CreateTempAlloca(LTy, Name.c_str());
243
244      // Store the initial value into the alloca.
245      Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified());
246    } else {
247      // Otherwise, if this is an aggregate, just use the input pointer.
248      DeclPtr = Arg;
249    }
250    Arg->setName(D.getNameAsString());
251  }
252
253  llvm::Value *&DMEntry = LocalDeclMap[&D];
254  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
255  DMEntry = DeclPtr;
256
257  // Emit debug info for param declaration.
258  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
259    DI->setLocation(D.getLocation());
260    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
261  }
262}
263
264