CGDecl.cpp revision ee09422b014151a6a47c2ce704a81e94467bc786
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/Target/TargetData.h"
25#include "llvm/Type.h"
26using namespace clang;
27using namespace CodeGen;
28
29
30void CodeGenFunction::EmitDecl(const Decl &D) {
31  switch (D.getKind()) {
32  default: assert(0 && "Unknown decl kind!");
33  case Decl::ParmVar:
34    assert(0 && "Parmdecls should not be in declstmts!");
35  case Decl::Function:  // void X();
36  case Decl::Record:    // struct/union/class X;
37  case Decl::Enum:      // enum X;
38  case Decl::EnumConstant: // enum ? { X = ? }
39  case Decl::CXXRecord: // struct/union/class X; [C++]
40    // None of these decls require codegen support.
41    return;
42
43  case Decl::Var: {
44    const VarDecl &VD = cast<VarDecl>(D);
45    assert(VD.isBlockVarDecl() &&
46           "Should not see file-scope variables inside a function!");
47    return EmitBlockVarDecl(VD);
48  }
49
50  case Decl::Typedef: {   // typedef int X;
51    const TypedefDecl &TD = cast<TypedefDecl>(D);
52    QualType Ty = TD.getUnderlyingType();
53
54    if (Ty->isVariablyModifiedType())
55      EmitVLASize(Ty);
56  }
57  }
58}
59
60/// EmitBlockVarDecl - This method handles emission of any variable declaration
61/// inside a function, including static vars etc.
62void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
63  switch (D.getStorageClass()) {
64  case VarDecl::Static:
65    return EmitStaticBlockVarDecl(D);
66  case VarDecl::Extern:
67    // Don't emit it now, allow it to be emitted lazily on its first use.
68    return;
69  default:
70    assert((D.getStorageClass() == VarDecl::None ||
71            D.getStorageClass() == VarDecl::Auto ||
72            D.getStorageClass() == VarDecl::Register) &&
73           "Unknown storage class");
74    return EmitLocalBlockVarDecl(D);
75  }
76}
77
78llvm::GlobalVariable *
79CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
80                                          const char *Separator,
81                                          llvm::GlobalValue::LinkageTypes
82                                          Linkage) {
83  QualType Ty = D.getType();
84  assert(Ty->isConstantSizeType() && "VLAs can't be static");
85
86  std::string ContextName;
87  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
88    ContextName = CGM.getMangledName(FD);
89  else if (isa<ObjCMethodDecl>(CurFuncDecl))
90    ContextName = std::string(CurFn->getNameStart(),
91                              CurFn->getNameStart() + CurFn->getNameLen());
92  else if (isa<BlockDecl>(CurFuncDecl))
93    // FIXME: We want to traverse up and pick a name based upon where we came
94    // from.
95    ContextName = "block";
96  else
97    assert(0 && "Unknown context for block var decl");
98
99  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
100  return new llvm::GlobalVariable(LTy, Ty.isConstant(getContext()), Linkage,
101                                  llvm::Constant::getNullValue(LTy),
102                                  ContextName + Separator + D.getNameAsString(),
103                                  &CGM.getModule(), 0, Ty.getAddressSpace());
104}
105
106void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
107
108  llvm::Value *&DMEntry = LocalDeclMap[&D];
109  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
110
111  llvm::GlobalVariable *GV =
112    CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
113
114  // Store into LocalDeclMap before generating initializer to handle
115  // circular references.
116  DMEntry = GV;
117
118  if (D.getInit()) {
119    llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), this);
120
121    // If constant emission failed, then this should be a C++ static
122    // initializer.
123    if (!Init) {
124      if (!getContext().getLangOptions().CPlusPlus)
125        CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
126      else
127        GenerateStaticCXXBlockVarDeclInit(D, GV);
128    } else {
129      // The initializer may differ in type from the global. Rewrite
130      // the global to match the initializer.  (We have to do this
131      // because some types, like unions, can't be completely represented
132      // in the LLVM type system.)
133      if (GV->getType() != Init->getType()) {
134        llvm::GlobalVariable *OldGV = GV;
135
136        GV = new llvm::GlobalVariable(Init->getType(), OldGV->isConstant(),
137                                      OldGV->getLinkage(), Init, "",
138                                      &CGM.getModule(), 0,
139                                      D.getType().getAddressSpace());
140
141        // Steal the name of the old global
142        GV->takeName(OldGV);
143
144        // Replace all uses of the old global with the new global
145        llvm::Constant *NewPtrForOldDecl =
146          llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
147        OldGV->replaceAllUsesWith(NewPtrForOldDecl);
148
149        // Erase the old global, since it is no longer used.
150        OldGV->eraseFromParent();
151      }
152
153      GV->setInitializer(Init);
154    }
155  }
156
157  // FIXME: Merge attribute handling.
158  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
159    SourceManager &SM = CGM.getContext().getSourceManager();
160    llvm::Constant *Ann =
161      CGM.EmitAnnotateAttr(GV, AA,
162                           SM.getInstantiationLineNumber(D.getLocation()));
163    CGM.AddAnnotation(Ann);
164  }
165
166  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
167    GV->setSection(SA->getName());
168
169  if (D.getAttr<UsedAttr>())
170    CGM.AddUsedGlobal(GV);
171
172  // We may have to cast the constant because of the initializer
173  // mismatch above.
174  //
175  // FIXME: It is really dangerous to store this in the map; if anyone
176  // RAUW's the GV uses of this constant will be invalid.
177  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
178  const llvm::Type *LPtrTy =
179    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
180  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
181
182  // Emit global variable debug descriptor for static vars.
183  CGDebugInfo *DI = getDebugInfo();
184  if (DI) {
185    DI->setLocation(D.getLocation());
186    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
187  }
188}
189
190/// BuildByRefType - This routine changes a __block variable declared as T x
191///   into:
192///
193///      struct {
194///        void *__isa;
195///        void *__forwarding;
196///        int32_t __flags;
197///        int32_t __size;
198///        void *__copy_helper;
199///        void *__destroy_helper;
200///        T x;
201///      } x
202///
203/// Align is the alignment needed in bytes for x.
204const llvm::Type *CodeGenFunction::BuildByRefType(QualType Ty,
205                                                  uint64_t Align) {
206  const llvm::Type *LTy = ConvertType(Ty);
207  bool needsCopyDispose = BlockRequiresCopying(Ty);
208  std::vector<const llvm::Type *> Types(needsCopyDispose*2+5);
209  const llvm::PointerType *PtrToInt8Ty
210    = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
211  Types[0] = PtrToInt8Ty;
212  Types[1] = PtrToInt8Ty;
213  Types[2] = llvm::Type::Int32Ty;
214  Types[3] = llvm::Type::Int32Ty;
215  if (needsCopyDispose) {
216    Types[4] = PtrToInt8Ty;
217    Types[5] = PtrToInt8Ty;
218  }
219  // FIXME: Align this on at least an Align boundary.
220  Types[needsCopyDispose*2 + 4] = LTy;
221  return llvm::StructType::get(Types, false);
222}
223
224/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
225/// variable declaration with auto, register, or no storage class specifier.
226/// These turn into simple stack objects, or GlobalValues depending on target.
227void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
228  QualType Ty = D.getType();
229  bool isByRef = D.getAttr<BlocksAttr>();
230  bool needsDispose = false;
231
232  llvm::Value *DeclPtr;
233  if (Ty->isConstantSizeType()) {
234    if (!Target.useGlobalsForAutomaticVariables()) {
235      // A normal fixed sized variable becomes an alloca in the entry block.
236      const llvm::Type *LTy = ConvertTypeForMem(Ty);
237      if (isByRef)
238        LTy = BuildByRefType(Ty, getContext().getDeclAlignInBytes(&D));
239      llvm::AllocaInst *Alloc =
240        CreateTempAlloca(LTy, D.getNameAsString().c_str());
241      if (isByRef)
242        Alloc->setAlignment(std::max(getContext().getDeclAlignInBytes(&D),
243                                     getContext().getTypeAlign(getContext().VoidPtrTy) / 8));
244      else
245        Alloc->setAlignment(getContext().getDeclAlignInBytes(&D));
246      DeclPtr = Alloc;
247    } else {
248      // Targets that don't support recursion emit locals as globals.
249      const char *Class =
250        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
251      DeclPtr = CreateStaticBlockVarDecl(D, Class,
252                                         llvm::GlobalValue
253                                         ::InternalLinkage);
254    }
255
256    if (Ty->isVariablyModifiedType())
257      EmitVLASize(Ty);
258  } else {
259    if (!DidCallStackSave) {
260      // Save the stack.
261      const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
262      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
263
264      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
265      llvm::Value *V = Builder.CreateCall(F);
266
267      Builder.CreateStore(V, Stack);
268
269      DidCallStackSave = true;
270
271      {
272        // Push a cleanup block and restore the stack there.
273        CleanupScope scope(*this);
274
275        V = Builder.CreateLoad(Stack, "tmp");
276        llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
277        Builder.CreateCall(F, V);
278      }
279    }
280
281    // Get the element type.
282    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
283    const llvm::Type *LElemPtrTy =
284      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
285
286    llvm::Value *VLASize = EmitVLASize(Ty);
287
288    // Downcast the VLA size expression
289    VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp");
290
291    // Allocate memory for the array.
292    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
293    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
294  }
295
296  llvm::Value *&DMEntry = LocalDeclMap[&D];
297  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
298  DMEntry = DeclPtr;
299
300  // Emit debug info for local var declaration.
301  if (CGDebugInfo *DI = getDebugInfo()) {
302    DI->setLocation(D.getLocation());
303    if (isByRef) {
304      llvm::Value *Loc;
305      bool needsCopyDispose = BlockRequiresCopying(Ty);
306      // FIXME: I think we need to indirect through the forwarding pointer first
307      Loc = Builder.CreateStructGEP(DeclPtr, needsCopyDispose*2+4, "x");
308      DI->EmitDeclareOfAutoVariable(&D, Loc, Builder);
309    } else
310      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
311  }
312
313  // If this local has an initializer, emit it now.
314  if (const Expr *Init = D.getInit()) {
315    llvm::Value *Loc = DeclPtr;
316    if (isByRef) {
317      bool needsCopyDispose = BlockRequiresCopying(Ty);
318      Loc = Builder.CreateStructGEP(DeclPtr, needsCopyDispose*2+4, "x");
319    }
320    if (!hasAggregateLLVMType(Init->getType())) {
321      llvm::Value *V = EmitScalarExpr(Init);
322      EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified());
323    } else if (Init->getType()->isAnyComplexType()) {
324      EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
325    } else {
326      EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
327    }
328  }
329  if (isByRef) {
330    const llvm::PointerType *PtrToInt8Ty
331      = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
332
333    llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
334    llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
335    llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
336    llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
337    llvm::Value *V;
338    int flag = 0;
339    int flags = 0;
340
341    // The block literal will need a copy/destroy helper.
342    BlockHasCopyDispose = true;
343
344    if (Ty->isBlockPointerType()) {
345      flag |= BLOCK_FIELD_IS_BLOCK;
346      flags |= BLOCK_HAS_COPY_DISPOSE;
347    } else if (BlockRequiresCopying(Ty)) {
348      flag |= BLOCK_FIELD_IS_OBJECT;
349      flags |= BLOCK_HAS_COPY_DISPOSE;
350    }
351    // FIXME: Need to set BLOCK_FIELD_IS_WEAK as appropriate.
352
353    int isa = 0;
354    if (flag&BLOCK_FIELD_IS_WEAK)
355      isa = 1;
356    V = llvm::ConstantInt::get(llvm::Type::Int32Ty, isa);
357    V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
358    Builder.CreateStore(V, isa_field);
359
360    V = Builder.CreateBitCast(DeclPtr, PtrToInt8Ty, "forwarding");
361    Builder.CreateStore(V, forwarding_field);
362
363    V = llvm::ConstantInt::get(llvm::Type::Int32Ty, flags);
364    Builder.CreateStore(V, flags_field);
365
366    const llvm::Type *V1;
367    V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
368    V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
369                               (CGM.getTargetData().getTypeStoreSizeInBits(V1)
370                                / 8));
371    Builder.CreateStore(V, size_field);
372
373    if (flags & BLOCK_HAS_COPY_DISPOSE) {
374      BlockHasCopyDispose = true;
375      llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
376      Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag),
377                          copy_helper);
378
379      llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
380      Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag),
381                          destroy_helper);
382    }
383    needsDispose = true;
384  }
385
386  // Handle the cleanup attribute
387  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
388    const FunctionDecl *FD = CA->getFunctionDecl();
389
390    llvm::Constant* F = CGM.GetAddrOfFunction(FD);
391    assert(F && "Could not find function!");
392
393    CleanupScope scope(*this);
394
395    CallArgList Args;
396    Args.push_back(std::make_pair(RValue::get(DeclPtr),
397                                  getContext().getPointerType(D.getType())));
398
399    EmitCall(CGM.getTypes().getFunctionInfo(FD), F, Args);
400  }
401
402  if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
403    CleanupScope scope(*this);
404    llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
405    V = Builder.CreateLoad(V, false);
406    BuildBlockRelease(V);
407  }
408}
409
410/// Emit an alloca (or GlobalValue depending on target)
411/// for the specified parameter and set up LocalDeclMap.
412void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
413  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
414  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
415         "Invalid argument to EmitParmDecl");
416  QualType Ty = D.getType();
417
418  llvm::Value *DeclPtr;
419  if (!Ty->isConstantSizeType()) {
420    // Variable sized values always are passed by-reference.
421    DeclPtr = Arg;
422  } else if (Target.useGlobalsForAutomaticVariables()) {
423    // Targets that don't have stack use global address space for parameters.
424    // Specify external linkage for such globals so that llvm optimizer do
425    // not assume there values initialized as zero.
426    DeclPtr = CreateStaticBlockVarDecl(D, ".auto.",
427                                       llvm::GlobalValue::ExternalLinkage);
428  } else {
429    // A fixed sized single-value variable becomes an alloca in the entry block.
430    const llvm::Type *LTy = ConvertTypeForMem(Ty);
431    if (LTy->isSingleValueType()) {
432      // TODO: Alignment
433      std::string Name = D.getNameAsString();
434      Name += ".addr";
435      DeclPtr = CreateTempAlloca(LTy, Name.c_str());
436
437      // Store the initial value into the alloca.
438      EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified());
439    } else {
440      // Otherwise, if this is an aggregate, just use the input pointer.
441      DeclPtr = Arg;
442    }
443    Arg->setName(D.getNameAsString());
444  }
445
446  llvm::Value *&DMEntry = LocalDeclMap[&D];
447  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
448  DMEntry = DeclPtr;
449
450  // Emit debug info for param declaration.
451  if (CGDebugInfo *DI = getDebugInfo()) {
452    DI->setLocation(D.getLocation());
453    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
454  }
455}
456
457