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