CGDecl.cpp revision 207f4d8543529221932af82836016a2ef066c917
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 "CGBlocks.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Frontend/CodeGenOptions.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Type.h"
29using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
34  switch (D.getKind()) {
35  case Decl::TranslationUnit:
36  case Decl::Namespace:
37  case Decl::UnresolvedUsingTypename:
38  case Decl::ClassTemplateSpecialization:
39  case Decl::ClassTemplatePartialSpecialization:
40  case Decl::TemplateTypeParm:
41  case Decl::UnresolvedUsingValue:
42  case Decl::NonTypeTemplateParm:
43  case Decl::CXXMethod:
44  case Decl::CXXConstructor:
45  case Decl::CXXDestructor:
46  case Decl::CXXConversion:
47  case Decl::Field:
48  case Decl::IndirectField:
49  case Decl::ObjCIvar:
50  case Decl::ObjCAtDefsField:
51  case Decl::ParmVar:
52  case Decl::ImplicitParam:
53  case Decl::ClassTemplate:
54  case Decl::FunctionTemplate:
55  case Decl::TemplateTemplateParm:
56  case Decl::ObjCMethod:
57  case Decl::ObjCCategory:
58  case Decl::ObjCProtocol:
59  case Decl::ObjCInterface:
60  case Decl::ObjCCategoryImpl:
61  case Decl::ObjCImplementation:
62  case Decl::ObjCProperty:
63  case Decl::ObjCCompatibleAlias:
64  case Decl::AccessSpec:
65  case Decl::LinkageSpec:
66  case Decl::ObjCPropertyImpl:
67  case Decl::ObjCClass:
68  case Decl::ObjCForwardProtocol:
69  case Decl::FileScopeAsm:
70  case Decl::Friend:
71  case Decl::FriendTemplate:
72  case Decl::Block:
73    assert(0 && "Declaration not should not be in declstmts!");
74  case Decl::Function:  // void X();
75  case Decl::Record:    // struct/union/class X;
76  case Decl::Enum:      // enum X;
77  case Decl::EnumConstant: // enum ? { X = ? }
78  case Decl::CXXRecord: // struct/union/class X; [C++]
79  case Decl::Using:          // using X; [C++]
80  case Decl::UsingShadow:
81  case Decl::UsingDirective: // using namespace X; [C++]
82  case Decl::NamespaceAlias:
83  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
84  case Decl::Label:        // __label__ x;
85    // None of these decls require codegen support.
86    return;
87
88  case Decl::Var: {
89    const VarDecl &VD = cast<VarDecl>(D);
90    assert(VD.isLocalVarDecl() &&
91           "Should not see file-scope variables inside a function!");
92    return EmitVarDecl(VD);
93  }
94
95  case Decl::Typedef: {   // typedef int X;
96    const TypedefDecl &TD = cast<TypedefDecl>(D);
97    QualType Ty = TD.getUnderlyingType();
98
99    if (Ty->isVariablyModifiedType())
100      EmitVLASize(Ty);
101  }
102  }
103}
104
105/// EmitVarDecl - This method handles emission of any variable declaration
106/// inside a function, including static vars etc.
107void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
108  switch (D.getStorageClass()) {
109  case SC_None:
110  case SC_Auto:
111  case SC_Register:
112    return EmitAutoVarDecl(D);
113  case SC_Static: {
114    llvm::GlobalValue::LinkageTypes Linkage =
115      llvm::GlobalValue::InternalLinkage;
116
117    // If the function definition has some sort of weak linkage, its
118    // static variables should also be weak so that they get properly
119    // uniqued.  We can't do this in C, though, because there's no
120    // standard way to agree on which variables are the same (i.e.
121    // there's no mangling).
122    if (getContext().getLangOptions().CPlusPlus)
123      if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
124        Linkage = CurFn->getLinkage();
125
126    return EmitStaticVarDecl(D, Linkage);
127  }
128  case SC_Extern:
129  case SC_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    llvm::StringRef Name = CGM.getMangledName(&D);
142    return Name.str();
143  }
144
145  std::string ContextName;
146  if (!CGF.CurFuncDecl) {
147    // Better be in a block declared in global scope.
148    const NamedDecl *ND = cast<NamedDecl>(&D);
149    const DeclContext *DC = ND->getDeclContext();
150    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
151      MangleBuffer Name;
152      CGM.getBlockMangledName(GlobalDecl(), Name, BD);
153      ContextName = Name.getString();
154    }
155    else
156      assert(0 && "Unknown context for block static var decl");
157  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
158    llvm::StringRef Name = CGM.getMangledName(FD);
159    ContextName = Name.str();
160  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
161    ContextName = CGF.CurFn->getName();
162  else
163    assert(0 && "Unknown context for static var decl");
164
165  return ContextName + Separator + D.getNameAsString();
166}
167
168llvm::GlobalVariable *
169CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
170                                     const char *Separator,
171                                     llvm::GlobalValue::LinkageTypes Linkage) {
172  QualType Ty = D.getType();
173  assert(Ty->isConstantSizeType() && "VLAs can't be static");
174
175  std::string Name = GetStaticDeclName(*this, D, Separator);
176
177  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
178  llvm::GlobalVariable *GV =
179    new llvm::GlobalVariable(CGM.getModule(), LTy,
180                             Ty.isConstant(getContext()), Linkage,
181                             CGM.EmitNullConstant(D.getType()), Name, 0,
182                             D.isThreadSpecified(),
183                             CGM.getContext().getTargetAddressSpace(Ty));
184  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
185  if (Linkage != llvm::GlobalValue::InternalLinkage)
186    GV->setVisibility(CurFn->getVisibility());
187  return GV;
188}
189
190/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
191/// global variable that has already been created for it.  If the initializer
192/// has a different type than GV does, this may free GV and return a different
193/// one.  Otherwise it just returns GV.
194llvm::GlobalVariable *
195CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
196                                               llvm::GlobalVariable *GV) {
197  llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
198
199  // If constant emission failed, then this should be a C++ static
200  // initializer.
201  if (!Init) {
202    if (!getContext().getLangOptions().CPlusPlus)
203      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
204    else if (Builder.GetInsertBlock()) {
205      // Since we have a static initializer, this global variable can't
206      // be constant.
207      GV->setConstant(false);
208
209      EmitCXXGuardedInit(D, GV);
210    }
211    return GV;
212  }
213
214  // The initializer may differ in type from the global. Rewrite
215  // the global to match the initializer.  (We have to do this
216  // because some types, like unions, can't be completely represented
217  // in the LLVM type system.)
218  if (GV->getType()->getElementType() != Init->getType()) {
219    llvm::GlobalVariable *OldGV = GV;
220
221    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
222                                  OldGV->isConstant(),
223                                  OldGV->getLinkage(), Init, "",
224                                  /*InsertBefore*/ OldGV,
225                                  D.isThreadSpecified(),
226                           CGM.getContext().getTargetAddressSpace(D.getType()));
227    GV->setVisibility(OldGV->getVisibility());
228
229    // Steal the name of the old global
230    GV->takeName(OldGV);
231
232    // Replace all uses of the old global with the new global
233    llvm::Constant *NewPtrForOldDecl =
234    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
235    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
236
237    // Erase the old global, since it is no longer used.
238    OldGV->eraseFromParent();
239  }
240
241  GV->setInitializer(Init);
242  return GV;
243}
244
245void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
246                                      llvm::GlobalValue::LinkageTypes Linkage) {
247  llvm::Value *&DMEntry = LocalDeclMap[&D];
248  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
249
250  llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
251
252  // Store into LocalDeclMap before generating initializer to handle
253  // circular references.
254  DMEntry = GV;
255
256  // We can't have a VLA here, but we can have a pointer to a VLA,
257  // even though that doesn't really make any sense.
258  // Make sure to evaluate VLA bounds now so that we have them for later.
259  if (D.getType()->isVariablyModifiedType())
260    EmitVLASize(D.getType());
261
262  // Local static block variables must be treated as globals as they may be
263  // referenced in their RHS initializer block-literal expresion.
264  CGM.setStaticLocalDeclAddress(&D, GV);
265
266  // If this value has an initializer, emit it.
267  if (D.getInit())
268    GV = AddInitializerToStaticVarDecl(D, GV);
269
270  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
271
272  // FIXME: Merge attribute handling.
273  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
274    SourceManager &SM = CGM.getContext().getSourceManager();
275    llvm::Constant *Ann =
276      CGM.EmitAnnotateAttr(GV, AA,
277                           SM.getInstantiationLineNumber(D.getLocation()));
278    CGM.AddAnnotation(Ann);
279  }
280
281  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
282    GV->setSection(SA->getName());
283
284  if (D.hasAttr<UsedAttr>())
285    CGM.AddUsedGlobal(GV);
286
287  // We may have to cast the constant because of the initializer
288  // mismatch above.
289  //
290  // FIXME: It is really dangerous to store this in the map; if anyone
291  // RAUW's the GV uses of this constant will be invalid.
292  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
293  const llvm::Type *LPtrTy =
294    LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
295  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
296
297  // Emit global variable debug descriptor for static vars.
298  CGDebugInfo *DI = getDebugInfo();
299  if (DI) {
300    DI->setLocation(D.getLocation());
301    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
302  }
303}
304
305unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
306  assert(ByRefValueInfo.count(VD) && "Did not find value!");
307
308  return ByRefValueInfo.find(VD)->second.second;
309}
310
311llvm::Value *CodeGenFunction::BuildBlockByrefAddress(llvm::Value *BaseAddr,
312                                                     const VarDecl *V) {
313  llvm::Value *Loc = Builder.CreateStructGEP(BaseAddr, 1, "forwarding");
314  Loc = Builder.CreateLoad(Loc);
315  Loc = Builder.CreateStructGEP(Loc, getByRefValueLLVMField(V),
316                                V->getNameAsString());
317  return Loc;
318}
319
320/// BuildByRefType - This routine changes a __block variable declared as T x
321///   into:
322///
323///      struct {
324///        void *__isa;
325///        void *__forwarding;
326///        int32_t __flags;
327///        int32_t __size;
328///        void *__copy_helper;       // only if needed
329///        void *__destroy_helper;    // only if needed
330///        char padding[X];           // only if needed
331///        T x;
332///      } x
333///
334const llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
335  std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
336  if (Info.first)
337    return Info.first;
338
339  QualType Ty = D->getType();
340
341  std::vector<const llvm::Type *> Types;
342
343  llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(getLLVMContext());
344
345  // void *__isa;
346  Types.push_back(Int8PtrTy);
347
348  // void *__forwarding;
349  Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
350
351  // int32_t __flags;
352  Types.push_back(Int32Ty);
353
354  // int32_t __size;
355  Types.push_back(Int32Ty);
356
357  bool HasCopyAndDispose = getContext().BlockRequiresCopying(Ty);
358  if (HasCopyAndDispose) {
359    /// void *__copy_helper;
360    Types.push_back(Int8PtrTy);
361
362    /// void *__destroy_helper;
363    Types.push_back(Int8PtrTy);
364  }
365
366  bool Packed = false;
367  CharUnits Align = getContext().getDeclAlign(D);
368  if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
369    // We have to insert padding.
370
371    // The struct above has 2 32-bit integers.
372    unsigned CurrentOffsetInBytes = 4 * 2;
373
374    // And either 2 or 4 pointers.
375    CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
376      CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
377
378    // Align the offset.
379    unsigned AlignedOffsetInBytes =
380      llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
381
382    unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
383    if (NumPaddingBytes > 0) {
384      const llvm::Type *Ty = llvm::Type::getInt8Ty(getLLVMContext());
385      // FIXME: We need a sema error for alignment larger than the minimum of
386      // the maximal stack alignmint and the alignment of malloc on the system.
387      if (NumPaddingBytes > 1)
388        Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
389
390      Types.push_back(Ty);
391
392      // We want a packed struct.
393      Packed = true;
394    }
395  }
396
397  // T x;
398  Types.push_back(ConvertTypeForMem(Ty));
399
400  const llvm::Type *T = llvm::StructType::get(getLLVMContext(), Types, Packed);
401
402  cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
403  CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
404                              ByRefTypeHolder.get());
405
406  Info.first = ByRefTypeHolder.get();
407
408  Info.second = Types.size() - 1;
409
410  return Info.first;
411}
412
413namespace {
414  struct CallArrayDtor : EHScopeStack::Cleanup {
415    CallArrayDtor(const CXXDestructorDecl *Dtor,
416                  const ConstantArrayType *Type,
417                  llvm::Value *Loc)
418      : Dtor(Dtor), Type(Type), Loc(Loc) {}
419
420    const CXXDestructorDecl *Dtor;
421    const ConstantArrayType *Type;
422    llvm::Value *Loc;
423
424    void Emit(CodeGenFunction &CGF, bool IsForEH) {
425      QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
426      const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
427      BasePtr = llvm::PointerType::getUnqual(BasePtr);
428      llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
429      CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
430    }
431  };
432
433  struct CallVarDtor : EHScopeStack::Cleanup {
434    CallVarDtor(const CXXDestructorDecl *Dtor,
435                llvm::Value *NRVOFlag,
436                llvm::Value *Loc)
437      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
438
439    const CXXDestructorDecl *Dtor;
440    llvm::Value *NRVOFlag;
441    llvm::Value *Loc;
442
443    void Emit(CodeGenFunction &CGF, bool IsForEH) {
444      // Along the exceptions path we always execute the dtor.
445      bool NRVO = !IsForEH && NRVOFlag;
446
447      llvm::BasicBlock *SkipDtorBB = 0;
448      if (NRVO) {
449        // If we exited via NRVO, we skip the destructor call.
450        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
451        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
452        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
453        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
454        CGF.EmitBlock(RunDtorBB);
455      }
456
457      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
458                                /*ForVirtualBase=*/false, Loc);
459
460      if (NRVO) CGF.EmitBlock(SkipDtorBB);
461    }
462  };
463}
464
465namespace {
466  struct CallStackRestore : EHScopeStack::Cleanup {
467    llvm::Value *Stack;
468    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
469    void Emit(CodeGenFunction &CGF, bool IsForEH) {
470      llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
471      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
472      CGF.Builder.CreateCall(F, V);
473    }
474  };
475
476  struct CallCleanupFunction : EHScopeStack::Cleanup {
477    llvm::Constant *CleanupFn;
478    const CGFunctionInfo &FnInfo;
479    const VarDecl &Var;
480
481    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
482                        const VarDecl *Var)
483      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
484
485    void Emit(CodeGenFunction &CGF, bool IsForEH) {
486      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
487                      SourceLocation());
488      // Compute the address of the local variable, in case it's a byref
489      // or something.
490      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
491
492      // In some cases, the type of the function argument will be different from
493      // the type of the pointer. An example of this is
494      // void f(void* arg);
495      // __attribute__((cleanup(f))) void *g;
496      //
497      // To fix this we insert a bitcast here.
498      QualType ArgTy = FnInfo.arg_begin()->type;
499      llvm::Value *Arg =
500        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
501
502      CallArgList Args;
503      Args.push_back(std::make_pair(RValue::get(Arg),
504                            CGF.getContext().getPointerType(Var.getType())));
505      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
506    }
507  };
508
509  struct CallBlockRelease : EHScopeStack::Cleanup {
510    llvm::Value *Addr;
511    CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
512
513    void Emit(CodeGenFunction &CGF, bool IsForEH) {
514      CGF.BuildBlockRelease(Addr, BLOCK_FIELD_IS_BYREF);
515    }
516  };
517}
518
519
520/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
521/// non-zero parts of the specified initializer with equal or fewer than
522/// NumStores scalar stores.
523static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
524                                                unsigned &NumStores) {
525  // Zero and Undef never requires any extra stores.
526  if (isa<llvm::ConstantAggregateZero>(Init) ||
527      isa<llvm::ConstantPointerNull>(Init) ||
528      isa<llvm::UndefValue>(Init))
529    return true;
530  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
531      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
532      isa<llvm::ConstantExpr>(Init))
533    return Init->isNullValue() || NumStores--;
534
535  // See if we can emit each element.
536  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
537    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
538      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
539      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
540        return false;
541    }
542    return true;
543  }
544
545  // Anything else is hard and scary.
546  return false;
547}
548
549/// emitStoresForInitAfterMemset - For inits that
550/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
551/// stores that would be required.
552static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
553                                         bool isVolatile, CGBuilderTy &Builder) {
554  // Zero doesn't require any stores.
555  if (isa<llvm::ConstantAggregateZero>(Init) ||
556      isa<llvm::ConstantPointerNull>(Init) ||
557      isa<llvm::UndefValue>(Init))
558    return;
559
560  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
561      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
562      isa<llvm::ConstantExpr>(Init)) {
563    if (!Init->isNullValue())
564      Builder.CreateStore(Init, Loc, isVolatile);
565    return;
566  }
567
568  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
569         "Unknown value type!");
570
571  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
572    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
573    if (Elt->isNullValue()) continue;
574
575    // Otherwise, get a pointer to the element and emit it.
576    emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
577                                 isVolatile, Builder);
578  }
579}
580
581
582/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
583/// plus some stores to initialize a local variable instead of using a memcpy
584/// from a constant global.  It is beneficial to use memset if the global is all
585/// zeros, or mostly zeros and large.
586static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
587                                                  uint64_t GlobalSize) {
588  // If a global is all zeros, always use a memset.
589  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
590
591
592  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
593  // do it if it will require 6 or fewer scalar stores.
594  // TODO: Should budget depends on the size?  Avoiding a large global warrants
595  // plopping in more stores.
596  unsigned StoreBudget = 6;
597  uint64_t SizeLimit = 32;
598
599  return GlobalSize > SizeLimit &&
600         canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
601}
602
603
604/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
605/// variable declaration with auto, register, or no storage class specifier.
606/// These turn into simple stack objects, or GlobalValues depending on target.
607void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
608  AutoVarEmission emission = EmitAutoVarAlloca(D);
609  EmitAutoVarInit(emission);
610  EmitAutoVarCleanups(emission);
611}
612
613/// EmitAutoVarAlloca - Emit the alloca and debug information for a
614/// local variable.  Does not emit initalization or destruction.
615CodeGenFunction::AutoVarEmission
616CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
617  QualType Ty = D.getType();
618
619  AutoVarEmission emission(D);
620
621  bool isByRef = D.hasAttr<BlocksAttr>();
622  emission.IsByRef = isByRef;
623
624  CharUnits alignment = getContext().getDeclAlign(&D);
625  emission.Alignment = alignment;
626
627  llvm::Value *DeclPtr;
628  if (Ty->isConstantSizeType()) {
629    if (!Target.useGlobalsForAutomaticVariables()) {
630      bool NRVO = getContext().getLangOptions().ElideConstructors &&
631                  D.isNRVOVariable();
632
633      // If this value is a POD array or struct with a statically
634      // determinable constant initializer, there are optimizations we
635      // can do.
636      // TODO: we can potentially constant-evaluate non-POD structs and
637      // arrays as long as the initialization is trivial (e.g. if they
638      // have a non-trivial destructor, but not a non-trivial constructor).
639      if (D.getInit() &&
640          (Ty->isArrayType() || Ty->isRecordType()) && Ty->isPODType() &&
641          D.getInit()->isConstantInitializer(getContext(), false)) {
642
643        // If the variable's a const type, and it's neither an NRVO
644        // candidate nor a __block variable, emit it as a global instead.
645        if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
646            !NRVO && !isByRef) {
647          EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
648
649          emission.Address = 0; // signal this condition to later callbacks
650          assert(emission.wasEmittedAsGlobal());
651          return emission;
652        }
653
654        // Otherwise, tell the initialization code that we're in this case.
655        emission.IsConstantAggregate = true;
656      }
657
658      // A normal fixed sized variable becomes an alloca in the entry block,
659      // unless it's an NRVO variable.
660      const llvm::Type *LTy = ConvertTypeForMem(Ty);
661
662      if (NRVO) {
663        // The named return value optimization: allocate this variable in the
664        // return slot, so that we can elide the copy when returning this
665        // variable (C++0x [class.copy]p34).
666        DeclPtr = ReturnValue;
667
668        if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
669          if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
670            // Create a flag that is used to indicate when the NRVO was applied
671            // to this variable. Set it to zero to indicate that NRVO was not
672            // applied.
673            llvm::Value *Zero = Builder.getFalse();
674            llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
675            EnsureInsertPoint();
676            Builder.CreateStore(Zero, NRVOFlag);
677
678            // Record the NRVO flag for this variable.
679            NRVOFlags[&D] = NRVOFlag;
680            emission.NRVOFlag = NRVOFlag;
681          }
682        }
683      } else {
684        if (isByRef)
685          LTy = BuildByRefType(&D);
686
687        llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
688        Alloc->setName(D.getNameAsString());
689
690        CharUnits allocaAlignment = alignment;
691        if (isByRef)
692          allocaAlignment = std::max(allocaAlignment,
693              getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
694        Alloc->setAlignment(allocaAlignment.getQuantity());
695        DeclPtr = Alloc;
696      }
697    } else {
698      // Targets that don't support recursion emit locals as globals.
699      const char *Class =
700        D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
701      DeclPtr = CreateStaticVarDecl(D, Class,
702                                    llvm::GlobalValue::InternalLinkage);
703    }
704
705    // FIXME: Can this happen?
706    if (Ty->isVariablyModifiedType())
707      EmitVLASize(Ty);
708  } else {
709    EnsureInsertPoint();
710
711    if (!DidCallStackSave) {
712      // Save the stack.
713      llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
714
715      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
716      llvm::Value *V = Builder.CreateCall(F);
717
718      Builder.CreateStore(V, Stack);
719
720      DidCallStackSave = true;
721
722      // Push a cleanup block and restore the stack there.
723      // FIXME: in general circumstances, this should be an EH cleanup.
724      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
725    }
726
727    // Get the element type.
728    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
729    const llvm::Type *LElemPtrTy =
730      LElemTy->getPointerTo(CGM.getContext().getTargetAddressSpace(Ty));
731
732    llvm::Value *VLASize = EmitVLASize(Ty);
733
734    // Allocate memory for the array.
735    llvm::AllocaInst *VLA =
736      Builder.CreateAlloca(llvm::Type::getInt8Ty(getLLVMContext()), VLASize, "vla");
737    VLA->setAlignment(alignment.getQuantity());
738
739    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
740  }
741
742  llvm::Value *&DMEntry = LocalDeclMap[&D];
743  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
744  DMEntry = DeclPtr;
745  emission.Address = DeclPtr;
746
747  // Emit debug info for local var declaration.
748  if (CGDebugInfo *DI = getDebugInfo()) {
749    assert(HaveInsertPoint() && "Unexpected unreachable point!");
750
751    DI->setLocation(D.getLocation());
752    if (Target.useGlobalsForAutomaticVariables()) {
753      DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
754    } else
755      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
756  }
757
758  return emission;
759}
760
761/// Determines whether the given __block variable is potentially
762/// captured by the given expression.
763static bool isCapturedBy(const VarDecl &var, const Expr *e) {
764  // Skip the most common kinds of expressions that make
765  // hierarchy-walking expensive.
766  e = e->IgnoreParenCasts();
767
768  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
769    const BlockDecl *block = be->getBlockDecl();
770    for (BlockDecl::capture_const_iterator i = block->capture_begin(),
771           e = block->capture_end(); i != e; ++i) {
772      if (i->getVariable() == &var)
773        return true;
774    }
775
776    // No need to walk into the subexpressions.
777    return false;
778  }
779
780  for (Stmt::const_child_range children = e->children(); children; ++children)
781    if (isCapturedBy(var, cast<Expr>(*children)))
782      return true;
783
784  return false;
785}
786
787void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
788  assert(emission.Variable && "emission was not valid!");
789
790  // If this was emitted as a global constant, we're done.
791  if (emission.wasEmittedAsGlobal()) return;
792
793  const VarDecl &D = *emission.Variable;
794  QualType type = D.getType();
795
796  // If this local has an initializer, emit it now.
797  const Expr *Init = D.getInit();
798
799  // If we are at an unreachable point, we don't need to emit the initializer
800  // unless it contains a label.
801  if (!HaveInsertPoint()) {
802    if (!Init || !ContainsLabel(Init)) return;
803    EnsureInsertPoint();
804  }
805
806  CharUnits alignment = emission.Alignment;
807
808  if (emission.IsByRef) {
809    llvm::Value *V;
810
811    BlockFieldFlags fieldFlags;
812    bool fieldNeedsCopyDispose = false;
813
814    if (type->isBlockPointerType()) {
815      fieldFlags |= BLOCK_FIELD_IS_BLOCK;
816      fieldNeedsCopyDispose = true;
817    } else if (getContext().isObjCNSObjectType(type) ||
818               type->isObjCObjectPointerType()) {
819      fieldFlags |= BLOCK_FIELD_IS_OBJECT;
820      fieldNeedsCopyDispose = true;
821    } else if (getLangOptions().CPlusPlus) {
822      if (getContext().getBlockVarCopyInits(&D))
823        fieldNeedsCopyDispose = true;
824      else if (const CXXRecordDecl *record = type->getAsCXXRecordDecl())
825        fieldNeedsCopyDispose = !record->hasTrivialDestructor();
826    }
827
828    llvm::Value *addr = emission.Address;
829
830    // FIXME: Someone double check this.
831    if (type.isObjCGCWeak())
832      fieldFlags |= BLOCK_FIELD_IS_WEAK;
833
834    // Initialize the 'isa', which is just 0 or 1.
835    int isa = 0;
836    if (fieldFlags & BLOCK_FIELD_IS_WEAK)
837      isa = 1;
838    V = Builder.CreateIntToPtr(Builder.getInt32(isa), Int8PtrTy, "isa");
839    Builder.CreateStore(V, Builder.CreateStructGEP(addr, 0, "byref.isa"));
840
841    // Store the address of the variable into its own forwarding pointer.
842    Builder.CreateStore(addr,
843                        Builder.CreateStructGEP(addr, 1, "byref.forwarding"));
844
845    // Blocks ABI:
846    //   c) the flags field is set to either 0 if no helper functions are
847    //      needed or BLOCK_HAS_COPY_DISPOSE if they are,
848    BlockFlags flags;
849    if (fieldNeedsCopyDispose) flags |= BLOCK_HAS_COPY_DISPOSE;
850    Builder.CreateStore(llvm::ConstantInt::get(IntTy, flags.getBitMask()),
851                        Builder.CreateStructGEP(addr, 2, "byref.flags"));
852
853    const llvm::Type *V1;
854    V1 = cast<llvm::PointerType>(addr->getType())->getElementType();
855    V = llvm::ConstantInt::get(IntTy, CGM.GetTargetTypeStoreSize(V1).getQuantity());
856    Builder.CreateStore(V, Builder.CreateStructGEP(addr, 3, "byref.size"));
857
858    if (fieldNeedsCopyDispose) {
859      llvm::Value *copy_helper = Builder.CreateStructGEP(addr, 4);
860      Builder.CreateStore(CGM.BuildbyrefCopyHelper(addr->getType(), fieldFlags,
861                                                   alignment.getQuantity(), &D),
862                          copy_helper);
863
864      llvm::Value *destroy_helper = Builder.CreateStructGEP(addr, 5);
865      Builder.CreateStore(CGM.BuildbyrefDestroyHelper(addr->getType(),
866                                                      fieldFlags,
867                                                      alignment.getQuantity(),
868                                                      &D),
869                          destroy_helper);
870    }
871  }
872
873  if (!Init) return;
874
875  // Check whether this is a byref variable that's potentially
876  // captured and moved by its own initializer.  If so, we'll need to
877  // emit the initializer first, then copy into the variable.
878  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
879
880  llvm::Value *Loc =
881    capturedByInit ? emission.Address : emission.getObjectAddress(*this);
882
883  if (!emission.IsConstantAggregate)
884    return EmitExprAsInit(Init, &D, Loc, alignment, capturedByInit);
885
886  // If this is a simple aggregate initialization, we can optimize it
887  // in various ways.
888  assert(!capturedByInit && "constant init contains a capturing block?");
889
890  bool isVolatile = type.isVolatileQualified();
891
892  llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
893  assert(constant != 0 && "Wasn't a simple constant init?");
894
895  llvm::Value *SizeVal =
896    llvm::ConstantInt::get(IntPtrTy,
897                           getContext().getTypeSizeInChars(type).getQuantity());
898
899  const llvm::Type *BP = Int8PtrTy;
900  if (Loc->getType() != BP)
901    Loc = Builder.CreateBitCast(Loc, BP, "tmp");
902
903  // If the initializer is all or mostly zeros, codegen with memset then do
904  // a few stores afterward.
905  if (shouldUseMemSetPlusStoresToInitialize(constant,
906                CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
907    Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
908                         alignment.getQuantity(), isVolatile);
909    if (!constant->isNullValue()) {
910      Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
911      emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
912    }
913  } else {
914    // Otherwise, create a temporary global with the initializer then
915    // memcpy from the global to the alloca.
916    std::string Name = GetStaticDeclName(*this, D, ".");
917    llvm::GlobalVariable *GV =
918      new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
919                               llvm::GlobalValue::InternalLinkage,
920                               constant, Name, 0, false, 0);
921    GV->setAlignment(alignment.getQuantity());
922
923    llvm::Value *SrcPtr = GV;
924    if (SrcPtr->getType() != BP)
925      SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
926
927    Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
928                         isVolatile);
929  }
930}
931
932/// Emit an expression as an initializer for a variable at the given
933/// location.  The expression is not necessarily the normal
934/// initializer for the variable, and the address is not necessarily
935/// its normal location.
936///
937/// \param init the initializing expression
938/// \param var the variable to act as if we're initializing
939/// \param loc the address to initialize; its type is a pointer
940///   to the LLVM mapping of the variable's type
941/// \param alignment the alignment of the address
942/// \param capturedByInit true if the variable is a __block variable
943///   whose address is potentially changed by the initializer
944void CodeGenFunction::EmitExprAsInit(const Expr *init,
945                                     const VarDecl *var,
946                                     llvm::Value *loc,
947                                     CharUnits alignment,
948                                     bool capturedByInit) {
949  QualType type = var->getType();
950  bool isVolatile = type.isVolatileQualified();
951
952  if (type->isReferenceType()) {
953    RValue RV = EmitReferenceBindingToExpr(init, var);
954    if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
955    EmitStoreOfScalar(RV.getScalarVal(), loc, false,
956                      alignment.getQuantity(), type);
957  } else if (!hasAggregateLLVMType(type)) {
958    llvm::Value *V = EmitScalarExpr(init);
959    if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
960    EmitStoreOfScalar(V, loc, isVolatile, alignment.getQuantity(), type);
961  } else if (type->isAnyComplexType()) {
962    ComplexPairTy complex = EmitComplexExpr(init);
963    if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
964    StoreComplexToAddr(complex, loc, isVolatile);
965  } else {
966    // TODO: how can we delay here if D is captured by its initializer?
967    EmitAggExpr(init, AggValueSlot::forAddr(loc, isVolatile, true, false));
968  }
969}
970
971void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
972  assert(emission.Variable && "emission was not valid!");
973
974  // If this was emitted as a global constant, we're done.
975  if (emission.wasEmittedAsGlobal()) return;
976
977  const VarDecl &D = *emission.Variable;
978
979  // Handle C++ destruction of variables.
980  if (getLangOptions().CPlusPlus) {
981    QualType type = D.getType();
982    QualType baseType = getContext().getBaseElementType(type);
983    if (const RecordType *RT = baseType->getAs<RecordType>()) {
984      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
985      if (!ClassDecl->hasTrivialDestructor()) {
986        // Note: We suppress the destructor call when the corresponding NRVO
987        // flag has been set.
988
989        // Note that for __block variables, we want to destroy the
990        // original stack object, not the possible forwarded object.
991        llvm::Value *Loc = emission.getObjectAddress(*this);
992
993        const CXXDestructorDecl *D = ClassDecl->getDestructor();
994        assert(D && "EmitLocalBlockVarDecl - destructor is nul");
995
996        if (type != baseType) {
997          const ConstantArrayType *Array =
998            getContext().getAsConstantArrayType(type);
999          assert(Array && "types changed without array?");
1000          EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
1001                                             D, Array, Loc);
1002        } else {
1003          EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
1004                                           D, emission.NRVOFlag, Loc);
1005        }
1006      }
1007    }
1008  }
1009
1010  // Handle the cleanup attribute.
1011  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1012    const FunctionDecl *FD = CA->getFunctionDecl();
1013
1014    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1015    assert(F && "Could not find function!");
1016
1017    const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
1018    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1019  }
1020
1021  // If this is a block variable, call _Block_object_destroy
1022  // (on the unforwarded address).
1023  if (emission.IsByRef &&
1024      CGM.getLangOptions().getGCMode() != LangOptions::GCOnly)
1025    EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, emission.Address);
1026}
1027
1028/// Emit an alloca (or GlobalValue depending on target)
1029/// for the specified parameter and set up LocalDeclMap.
1030void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1031                                   unsigned ArgNo) {
1032  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1033  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1034         "Invalid argument to EmitParmDecl");
1035
1036  Arg->setName(D.getName());
1037
1038  // Use better IR generation for certain implicit parameters.
1039  if (isa<ImplicitParamDecl>(D)) {
1040    // The only implicit argument a block has is its literal.
1041    if (BlockInfo) {
1042      LocalDeclMap[&D] = Arg;
1043
1044      if (CGDebugInfo *DI = getDebugInfo()) {
1045        DI->setLocation(D.getLocation());
1046        DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1047      }
1048
1049      return;
1050    }
1051  }
1052
1053  QualType Ty = D.getType();
1054
1055  llvm::Value *DeclPtr;
1056  // If this is an aggregate or variable sized value, reuse the input pointer.
1057  if (!Ty->isConstantSizeType() ||
1058      CodeGenFunction::hasAggregateLLVMType(Ty)) {
1059    DeclPtr = Arg;
1060  } else {
1061    // Otherwise, create a temporary to hold the value.
1062    DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
1063
1064    // Store the initial value into the alloca.
1065    EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(),
1066                      getContext().getDeclAlign(&D).getQuantity(), Ty,
1067                      CGM.getTBAAInfo(Ty));
1068  }
1069
1070  llvm::Value *&DMEntry = LocalDeclMap[&D];
1071  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1072  DMEntry = DeclPtr;
1073
1074  // Emit debug info for param declaration.
1075  if (CGDebugInfo *DI = getDebugInfo()) {
1076    DI->setLocation(D.getLocation());
1077    DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1078  }
1079}
1080