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