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