CGDecl.cpp revision 18be84c37b2b796fddfb36447c2b29141d7fdd18
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 = CurFn->getName();
99    else
100      assert(0 && "Unknown context for block var decl");
101
102    Name = ContextName + Separator + D.getNameAsString();
103  }
104
105  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
106  return new llvm::GlobalVariable(CGM.getModule(), LTy,
107                                  Ty.isConstant(getContext()), Linkage,
108                                  CGM.EmitNullConstant(D.getType()), Name, 0,
109                                  D.isThreadSpecified(), Ty.getAddressSpace());
110}
111
112void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
113  llvm::Value *&DMEntry = LocalDeclMap[&D];
114  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
115
116  llvm::GlobalVariable *GV =
117    CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
118
119  // Store into LocalDeclMap before generating initializer to handle
120  // circular references.
121  DMEntry = GV;
122
123  // Make sure to evaluate VLA bounds now so that we have them for later.
124  //
125  // FIXME: Can this happen?
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        EmitStaticCXXBlockVarDeclInit(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(CGM.getModule(), Init->getType(),
148                                      OldGV->isConstant(),
149                                      OldGV->getLinkage(), Init, "",
150                                      0, D.isThreadSpecified(),
151                                      D.getType().getAddressSpace());
152
153        // Steal the name of the old global
154        GV->takeName(OldGV);
155
156        // Replace all uses of the old global with the new global
157        llvm::Constant *NewPtrForOldDecl =
158          llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
159        OldGV->replaceAllUsesWith(NewPtrForOldDecl);
160
161        // Erase the old global, since it is no longer used.
162        OldGV->eraseFromParent();
163      }
164
165      GV->setInitializer(Init);
166    }
167  }
168
169  // FIXME: Merge attribute handling.
170  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
171    SourceManager &SM = CGM.getContext().getSourceManager();
172    llvm::Constant *Ann =
173      CGM.EmitAnnotateAttr(GV, AA,
174                           SM.getInstantiationLineNumber(D.getLocation()));
175    CGM.AddAnnotation(Ann);
176  }
177
178  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
179    GV->setSection(SA->getName());
180
181  if (D.hasAttr<UsedAttr>())
182    CGM.AddUsedGlobal(GV);
183
184  // We may have to cast the constant because of the initializer
185  // mismatch above.
186  //
187  // FIXME: It is really dangerous to store this in the map; if anyone
188  // RAUW's the GV uses of this constant will be invalid.
189  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
190  const llvm::Type *LPtrTy =
191    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
192  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
193
194  // Emit global variable debug descriptor for static vars.
195  CGDebugInfo *DI = getDebugInfo();
196  if (DI) {
197    DI->setLocation(D.getLocation());
198    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
199  }
200}
201
202unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
203  assert(ByRefValueInfo.count(VD) && "Did not find value!");
204
205  return ByRefValueInfo.find(VD)->second.second;
206}
207
208/// BuildByRefType - This routine changes a __block variable declared as T x
209///   into:
210///
211///      struct {
212///        void *__isa;
213///        void *__forwarding;
214///        int32_t __flags;
215///        int32_t __size;
216///        void *__copy_helper;
217///        void *__destroy_helper;
218///        T x;
219///      } x
220///
221const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
222  std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
223  if (Info.first)
224    return Info.first;
225
226  QualType Ty = D->getType();
227
228  std::vector<const llvm::Type *> Types;
229
230  const llvm::PointerType *Int8PtrTy
231    = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
232
233  llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
234
235  // void *__isa;
236  Types.push_back(Int8PtrTy);
237
238  // void *__forwarding;
239  Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
240
241  // int32_t __flags;
242  Types.push_back(llvm::Type::getInt32Ty(VMContext));
243
244  // int32_t __size;
245  Types.push_back(llvm::Type::getInt32Ty(VMContext));
246
247  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
248  if (HasCopyAndDispose) {
249    /// void *__copy_helper;
250    Types.push_back(Int8PtrTy);
251
252    /// void *__destroy_helper;
253    Types.push_back(Int8PtrTy);
254  }
255
256  bool Packed = false;
257  unsigned Align = getContext().getDeclAlignInBytes(D);
258  if (Align > Target.getPointerAlign(0) / 8) {
259    // We have to insert padding.
260
261    // The struct above has 2 32-bit integers.
262    unsigned CurrentOffsetInBytes = 4 * 2;
263
264    // And either 2 or 4 pointers.
265    CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
266      CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
267
268    // Align the offset.
269    unsigned AlignedOffsetInBytes =
270      llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align);
271
272    unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
273    assert(NumPaddingBytes > 0 && "Can't append any padding!");
274
275    const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
276    if (NumPaddingBytes > 1)
277      Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
278
279    Types.push_back(Ty);
280
281    // We want a packed struct.
282    Packed = true;
283  }
284
285  // T x;
286  Types.push_back(ConvertType(Ty));
287
288  const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
289
290  cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
291  CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
292                              ByRefTypeHolder.get());
293
294  Info.first = ByRefTypeHolder.get();
295
296  Info.second = Types.size() - 1;
297
298  return Info.first;
299}
300
301/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
302/// variable declaration with auto, register, or no storage class specifier.
303/// These turn into simple stack objects, or GlobalValues depending on target.
304void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
305  QualType Ty = D.getType();
306  bool isByRef = D.hasAttr<BlocksAttr>();
307  bool needsDispose = false;
308  unsigned Align = 0;
309
310  llvm::Value *DeclPtr;
311  if (Ty->isConstantSizeType()) {
312    if (!Target.useGlobalsForAutomaticVariables()) {
313      // A normal fixed sized variable becomes an alloca in the entry block.
314      const llvm::Type *LTy = ConvertTypeForMem(Ty);
315      Align = getContext().getDeclAlignInBytes(&D);
316      if (isByRef)
317        LTy = BuildByRefType(&D);
318      llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
319      Alloc->setName(D.getNameAsString().c_str());
320
321      if (isByRef)
322        Align = std::max(Align, unsigned(Target.getPointerAlign(0) / 8));
323      Alloc->setAlignment(Align);
324      DeclPtr = Alloc;
325    } else {
326      // Targets that don't support recursion emit locals as globals.
327      const char *Class =
328        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
329      DeclPtr = CreateStaticBlockVarDecl(D, Class,
330                                         llvm::GlobalValue
331                                         ::InternalLinkage);
332    }
333
334    // FIXME: Can this happen?
335    if (Ty->isVariablyModifiedType())
336      EmitVLASize(Ty);
337  } else {
338    EnsureInsertPoint();
339
340    if (!DidCallStackSave) {
341      // Save the stack.
342      const llvm::Type *LTy =
343        llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
344      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
345
346      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
347      llvm::Value *V = Builder.CreateCall(F);
348
349      Builder.CreateStore(V, Stack);
350
351      DidCallStackSave = true;
352
353      {
354        // Push a cleanup block and restore the stack there.
355        CleanupScope scope(*this);
356
357        V = Builder.CreateLoad(Stack, "tmp");
358        llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
359        Builder.CreateCall(F, V);
360      }
361    }
362
363    // Get the element type.
364    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
365    const llvm::Type *LElemPtrTy =
366      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
367
368    llvm::Value *VLASize = EmitVLASize(Ty);
369
370    // Downcast the VLA size expression
371    VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
372                                    false, "tmp");
373
374    // Allocate memory for the array.
375    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext),
376                                            VLASize, "vla");
377    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
378  }
379
380  llvm::Value *&DMEntry = LocalDeclMap[&D];
381  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
382  DMEntry = DeclPtr;
383
384  // Emit debug info for local var declaration.
385  if (CGDebugInfo *DI = getDebugInfo()) {
386    assert(HaveInsertPoint() && "Unexpected unreachable point!");
387
388    DI->setLocation(D.getLocation());
389    if (Target.useGlobalsForAutomaticVariables()) {
390      DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
391    } else if (isByRef) {
392      // FIXME: This code is broken and will not emit debug info for the
393      // variable. The right way to do this would be to tell LLVM that this is a
394      // byref pointer, and what the offset is. Unfortunately, right now it's
395      // not possible unless we create a DIType that corresponds to the byref
396      // struct.
397      /*
398      llvm::Value *Loc;
399      bool needsCopyDispose = BlockRequiresCopying(Ty);
400      Loc = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
401      Loc = Builder.CreateLoad(Loc, false);
402      Loc = Builder.CreateBitCast(Loc, DeclPtr->getType());
403      Loc = Builder.CreateStructGEP(Loc, needsCopyDispose*2+4, "x");
404      DI->EmitDeclareOfAutoVariable(&D, Loc, Builder);
405      */
406    } else
407      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
408  }
409
410  // If this local has an initializer, emit it now.
411  const Expr *Init = D.getInit();
412
413  // If we are at an unreachable point, we don't need to emit the initializer
414  // unless it contains a label.
415  if (!HaveInsertPoint()) {
416    if (!ContainsLabel(Init))
417      Init = 0;
418    else
419      EnsureInsertPoint();
420  }
421
422  if (Init) {
423    llvm::Value *Loc = DeclPtr;
424    if (isByRef)
425      Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
426                                    D.getNameAsString());
427
428    if (Ty->isReferenceType()) {
429      RValue RV = EmitReferenceBindingToExpr(Init, Ty, /*IsInitializer=*/true);
430      EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty);
431    } else if (!hasAggregateLLVMType(Init->getType())) {
432      llvm::Value *V = EmitScalarExpr(Init);
433      EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified(),
434                        D.getType());
435    } else if (Init->getType()->isAnyComplexType()) {
436      EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
437    } else {
438      EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
439    }
440  }
441
442  if (isByRef) {
443    const llvm::PointerType *PtrToInt8Ty
444      = llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
445
446    EnsureInsertPoint();
447    llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
448    llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
449    llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
450    llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
451    llvm::Value *V;
452    int flag = 0;
453    int flags = 0;
454
455    needsDispose = true;
456
457    if (Ty->isBlockPointerType()) {
458      flag |= BLOCK_FIELD_IS_BLOCK;
459      flags |= BLOCK_HAS_COPY_DISPOSE;
460    } else if (BlockRequiresCopying(Ty)) {
461      flag |= BLOCK_FIELD_IS_OBJECT;
462      flags |= BLOCK_HAS_COPY_DISPOSE;
463    }
464
465    // FIXME: Someone double check this.
466    if (Ty.isObjCGCWeak())
467      flag |= BLOCK_FIELD_IS_WEAK;
468
469    int isa = 0;
470    if (flag&BLOCK_FIELD_IS_WEAK)
471      isa = 1;
472    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
473    V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
474    Builder.CreateStore(V, isa_field);
475
476    Builder.CreateStore(DeclPtr, forwarding_field);
477
478    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
479    Builder.CreateStore(V, flags_field);
480
481    const llvm::Type *V1;
482    V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
483    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
484                               (CGM.getTargetData().getTypeStoreSizeInBits(V1)
485                                / 8));
486    Builder.CreateStore(V, size_field);
487
488    if (flags & BLOCK_HAS_COPY_DISPOSE) {
489      BlockHasCopyDispose = true;
490      llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
491      Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag, Align),
492                          copy_helper);
493
494      llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
495      Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
496                                                  Align),
497                          destroy_helper);
498    }
499  }
500
501  // Handle CXX destruction of variables.
502  QualType DtorTy(Ty);
503  if (const ArrayType *Array = DtorTy->getAs<ArrayType>())
504    DtorTy = Array->getElementType();
505  if (const RecordType *RT = DtorTy->getAs<RecordType>())
506    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
507      if (!ClassDecl->hasTrivialDestructor()) {
508        const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
509        assert(D && "EmitLocalBlockVarDecl - destructor is nul");
510        assert(!Ty->getAs<ArrayType>() && "FIXME - destruction of arrays NYI");
511
512        CleanupScope scope(*this);
513        EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
514      }
515  }
516
517  // Handle the cleanup attribute
518  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
519    const FunctionDecl *FD = CA->getFunctionDecl();
520
521    llvm::Constant* F = CGM.GetAddrOfFunction(FD);
522    assert(F && "Could not find function!");
523
524    CleanupScope scope(*this);
525
526    const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
527
528    // In some cases, the type of the function argument will be different from
529    // the type of the pointer. An example of this is
530    // void f(void* arg);
531    // __attribute__((cleanup(f))) void *g;
532    //
533    // To fix this we insert a bitcast here.
534    QualType ArgTy = Info.arg_begin()->type;
535    DeclPtr = Builder.CreateBitCast(DeclPtr, ConvertType(ArgTy));
536
537    CallArgList Args;
538    Args.push_back(std::make_pair(RValue::get(DeclPtr),
539                                  getContext().getPointerType(D.getType())));
540
541    EmitCall(Info, F, Args);
542  }
543
544  if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
545    CleanupScope scope(*this);
546    llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
547    V = Builder.CreateLoad(V, false);
548    BuildBlockRelease(V);
549  }
550}
551
552/// Emit an alloca (or GlobalValue depending on target)
553/// for the specified parameter and set up LocalDeclMap.
554void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
555  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
556  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
557         "Invalid argument to EmitParmDecl");
558  QualType Ty = D.getType();
559
560  llvm::Value *DeclPtr;
561  if (!Ty->isConstantSizeType()) {
562    // Variable sized values always are passed by-reference.
563    DeclPtr = Arg;
564  } else {
565    // A fixed sized single-value variable becomes an alloca in the entry block.
566    const llvm::Type *LTy = ConvertTypeForMem(Ty);
567    if (LTy->isSingleValueType()) {
568      // TODO: Alignment
569      std::string Name = D.getNameAsString();
570      Name += ".addr";
571      DeclPtr = CreateTempAlloca(LTy);
572      DeclPtr->setName(Name.c_str());
573
574      // Store the initial value into the alloca.
575      EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), Ty);
576    } else {
577      // Otherwise, if this is an aggregate, just use the input pointer.
578      DeclPtr = Arg;
579    }
580    Arg->setName(D.getNameAsString());
581  }
582
583  llvm::Value *&DMEntry = LocalDeclMap[&D];
584  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
585  DMEntry = DeclPtr;
586
587  // Emit debug info for param declaration.
588  if (CGDebugInfo *DI = getDebugInfo()) {
589    DI->setLocation(D.getLocation());
590    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
591  }
592}
593
594