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