CGDecl.cpp revision c4a1dea2dc56bd1357ec91b829a0b9e68229a13e
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/Basic/SourceManager.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Type.h"
23#include "llvm/Support/Dwarf.h"
24using namespace clang;
25using namespace CodeGen;
26
27
28void CodeGenFunction::EmitDecl(const Decl &D) {
29  switch (D.getKind()) {
30  default: assert(0 && "Unknown decl kind!");
31  case Decl::ParmVar:
32    assert(0 && "Parmdecls should not be in declstmts!");
33  case Decl::Typedef:   // typedef int X;
34  case Decl::Function:  // void X();
35  case Decl::Struct:    // struct X;
36  case Decl::Union:     // union X;
37  case Decl::Class:     // class X;
38  case Decl::Enum:      // enum X;
39  case Decl::CXXStruct: // struct X; [C++]
40  case Decl::CXXUnion:  // union X; [C++]
41  case Decl::CXXClass:  // class X; [C++]
42    // None of these decls require codegen support.
43    return;
44
45  case Decl::Var:
46    if (cast<VarDecl>(D).isBlockVarDecl())
47      return EmitBlockVarDecl(cast<VarDecl>(D));
48    assert(0 && "Should not see file-scope variables inside a function!");
49
50  case Decl::EnumConstant:
51    return EmitEnumConstantDecl(cast<EnumConstantDecl>(D));
52  }
53}
54
55void CodeGenFunction::EmitEnumConstantDecl(const EnumConstantDecl &D) {
56  assert(0 && "FIXME: Enum constant decls not implemented yet!");
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    Init = CGM.EmitConstantExpr(D.getInit(), this);
90  }
91
92  assert(Init && "Unable to create initialiser for static decl");
93
94  std::string ContextName;
95  if (const FunctionDecl * FD = dyn_cast<FunctionDecl>(CurFuncDecl))
96    ContextName = FD->getName();
97  else
98    assert(0 && "Unknown context for block var decl"); // FIXME Handle objc.
99
100  llvm::GlobalValue *GV =
101    new llvm::GlobalVariable(Init->getType(), false,
102                             llvm::GlobalValue::InternalLinkage,
103                             Init, ContextName + Separator + D.getName(),
104                             &CGM.getModule(), 0, Ty.getAddressSpace());
105
106  return GV;
107}
108
109void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
110
111  llvm::Value *&DMEntry = LocalDeclMap[&D];
112  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
113
114  llvm::GlobalValue *GV = GenerateStaticBlockVarDecl(D, false, ".");
115
116  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
117    SourceManager &SM = CGM.getContext().getSourceManager();
118    llvm::Constant *Ann =
119      CGM.EmitAnnotateAttr(GV, AA, SM.getLogicalLineNumber(D.getLocation()));
120    CGM.AddAnnotation(Ann);
121  }
122
123  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
124  const llvm::Type *LPtrTy =
125    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
126  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
127
128  // Emit global variable debug descriptor for static vars.
129  CGDebugInfo *DI = CGM.getDebugInfo();
130  if(DI) {
131    if(D.getLocation().isValid())
132      DI->setLocation(D.getLocation());
133    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
134  }
135
136}
137
138/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
139/// variable declaration with auto, register, or no storage class specifier.
140/// These turn into simple stack objects, or GlobalValues depending on target.
141void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
142  QualType Ty = D.getType();
143
144  llvm::Value *DeclPtr;
145  if (Ty->isConstantSizeType()) {
146    if (!Target.useGlobalsForAutomaticVariables()) {
147      // A normal fixed sized variable becomes an alloca in the entry block.
148      const llvm::Type *LTy = ConvertType(Ty);
149      llvm::AllocaInst * Alloc = CreateTempAlloca(LTy, D.getName());
150      unsigned align = getContext().getTypeAlign(Ty);
151      if (const AlignedAttr* AA = D.getAttr<AlignedAttr>())
152        align = std::max(align, AA->getAlignment());
153      Alloc->setAlignment(align >> 3);
154      DeclPtr = Alloc;
155    } else {
156      // Targets that don't support recursion emit locals as globals.
157      const char *Class =
158        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
159      DeclPtr = GenerateStaticBlockVarDecl(D, true, Class);
160    }
161  } else {
162    // TODO: Create a dynamic alloca.
163    assert(0 && "FIXME: Local VLAs not implemented yet");
164  }
165
166  llvm::Value *&DMEntry = LocalDeclMap[&D];
167  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
168  DMEntry = DeclPtr;
169
170  // Emit debug info for local var declaration.
171  CGDebugInfo *DI = CGM.getDebugInfo();
172  if(DI) {
173    if(D.getLocation().isValid())
174      DI->setLocation(D.getLocation());
175    DI->EmitDeclare(&D, llvm::dwarf::DW_TAG_auto_variable,
176                    DeclPtr, Builder);
177  }
178
179  // If this local has an initializer, emit it now.
180  if (const Expr *Init = D.getInit()) {
181    if (!hasAggregateLLVMType(Init->getType())) {
182      llvm::Value *V = EmitScalarExpr(Init);
183      Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified());
184    } else if (Init->getType()->isAnyComplexType()) {
185      EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified());
186    } else {
187      EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified());
188    }
189  }
190}
191
192/// Emit an alloca (or GlobalValue depending on target)
193/// for the specified parameter and set up LocalDeclMap.
194void CodeGenFunction::EmitParmDecl(const ParmVarDecl &D, llvm::Value *Arg) {
195  QualType Ty = D.getType();
196
197  llvm::Value *DeclPtr;
198  if (!Ty->isConstantSizeType()) {
199    // Variable sized values always are passed by-reference.
200    DeclPtr = Arg;
201  } else if (Target.useGlobalsForAutomaticVariables()) {
202    DeclPtr = GenerateStaticBlockVarDecl(D, true, ".arg.");
203  } else {
204    // A fixed sized single-value variable becomes an alloca in the entry block.
205    const llvm::Type *LTy = ConvertType(Ty);
206    if (LTy->isSingleValueType()) {
207      // TODO: Alignment
208      DeclPtr = new llvm::AllocaInst(LTy, 0, std::string(D.getName())+".addr",
209                                     AllocaInsertPt);
210
211      // Store the initial value into the alloca.
212      Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified());
213    } else {
214      // Otherwise, if this is an aggregate, just use the input pointer.
215      DeclPtr = Arg;
216    }
217    Arg->setName(D.getName());
218  }
219
220  llvm::Value *&DMEntry = LocalDeclMap[&D];
221  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
222  DMEntry = DeclPtr;
223
224  // Emit debug info for param declaration.
225  CGDebugInfo *DI = CGM.getDebugInfo();
226  if(DI) {
227    if(D.getLocation().isValid())
228      DI->setLocation(D.getLocation());
229    DI->EmitDeclare(&D, llvm::dwarf::DW_TAG_arg_variable,
230                    DeclPtr, Builder);
231  }
232
233}
234
235