CGDecl.cpp revision 3aba09376c5f49c4c8d176109ea4835bc2c528ee
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/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/CodeGen/CodeGenOptions.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Type.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32void CodeGenFunction::EmitDecl(const Decl &D) {
33  switch (D.getKind()) {
34  default:
35    CGM.ErrorUnsupported(&D, "decl");
36    return;
37  case Decl::ParmVar:
38    assert(0 && "Parmdecls should not be in declstmts!");
39  case Decl::Function:  // void X();
40  case Decl::Record:    // struct/union/class X;
41  case Decl::Enum:      // enum X;
42  case Decl::EnumConstant: // enum ? { X = ? }
43  case Decl::CXXRecord: // struct/union/class X; [C++]
44  case Decl::Using:          // using X; [C++]
45  case Decl::UsingShadow:
46  case Decl::UsingDirective: // using namespace X; [C++]
47  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
48    // None of these decls require codegen support.
49    return;
50
51  case Decl::Var: {
52    const VarDecl &VD = cast<VarDecl>(D);
53    assert(VD.isBlockVarDecl() &&
54           "Should not see file-scope variables inside a function!");
55    return EmitBlockVarDecl(VD);
56  }
57
58  case Decl::Typedef: {   // typedef int X;
59    const TypedefDecl &TD = cast<TypedefDecl>(D);
60    QualType Ty = TD.getUnderlyingType();
61
62    if (Ty->isVariablyModifiedType())
63      EmitVLASize(Ty);
64  }
65  }
66}
67
68/// EmitBlockVarDecl - This method handles emission of any variable declaration
69/// inside a function, including static vars etc.
70void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
71  if (D.hasAttr<AsmLabelAttr>())
72    CGM.ErrorUnsupported(&D, "__asm__");
73
74  switch (D.getStorageClass()) {
75  case VarDecl::None:
76  case VarDecl::Auto:
77  case VarDecl::Register:
78    return EmitLocalBlockVarDecl(D);
79  case VarDecl::Static:
80    return EmitStaticBlockVarDecl(D);
81  case VarDecl::Extern:
82  case VarDecl::PrivateExtern:
83    // Don't emit it now, allow it to be emitted lazily on its first use.
84    return;
85  }
86
87  assert(0 && "Unknown storage class");
88}
89
90static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
91                                     const char *Separator) {
92  CodeGenModule &CGM = CGF.CGM;
93  if (CGF.getContext().getLangOptions().CPlusPlus)
94    return CGM.getMangledName(&D);
95
96  std::string ContextName;
97  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl))
98    ContextName = CGM.getMangledName(FD);
99  else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
100    ContextName = CGF.CurFn->getName();
101  else
102    // FIXME: What about in a block??
103    assert(0 && "Unknown context for block var decl");
104
105  return ContextName + Separator + D.getNameAsString();
106}
107
108llvm::GlobalVariable *
109CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
110                                          const char *Separator,
111                                      llvm::GlobalValue::LinkageTypes Linkage) {
112  QualType Ty = D.getType();
113  assert(Ty->isConstantSizeType() && "VLAs can't be static");
114
115  std::string Name = GetStaticDeclName(*this, D, Separator);
116
117  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
118  llvm::GlobalVariable *GV =
119    new llvm::GlobalVariable(CGM.getModule(), LTy,
120                             Ty.isConstant(getContext()), Linkage,
121                             CGM.EmitNullConstant(D.getType()), Name, 0,
122                             D.isThreadSpecified(), Ty.getAddressSpace());
123  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
124  return GV;
125}
126
127/// AddInitializerToGlobalBlockVarDecl - Add the initializer for 'D' to the
128/// global variable that has already been created for it.  If the initializer
129/// has a different type than GV does, this may free GV and return a different
130/// one.  Otherwise it just returns GV.
131llvm::GlobalVariable *
132CodeGenFunction::AddInitializerToGlobalBlockVarDecl(const VarDecl &D,
133                                                    llvm::GlobalVariable *GV) {
134  llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
135
136  // If constant emission failed, then this should be a C++ static
137  // initializer.
138  if (!Init) {
139    if (!getContext().getLangOptions().CPlusPlus)
140      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
141    else {
142      // Since we have a static initializer, this global variable can't
143      // be constant.
144      GV->setConstant(false);
145
146      EmitStaticCXXBlockVarDeclInit(D, GV);
147    }
148    return GV;
149  }
150
151  // The initializer may differ in type from the global. Rewrite
152  // the global to match the initializer.  (We have to do this
153  // because some types, like unions, can't be completely represented
154  // in the LLVM type system.)
155  if (GV->getType() != Init->getType()) {
156    llvm::GlobalVariable *OldGV = GV;
157
158    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
159                                  OldGV->isConstant(),
160                                  OldGV->getLinkage(), Init, "",
161                                  0, D.isThreadSpecified(),
162                                  D.getType().getAddressSpace());
163
164    // Steal the name of the old global
165    GV->takeName(OldGV);
166
167    // Replace all uses of the old global with the new global
168    llvm::Constant *NewPtrForOldDecl =
169    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
170    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
171
172    // Erase the old global, since it is no longer used.
173    OldGV->eraseFromParent();
174  }
175
176  GV->setInitializer(Init);
177  return GV;
178}
179
180void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
181  llvm::Value *&DMEntry = LocalDeclMap[&D];
182  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
183
184  llvm::GlobalVariable *GV =
185    CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
186
187  // Store into LocalDeclMap before generating initializer to handle
188  // circular references.
189  DMEntry = GV;
190
191  // Make sure to evaluate VLA bounds now so that we have them for later.
192  //
193  // FIXME: Can this happen?
194  if (D.getType()->isVariablyModifiedType())
195    EmitVLASize(D.getType());
196
197  // If this value has an initializer, emit it.
198  if (D.getInit())
199    GV = AddInitializerToGlobalBlockVarDecl(D, GV);
200
201  // FIXME: Merge attribute handling.
202  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
203    SourceManager &SM = CGM.getContext().getSourceManager();
204    llvm::Constant *Ann =
205      CGM.EmitAnnotateAttr(GV, AA,
206                           SM.getInstantiationLineNumber(D.getLocation()));
207    CGM.AddAnnotation(Ann);
208  }
209
210  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
211    GV->setSection(SA->getName());
212
213  if (D.hasAttr<UsedAttr>())
214    CGM.AddUsedGlobal(GV);
215
216  // We may have to cast the constant because of the initializer
217  // mismatch above.
218  //
219  // FIXME: It is really dangerous to store this in the map; if anyone
220  // RAUW's the GV uses of this constant will be invalid.
221  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
222  const llvm::Type *LPtrTy =
223    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
224  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
225
226  // Emit global variable debug descriptor for static vars.
227  CGDebugInfo *DI = getDebugInfo();
228  if (DI) {
229    DI->setLocation(D.getLocation());
230    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
231  }
232}
233
234unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
235  assert(ByRefValueInfo.count(VD) && "Did not find value!");
236
237  return ByRefValueInfo.find(VD)->second.second;
238}
239
240/// BuildByRefType - This routine changes a __block variable declared as T x
241///   into:
242///
243///      struct {
244///        void *__isa;
245///        void *__forwarding;
246///        int32_t __flags;
247///        int32_t __size;
248///        void *__copy_helper;       // only if needed
249///        void *__destroy_helper;    // only if needed
250///        char padding[X];           // only if needed
251///        T x;
252///      } x
253///
254const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
255  std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
256  if (Info.first)
257    return Info.first;
258
259  QualType Ty = D->getType();
260
261  std::vector<const llvm::Type *> Types;
262
263  const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
264
265  llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
266
267  // void *__isa;
268  Types.push_back(Int8PtrTy);
269
270  // void *__forwarding;
271  Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
272
273  // int32_t __flags;
274  Types.push_back(llvm::Type::getInt32Ty(VMContext));
275
276  // int32_t __size;
277  Types.push_back(llvm::Type::getInt32Ty(VMContext));
278
279  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
280  if (HasCopyAndDispose) {
281    /// void *__copy_helper;
282    Types.push_back(Int8PtrTy);
283
284    /// void *__destroy_helper;
285    Types.push_back(Int8PtrTy);
286  }
287
288  bool Packed = false;
289  CharUnits Align = getContext().getDeclAlign(D);
290  if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
291    // We have to insert padding.
292
293    // The struct above has 2 32-bit integers.
294    unsigned CurrentOffsetInBytes = 4 * 2;
295
296    // And either 2 or 4 pointers.
297    CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
298      CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
299
300    // Align the offset.
301    unsigned AlignedOffsetInBytes =
302      llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
303
304    unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
305    if (NumPaddingBytes > 0) {
306      const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
307      // FIXME: We need a sema error for alignment larger than the minimum of
308      // the maximal stack alignmint and the alignment of malloc on the system.
309      if (NumPaddingBytes > 1)
310        Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
311
312      Types.push_back(Ty);
313
314      // We want a packed struct.
315      Packed = true;
316    }
317  }
318
319  // T x;
320  Types.push_back(ConvertType(Ty));
321
322  const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
323
324  cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
325  CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
326                              ByRefTypeHolder.get());
327
328  Info.first = ByRefTypeHolder.get();
329
330  Info.second = Types.size() - 1;
331
332  return Info.first;
333}
334
335/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
336/// variable declaration with auto, register, or no storage class specifier.
337/// These turn into simple stack objects, or GlobalValues depending on target.
338void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
339  QualType Ty = D.getType();
340  bool isByRef = D.hasAttr<BlocksAttr>();
341  bool needsDispose = false;
342  CharUnits Align = CharUnits::Zero();
343  bool IsSimpleConstantInitializer = false;
344
345  llvm::Value *DeclPtr;
346  if (Ty->isConstantSizeType()) {
347    if (!Target.useGlobalsForAutomaticVariables()) {
348
349      // If this value is an array or struct, is POD, and if the initializer is
350      // a staticly determinable constant, try to optimize it.
351      if (D.getInit() && !isByRef &&
352          (Ty->isArrayType() || Ty->isRecordType()) &&
353          Ty->isPODType() &&
354          D.getInit()->isConstantInitializer(getContext())) {
355        // If this variable is marked 'const', emit the value as a global.
356        if (CGM.getCodeGenOpts().MergeAllConstants &&
357            Ty.isConstant(getContext())) {
358          EmitStaticBlockVarDecl(D);
359          return;
360        }
361
362        IsSimpleConstantInitializer = true;
363      }
364
365      // A normal fixed sized variable becomes an alloca in the entry block.
366      const llvm::Type *LTy = ConvertTypeForMem(Ty);
367      if (isByRef)
368        LTy = BuildByRefType(&D);
369      llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
370      Alloc->setName(D.getNameAsString());
371
372      Align = getContext().getDeclAlign(&D);
373      if (isByRef)
374        Align = std::max(Align,
375            CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
376      Alloc->setAlignment(Align.getQuantity());
377      DeclPtr = Alloc;
378    } else {
379      // Targets that don't support recursion emit locals as globals.
380      const char *Class =
381        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
382      DeclPtr = CreateStaticBlockVarDecl(D, Class,
383                                         llvm::GlobalValue
384                                         ::InternalLinkage);
385    }
386
387    // FIXME: Can this happen?
388    if (Ty->isVariablyModifiedType())
389      EmitVLASize(Ty);
390  } else {
391    EnsureInsertPoint();
392
393    if (!DidCallStackSave) {
394      // Save the stack.
395      const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
396      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
397
398      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
399      llvm::Value *V = Builder.CreateCall(F);
400
401      Builder.CreateStore(V, Stack);
402
403      DidCallStackSave = true;
404
405      {
406        // Push a cleanup block and restore the stack there.
407        DelayedCleanupBlock scope(*this);
408
409        V = Builder.CreateLoad(Stack, "tmp");
410        llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
411        Builder.CreateCall(F, V);
412      }
413    }
414
415    // Get the element type.
416    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
417    const llvm::Type *LElemPtrTy =
418      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
419
420    llvm::Value *VLASize = EmitVLASize(Ty);
421
422    // Downcast the VLA size expression
423    VLASize = Builder.CreateIntCast(VLASize, llvm::Type::getInt32Ty(VMContext),
424                                    false, "tmp");
425
426    // Allocate memory for the array.
427    llvm::AllocaInst *VLA =
428      Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
429    VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
430
431    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
432  }
433
434  llvm::Value *&DMEntry = LocalDeclMap[&D];
435  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
436  DMEntry = DeclPtr;
437
438  // Emit debug info for local var declaration.
439  if (CGDebugInfo *DI = getDebugInfo()) {
440    assert(HaveInsertPoint() && "Unexpected unreachable point!");
441
442    DI->setLocation(D.getLocation());
443    if (Target.useGlobalsForAutomaticVariables()) {
444      DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
445    } else
446      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
447  }
448
449  // If this local has an initializer, emit it now.
450  const Expr *Init = D.getInit();
451
452  // If we are at an unreachable point, we don't need to emit the initializer
453  // unless it contains a label.
454  if (!HaveInsertPoint()) {
455    if (!ContainsLabel(Init))
456      Init = 0;
457    else
458      EnsureInsertPoint();
459  }
460
461  if (Init) {
462    llvm::Value *Loc = DeclPtr;
463    if (isByRef)
464      Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
465                                    D.getNameAsString());
466
467    bool isVolatile =
468      getContext().getCanonicalType(D.getType()).isVolatileQualified();
469
470    // If the initializer was a simple constant initializer, we can optimize it
471    // in various ways.
472    if (IsSimpleConstantInitializer) {
473      llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(),D.getType(),this);
474      assert(Init != 0 && "Wasn't a simple constant init?");
475
476      llvm::Value *AlignVal =
477        llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
478            Align.getQuantity());
479      const llvm::Type *IntPtr =
480        llvm::IntegerType::get(VMContext, LLVMPointerWidth);
481      llvm::Value *SizeVal =
482        llvm::ConstantInt::get(IntPtr,
483            getContext().getTypeSizeInChars(Ty).getQuantity());
484
485      const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
486      if (Loc->getType() != BP)
487        Loc = Builder.CreateBitCast(Loc, BP, "tmp");
488
489      // If the initializer is all zeros, codegen with memset.
490      if (isa<llvm::ConstantAggregateZero>(Init)) {
491        llvm::Value *Zero =
492          llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0);
493        Builder.CreateCall4(CGM.getMemSetFn(), Loc, Zero, SizeVal, AlignVal);
494      } else {
495        // Otherwise, create a temporary global with the initializer then
496        // memcpy from the global to the alloca.
497        std::string Name = GetStaticDeclName(*this, D, ".");
498        llvm::GlobalVariable *GV =
499          new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
500                                   llvm::GlobalValue::InternalLinkage,
501                                   Init, Name, 0, false, 0);
502        GV->setAlignment(Align.getQuantity());
503
504        llvm::Value *SrcPtr = GV;
505        if (SrcPtr->getType() != BP)
506          SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
507
508        Builder.CreateCall4(CGM.getMemCpyFn(), Loc, SrcPtr, SizeVal, AlignVal);
509      }
510    } else if (const CXXBindReferenceExpr *BE =
511                dyn_cast<CXXBindReferenceExpr>(Init)) {
512      llvm::Value *V = EmitCXXBindReferenceExpr(BE);
513      EmitStoreOfScalar(V, Loc, /*Volatile=*/false, Ty);
514    } else if (Ty->isReferenceType()) {
515      RValue RV = EmitReferenceBindingToExpr(Init, Ty, /*IsInitializer=*/true);
516      EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Ty);
517    } else if (!hasAggregateLLVMType(Init->getType())) {
518      llvm::Value *V = EmitScalarExpr(Init);
519      EmitStoreOfScalar(V, Loc, isVolatile, D.getType());
520    } else if (Init->getType()->isAnyComplexType()) {
521      EmitComplexExprIntoAddr(Init, Loc, isVolatile);
522    } else {
523      EmitAggExpr(Init, Loc, isVolatile);
524    }
525  }
526
527  if (isByRef) {
528    const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
529
530    EnsureInsertPoint();
531    llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
532    llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
533    llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
534    llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
535    llvm::Value *V;
536    int flag = 0;
537    int flags = 0;
538
539    needsDispose = true;
540
541    if (Ty->isBlockPointerType()) {
542      flag |= BLOCK_FIELD_IS_BLOCK;
543      flags |= BLOCK_HAS_COPY_DISPOSE;
544    } else if (BlockRequiresCopying(Ty)) {
545      flag |= BLOCK_FIELD_IS_OBJECT;
546      flags |= BLOCK_HAS_COPY_DISPOSE;
547    }
548
549    // FIXME: Someone double check this.
550    if (Ty.isObjCGCWeak())
551      flag |= BLOCK_FIELD_IS_WEAK;
552
553    int isa = 0;
554    if (flag&BLOCK_FIELD_IS_WEAK)
555      isa = 1;
556    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), isa);
557    V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
558    Builder.CreateStore(V, isa_field);
559
560    Builder.CreateStore(DeclPtr, forwarding_field);
561
562    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), flags);
563    Builder.CreateStore(V, flags_field);
564
565    const llvm::Type *V1;
566    V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
567    V = llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
568                               CGM.GetTargetTypeStoreSize(V1).getQuantity());
569    Builder.CreateStore(V, size_field);
570
571    if (flags & BLOCK_HAS_COPY_DISPOSE) {
572      BlockHasCopyDispose = true;
573      llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
574      Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
575                                               Align.getQuantity()),
576                          copy_helper);
577
578      llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
579      Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
580                                                  Align.getQuantity()),
581                          destroy_helper);
582    }
583  }
584
585  // Handle CXX destruction of variables.
586  QualType DtorTy(Ty);
587  while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
588    DtorTy = getContext().getBaseElementType(Array);
589  if (const RecordType *RT = DtorTy->getAs<RecordType>())
590    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
591      if (!ClassDecl->hasTrivialDestructor()) {
592        const CXXDestructorDecl *D = ClassDecl->getDestructor(getContext());
593        assert(D && "EmitLocalBlockVarDecl - destructor is nul");
594
595        if (const ConstantArrayType *Array =
596              getContext().getAsConstantArrayType(Ty)) {
597          {
598            DelayedCleanupBlock Scope(*this);
599            QualType BaseElementTy = getContext().getBaseElementType(Array);
600            const llvm::Type *BasePtr = ConvertType(BaseElementTy);
601            BasePtr = llvm::PointerType::getUnqual(BasePtr);
602            llvm::Value *BaseAddrPtr =
603              Builder.CreateBitCast(DeclPtr, BasePtr);
604            EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
605
606            // Make sure to jump to the exit block.
607            EmitBranch(Scope.getCleanupExitBlock());
608          }
609          if (Exceptions) {
610            EHCleanupBlock Cleanup(*this);
611            QualType BaseElementTy = getContext().getBaseElementType(Array);
612            const llvm::Type *BasePtr = ConvertType(BaseElementTy);
613            BasePtr = llvm::PointerType::getUnqual(BasePtr);
614            llvm::Value *BaseAddrPtr =
615              Builder.CreateBitCast(DeclPtr, BasePtr);
616            EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr);
617          }
618        } else {
619          {
620            DelayedCleanupBlock Scope(*this);
621            EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
622
623            // Make sure to jump to the exit block.
624            EmitBranch(Scope.getCleanupExitBlock());
625          }
626          if (Exceptions) {
627            EHCleanupBlock Cleanup(*this);
628            EmitCXXDestructorCall(D, Dtor_Complete, DeclPtr);
629          }
630        }
631      }
632  }
633
634  // Handle the cleanup attribute
635  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
636    const FunctionDecl *FD = CA->getFunctionDecl();
637
638    llvm::Constant* F = CGM.GetAddrOfFunction(FD);
639    assert(F && "Could not find function!");
640
641    const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
642
643    // In some cases, the type of the function argument will be different from
644    // the type of the pointer. An example of this is
645    // void f(void* arg);
646    // __attribute__((cleanup(f))) void *g;
647    //
648    // To fix this we insert a bitcast here.
649    QualType ArgTy = Info.arg_begin()->type;
650    {
651      DelayedCleanupBlock scope(*this);
652
653      CallArgList Args;
654      Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
655                                                           ConvertType(ArgTy))),
656                                    getContext().getPointerType(D.getType())));
657      EmitCall(Info, F, ReturnValueSlot(), Args);
658    }
659    if (Exceptions) {
660      EHCleanupBlock Cleanup(*this);
661
662      CallArgList Args;
663      Args.push_back(std::make_pair(RValue::get(Builder.CreateBitCast(DeclPtr,
664                                                           ConvertType(ArgTy))),
665                                    getContext().getPointerType(D.getType())));
666      EmitCall(Info, F, ReturnValueSlot(), Args);
667    }
668  }
669
670  if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
671    {
672      DelayedCleanupBlock scope(*this);
673      llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
674      V = Builder.CreateLoad(V);
675      BuildBlockRelease(V);
676    }
677    // FIXME: Turn this on and audit the codegen
678    if (0 && Exceptions) {
679      EHCleanupBlock Cleanup(*this);
680      llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
681      V = Builder.CreateLoad(V);
682      BuildBlockRelease(V);
683    }
684  }
685}
686
687/// Emit an alloca (or GlobalValue depending on target)
688/// for the specified parameter and set up LocalDeclMap.
689void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
690  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
691  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
692         "Invalid argument to EmitParmDecl");
693  QualType Ty = D.getType();
694  CanQualType CTy = getContext().getCanonicalType(Ty);
695
696  llvm::Value *DeclPtr;
697  if (!Ty->isConstantSizeType()) {
698    // Variable sized values always are passed by-reference.
699    DeclPtr = Arg;
700  } else {
701    // A fixed sized single-value variable becomes an alloca in the entry block.
702    const llvm::Type *LTy = ConvertTypeForMem(Ty);
703    if (LTy->isSingleValueType()) {
704      // TODO: Alignment
705      DeclPtr = CreateTempAlloca(LTy);
706      DeclPtr->setName(D.getNameAsString() + llvm::StringRef(".addr"));
707
708      // Store the initial value into the alloca.
709      EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Ty);
710    } else {
711      // Otherwise, if this is an aggregate, just use the input pointer.
712      DeclPtr = Arg;
713    }
714    Arg->setName(D.getNameAsString());
715  }
716
717  llvm::Value *&DMEntry = LocalDeclMap[&D];
718  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
719  DMEntry = DeclPtr;
720
721  // Emit debug info for param declaration.
722  if (CGDebugInfo *DI = getDebugInfo()) {
723    DI->setLocation(D.getLocation());
724    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
725  }
726}
727