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 "CGOpenCLRuntime.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::TypeAliasTemplate:
56  case Decl::TemplateTemplateParm:
57  case Decl::ObjCMethod:
58  case Decl::ObjCCategory:
59  case Decl::ObjCProtocol:
60  case Decl::ObjCInterface:
61  case Decl::ObjCCategoryImpl:
62  case Decl::ObjCImplementation:
63  case Decl::ObjCProperty:
64  case Decl::ObjCCompatibleAlias:
65  case Decl::AccessSpec:
66  case Decl::LinkageSpec:
67  case Decl::ObjCPropertyImpl:
68  case Decl::FileScopeAsm:
69  case Decl::Friend:
70  case Decl::FriendTemplate:
71  case Decl::Block:
72  case Decl::ClassScopeFunctionSpecialization:
73    llvm_unreachable("Declaration 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  case Decl::Import:
86    // None of these decls require codegen support.
87    return;
88
89  case Decl::Var: {
90    const VarDecl &VD = cast<VarDecl>(D);
91    assert(VD.isLocalVarDecl() &&
92           "Should not see file-scope variables inside a function!");
93    return EmitVarDecl(VD);
94  }
95
96  case Decl::Typedef:      // typedef int X;
97  case Decl::TypeAlias: {  // using X = int; [C++0x]
98    const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
99    QualType Ty = TD.getUnderlyingType();
100
101    if (Ty->isVariablyModifiedType())
102      EmitVariablyModifiedType(Ty);
103  }
104  }
105}
106
107/// EmitVarDecl - This method handles emission of any variable declaration
108/// inside a function, including static vars etc.
109void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
110  switch (D.getStorageClass()) {
111  case SC_None:
112  case SC_Auto:
113  case SC_Register:
114    return EmitAutoVarDecl(D);
115  case SC_Static: {
116    llvm::GlobalValue::LinkageTypes Linkage =
117      llvm::GlobalValue::InternalLinkage;
118
119    // If the function definition has some sort of weak linkage, its
120    // static variables should also be weak so that they get properly
121    // uniqued.  We can't do this in C, though, because there's no
122    // standard way to agree on which variables are the same (i.e.
123    // there's no mangling).
124    if (getContext().getLangOpts().CPlusPlus)
125      if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126        Linkage = CurFn->getLinkage();
127
128    return EmitStaticVarDecl(D, Linkage);
129  }
130  case SC_Extern:
131  case SC_PrivateExtern:
132    // Don't emit it now, allow it to be emitted lazily on its first use.
133    return;
134  case SC_OpenCLWorkGroupLocal:
135    return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
136  }
137
138  llvm_unreachable("Unknown storage class");
139}
140
141static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
142                                     const char *Separator) {
143  CodeGenModule &CGM = CGF.CGM;
144  if (CGF.getContext().getLangOpts().CPlusPlus) {
145    StringRef Name = CGM.getMangledName(&D);
146    return Name.str();
147  }
148
149  std::string ContextName;
150  if (!CGF.CurFuncDecl) {
151    // Better be in a block declared in global scope.
152    const NamedDecl *ND = cast<NamedDecl>(&D);
153    const DeclContext *DC = ND->getDeclContext();
154    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
155      MangleBuffer Name;
156      CGM.getBlockMangledName(GlobalDecl(), Name, BD);
157      ContextName = Name.getString();
158    }
159    else
160      llvm_unreachable("Unknown context for block static var decl");
161  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
162    StringRef Name = CGM.getMangledName(FD);
163    ContextName = Name.str();
164  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
165    ContextName = CGF.CurFn->getName();
166  else
167    llvm_unreachable("Unknown context for static var decl");
168
169  return ContextName + Separator + D.getNameAsString();
170}
171
172llvm::GlobalVariable *
173CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
174                                     const char *Separator,
175                                     llvm::GlobalValue::LinkageTypes Linkage) {
176  QualType Ty = D.getType();
177  assert(Ty->isConstantSizeType() && "VLAs can't be static");
178
179  // Use the label if the variable is renamed with the asm-label extension.
180  std::string Name;
181  if (D.hasAttr<AsmLabelAttr>())
182    Name = CGM.getMangledName(&D);
183  else
184    Name = GetStaticDeclName(*this, D, Separator);
185
186  llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
187  unsigned AddrSpace =
188   CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
189  llvm::GlobalVariable *GV =
190    new llvm::GlobalVariable(CGM.getModule(), LTy,
191                             Ty.isConstant(getContext()), Linkage,
192                             CGM.EmitNullConstant(D.getType()), Name, 0,
193                             llvm::GlobalVariable::NotThreadLocal,
194                             AddrSpace);
195  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
196  if (Linkage != llvm::GlobalValue::InternalLinkage)
197    GV->setVisibility(CurFn->getVisibility());
198
199  if (D.isThreadSpecified())
200    CGM.setTLSMode(GV, D);
201
202  return GV;
203}
204
205/// hasNontrivialDestruction - Determine whether a type's destruction is
206/// non-trivial. If so, and the variable uses static initialization, we must
207/// register its destructor to run on exit.
208static bool hasNontrivialDestruction(QualType T) {
209  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
210  return RD && !RD->hasTrivialDestructor();
211}
212
213/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
214/// global variable that has already been created for it.  If the initializer
215/// has a different type than GV does, this may free GV and return a different
216/// one.  Otherwise it just returns GV.
217llvm::GlobalVariable *
218CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
219                                               llvm::GlobalVariable *GV) {
220  llvm::Constant *Init = CGM.EmitConstantInit(D, this);
221
222  // If constant emission failed, then this should be a C++ static
223  // initializer.
224  if (!Init) {
225    if (!getContext().getLangOpts().CPlusPlus)
226      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
227    else if (Builder.GetInsertBlock()) {
228      // Since we have a static initializer, this global variable can't
229      // be constant.
230      GV->setConstant(false);
231
232      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
233    }
234    return GV;
235  }
236
237  // The initializer may differ in type from the global. Rewrite
238  // the global to match the initializer.  (We have to do this
239  // because some types, like unions, can't be completely represented
240  // in the LLVM type system.)
241  if (GV->getType()->getElementType() != Init->getType()) {
242    llvm::GlobalVariable *OldGV = GV;
243
244    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
245                                  OldGV->isConstant(),
246                                  OldGV->getLinkage(), Init, "",
247                                  /*InsertBefore*/ OldGV,
248                                  OldGV->getThreadLocalMode(),
249                           CGM.getContext().getTargetAddressSpace(D.getType()));
250    GV->setVisibility(OldGV->getVisibility());
251
252    // Steal the name of the old global
253    GV->takeName(OldGV);
254
255    // Replace all uses of the old global with the new global
256    llvm::Constant *NewPtrForOldDecl =
257    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
258    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
259
260    // Erase the old global, since it is no longer used.
261    OldGV->eraseFromParent();
262  }
263
264  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
265  GV->setInitializer(Init);
266
267  if (hasNontrivialDestruction(D.getType())) {
268    // We have a constant initializer, but a nontrivial destructor. We still
269    // need to perform a guarded "initialization" in order to register the
270    // destructor.
271    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
272  }
273
274  return GV;
275}
276
277void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
278                                      llvm::GlobalValue::LinkageTypes Linkage) {
279  llvm::Value *&DMEntry = LocalDeclMap[&D];
280  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
281
282  // Check to see if we already have a global variable for this
283  // declaration.  This can happen when double-emitting function
284  // bodies, e.g. with complete and base constructors.
285  llvm::Constant *addr =
286    CGM.getStaticLocalDeclAddress(&D);
287
288  llvm::GlobalVariable *var;
289  if (addr) {
290    var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
291  } else {
292    addr = var = CreateStaticVarDecl(D, ".", Linkage);
293  }
294
295  // Store into LocalDeclMap before generating initializer to handle
296  // circular references.
297  DMEntry = addr;
298  CGM.setStaticLocalDeclAddress(&D, addr);
299
300  // We can't have a VLA here, but we can have a pointer to a VLA,
301  // even though that doesn't really make any sense.
302  // Make sure to evaluate VLA bounds now so that we have them for later.
303  if (D.getType()->isVariablyModifiedType())
304    EmitVariablyModifiedType(D.getType());
305
306  // Save the type in case adding the initializer forces a type change.
307  llvm::Type *expectedType = addr->getType();
308
309  // If this value has an initializer, emit it.
310  if (D.getInit())
311    var = AddInitializerToStaticVarDecl(D, var);
312
313  var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
314
315  if (D.hasAttr<AnnotateAttr>())
316    CGM.AddGlobalAnnotations(&D, var);
317
318  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
319    var->setSection(SA->getName());
320
321  if (D.hasAttr<UsedAttr>())
322    CGM.AddUsedGlobal(var);
323
324  // We may have to cast the constant because of the initializer
325  // mismatch above.
326  //
327  // FIXME: It is really dangerous to store this in the map; if anyone
328  // RAUW's the GV uses of this constant will be invalid.
329  llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
330  DMEntry = castedAddr;
331  CGM.setStaticLocalDeclAddress(&D, castedAddr);
332
333  // Emit global variable debug descriptor for static vars.
334  CGDebugInfo *DI = getDebugInfo();
335  if (DI &&
336      CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
337    DI->setLocation(D.getLocation());
338    DI->EmitGlobalVariable(var, &D);
339  }
340}
341
342namespace {
343  struct DestroyObject : EHScopeStack::Cleanup {
344    DestroyObject(llvm::Value *addr, QualType type,
345                  CodeGenFunction::Destroyer *destroyer,
346                  bool useEHCleanupForArray)
347      : addr(addr), type(type), destroyer(destroyer),
348        useEHCleanupForArray(useEHCleanupForArray) {}
349
350    llvm::Value *addr;
351    QualType type;
352    CodeGenFunction::Destroyer *destroyer;
353    bool useEHCleanupForArray;
354
355    void Emit(CodeGenFunction &CGF, Flags flags) {
356      // Don't use an EH cleanup recursively from an EH cleanup.
357      bool useEHCleanupForArray =
358        flags.isForNormalCleanup() && this->useEHCleanupForArray;
359
360      CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
361    }
362  };
363
364  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
365    DestroyNRVOVariable(llvm::Value *addr,
366                        const CXXDestructorDecl *Dtor,
367                        llvm::Value *NRVOFlag)
368      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
369
370    const CXXDestructorDecl *Dtor;
371    llvm::Value *NRVOFlag;
372    llvm::Value *Loc;
373
374    void Emit(CodeGenFunction &CGF, Flags flags) {
375      // Along the exceptions path we always execute the dtor.
376      bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
377
378      llvm::BasicBlock *SkipDtorBB = 0;
379      if (NRVO) {
380        // If we exited via NRVO, we skip the destructor call.
381        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
382        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
383        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
384        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
385        CGF.EmitBlock(RunDtorBB);
386      }
387
388      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
389                                /*ForVirtualBase=*/false, Loc);
390
391      if (NRVO) CGF.EmitBlock(SkipDtorBB);
392    }
393  };
394
395  struct CallStackRestore : EHScopeStack::Cleanup {
396    llvm::Value *Stack;
397    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
398    void Emit(CodeGenFunction &CGF, Flags flags) {
399      llvm::Value *V = CGF.Builder.CreateLoad(Stack);
400      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
401      CGF.Builder.CreateCall(F, V);
402    }
403  };
404
405  struct ExtendGCLifetime : EHScopeStack::Cleanup {
406    const VarDecl &Var;
407    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
408
409    void Emit(CodeGenFunction &CGF, Flags flags) {
410      // Compute the address of the local variable, in case it's a
411      // byref or something.
412      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
413                      Var.getType(), VK_LValue, SourceLocation());
414      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
415      CGF.EmitExtendGCLifetime(value);
416    }
417  };
418
419  struct CallCleanupFunction : EHScopeStack::Cleanup {
420    llvm::Constant *CleanupFn;
421    const CGFunctionInfo &FnInfo;
422    const VarDecl &Var;
423
424    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
425                        const VarDecl *Var)
426      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
427
428    void Emit(CodeGenFunction &CGF, Flags flags) {
429      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
430                      Var.getType(), VK_LValue, SourceLocation());
431      // Compute the address of the local variable, in case it's a byref
432      // or something.
433      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
434
435      // In some cases, the type of the function argument will be different from
436      // the type of the pointer. An example of this is
437      // void f(void* arg);
438      // __attribute__((cleanup(f))) void *g;
439      //
440      // To fix this we insert a bitcast here.
441      QualType ArgTy = FnInfo.arg_begin()->type;
442      llvm::Value *Arg =
443        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
444
445      CallArgList Args;
446      Args.add(RValue::get(Arg),
447               CGF.getContext().getPointerType(Var.getType()));
448      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
449    }
450  };
451}
452
453/// EmitAutoVarWithLifetime - Does the setup required for an automatic
454/// variable with lifetime.
455static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
456                                    llvm::Value *addr,
457                                    Qualifiers::ObjCLifetime lifetime) {
458  switch (lifetime) {
459  case Qualifiers::OCL_None:
460    llvm_unreachable("present but none");
461
462  case Qualifiers::OCL_ExplicitNone:
463    // nothing to do
464    break;
465
466  case Qualifiers::OCL_Strong: {
467    CodeGenFunction::Destroyer *destroyer =
468      (var.hasAttr<ObjCPreciseLifetimeAttr>()
469       ? CodeGenFunction::destroyARCStrongPrecise
470       : CodeGenFunction::destroyARCStrongImprecise);
471
472    CleanupKind cleanupKind = CGF.getARCCleanupKind();
473    CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
474                    cleanupKind & EHCleanup);
475    break;
476  }
477  case Qualifiers::OCL_Autoreleasing:
478    // nothing to do
479    break;
480
481  case Qualifiers::OCL_Weak:
482    // __weak objects always get EH cleanups; otherwise, exceptions
483    // could cause really nasty crashes instead of mere leaks.
484    CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
485                    CodeGenFunction::destroyARCWeak,
486                    /*useEHCleanup*/ true);
487    break;
488  }
489}
490
491static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
492  if (const Expr *e = dyn_cast<Expr>(s)) {
493    // Skip the most common kinds of expressions that make
494    // hierarchy-walking expensive.
495    s = e = e->IgnoreParenCasts();
496
497    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
498      return (ref->getDecl() == &var);
499    if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
500      const BlockDecl *block = be->getBlockDecl();
501      for (BlockDecl::capture_const_iterator i = block->capture_begin(),
502           e = block->capture_end(); i != e; ++i) {
503        if (i->getVariable() == &var)
504          return true;
505      }
506    }
507  }
508
509  for (Stmt::const_child_range children = s->children(); children; ++children)
510    // children might be null; as in missing decl or conditional of an if-stmt.
511    if ((*children) && isAccessedBy(var, *children))
512      return true;
513
514  return false;
515}
516
517static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
518  if (!decl) return false;
519  if (!isa<VarDecl>(decl)) return false;
520  const VarDecl *var = cast<VarDecl>(decl);
521  return isAccessedBy(*var, e);
522}
523
524static void drillIntoBlockVariable(CodeGenFunction &CGF,
525                                   LValue &lvalue,
526                                   const VarDecl *var) {
527  lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
528}
529
530void CodeGenFunction::EmitScalarInit(const Expr *init,
531                                     const ValueDecl *D,
532                                     LValue lvalue,
533                                     bool capturedByInit) {
534  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
535  if (!lifetime) {
536    llvm::Value *value = EmitScalarExpr(init);
537    if (capturedByInit)
538      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
539    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
540    return;
541  }
542
543  // If we're emitting a value with lifetime, we have to do the
544  // initialization *before* we leave the cleanup scopes.
545  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
546    enterFullExpression(ewc);
547    init = ewc->getSubExpr();
548  }
549  CodeGenFunction::RunCleanupsScope Scope(*this);
550
551  // We have to maintain the illusion that the variable is
552  // zero-initialized.  If the variable might be accessed in its
553  // initializer, zero-initialize before running the initializer, then
554  // actually perform the initialization with an assign.
555  bool accessedByInit = false;
556  if (lifetime != Qualifiers::OCL_ExplicitNone)
557    accessedByInit = (capturedByInit || isAccessedBy(D, init));
558  if (accessedByInit) {
559    LValue tempLV = lvalue;
560    // Drill down to the __block object if necessary.
561    if (capturedByInit) {
562      // We can use a simple GEP for this because it can't have been
563      // moved yet.
564      tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
565                                   getByRefValueLLVMField(cast<VarDecl>(D))));
566    }
567
568    llvm::PointerType *ty
569      = cast<llvm::PointerType>(tempLV.getAddress()->getType());
570    ty = cast<llvm::PointerType>(ty->getElementType());
571
572    llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
573
574    // If __weak, we want to use a barrier under certain conditions.
575    if (lifetime == Qualifiers::OCL_Weak)
576      EmitARCInitWeak(tempLV.getAddress(), zero);
577
578    // Otherwise just do a simple store.
579    else
580      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
581  }
582
583  // Emit the initializer.
584  llvm::Value *value = 0;
585
586  switch (lifetime) {
587  case Qualifiers::OCL_None:
588    llvm_unreachable("present but none");
589
590  case Qualifiers::OCL_ExplicitNone:
591    // nothing to do
592    value = EmitScalarExpr(init);
593    break;
594
595  case Qualifiers::OCL_Strong: {
596    value = EmitARCRetainScalarExpr(init);
597    break;
598  }
599
600  case Qualifiers::OCL_Weak: {
601    // No way to optimize a producing initializer into this.  It's not
602    // worth optimizing for, because the value will immediately
603    // disappear in the common case.
604    value = EmitScalarExpr(init);
605
606    if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
607    if (accessedByInit)
608      EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
609    else
610      EmitARCInitWeak(lvalue.getAddress(), value);
611    return;
612  }
613
614  case Qualifiers::OCL_Autoreleasing:
615    value = EmitARCRetainAutoreleaseScalarExpr(init);
616    break;
617  }
618
619  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
620
621  // If the variable might have been accessed by its initializer, we
622  // might have to initialize with a barrier.  We have to do this for
623  // both __weak and __strong, but __weak got filtered out above.
624  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
625    llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
626    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
627    EmitARCRelease(oldValue, /*precise*/ false);
628    return;
629  }
630
631  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
632}
633
634/// EmitScalarInit - Initialize the given lvalue with the given object.
635void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
636  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
637  if (!lifetime)
638    return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
639
640  switch (lifetime) {
641  case Qualifiers::OCL_None:
642    llvm_unreachable("present but none");
643
644  case Qualifiers::OCL_ExplicitNone:
645    // nothing to do
646    break;
647
648  case Qualifiers::OCL_Strong:
649    init = EmitARCRetain(lvalue.getType(), init);
650    break;
651
652  case Qualifiers::OCL_Weak:
653    // Initialize and then skip the primitive store.
654    EmitARCInitWeak(lvalue.getAddress(), init);
655    return;
656
657  case Qualifiers::OCL_Autoreleasing:
658    init = EmitARCRetainAutorelease(lvalue.getType(), init);
659    break;
660  }
661
662  EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
663}
664
665/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
666/// non-zero parts of the specified initializer with equal or fewer than
667/// NumStores scalar stores.
668static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
669                                                unsigned &NumStores) {
670  // Zero and Undef never requires any extra stores.
671  if (isa<llvm::ConstantAggregateZero>(Init) ||
672      isa<llvm::ConstantPointerNull>(Init) ||
673      isa<llvm::UndefValue>(Init))
674    return true;
675  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
676      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
677      isa<llvm::ConstantExpr>(Init))
678    return Init->isNullValue() || NumStores--;
679
680  // See if we can emit each element.
681  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
682    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
683      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
684      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
685        return false;
686    }
687    return true;
688  }
689
690  if (llvm::ConstantDataSequential *CDS =
691        dyn_cast<llvm::ConstantDataSequential>(Init)) {
692    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
693      llvm::Constant *Elt = CDS->getElementAsConstant(i);
694      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
695        return false;
696    }
697    return true;
698  }
699
700  // Anything else is hard and scary.
701  return false;
702}
703
704/// emitStoresForInitAfterMemset - For inits that
705/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
706/// stores that would be required.
707static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
708                                         bool isVolatile, CGBuilderTy &Builder) {
709  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
710         "called emitStoresForInitAfterMemset for zero or undef value.");
711
712  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
713      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
714      isa<llvm::ConstantExpr>(Init)) {
715    Builder.CreateStore(Init, Loc, isVolatile);
716    return;
717  }
718
719  if (llvm::ConstantDataSequential *CDS =
720        dyn_cast<llvm::ConstantDataSequential>(Init)) {
721    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
722      llvm::Constant *Elt = CDS->getElementAsConstant(i);
723
724      // If necessary, get a pointer to the element and emit it.
725      if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
726        emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
727                                     isVolatile, Builder);
728    }
729    return;
730  }
731
732  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
733         "Unknown value type!");
734
735  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
736    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
737
738    // If necessary, get a pointer to the element and emit it.
739    if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
740      emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
741                                   isVolatile, Builder);
742  }
743}
744
745
746/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
747/// plus some stores to initialize a local variable instead of using a memcpy
748/// from a constant global.  It is beneficial to use memset if the global is all
749/// zeros, or mostly zeros and large.
750static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
751                                                  uint64_t GlobalSize) {
752  // If a global is all zeros, always use a memset.
753  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
754
755
756  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
757  // do it if it will require 6 or fewer scalar stores.
758  // TODO: Should budget depends on the size?  Avoiding a large global warrants
759  // plopping in more stores.
760  unsigned StoreBudget = 6;
761  uint64_t SizeLimit = 32;
762
763  return GlobalSize > SizeLimit &&
764         canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
765}
766
767
768/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
769/// variable declaration with auto, register, or no storage class specifier.
770/// These turn into simple stack objects, or GlobalValues depending on target.
771void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
772  AutoVarEmission emission = EmitAutoVarAlloca(D);
773  EmitAutoVarInit(emission);
774  EmitAutoVarCleanups(emission);
775}
776
777/// EmitAutoVarAlloca - Emit the alloca and debug information for a
778/// local variable.  Does not emit initalization or destruction.
779CodeGenFunction::AutoVarEmission
780CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
781  QualType Ty = D.getType();
782
783  AutoVarEmission emission(D);
784
785  bool isByRef = D.hasAttr<BlocksAttr>();
786  emission.IsByRef = isByRef;
787
788  CharUnits alignment = getContext().getDeclAlign(&D);
789  emission.Alignment = alignment;
790
791  // If the type is variably-modified, emit all the VLA sizes for it.
792  if (Ty->isVariablyModifiedType())
793    EmitVariablyModifiedType(Ty);
794
795  llvm::Value *DeclPtr;
796  if (Ty->isConstantSizeType()) {
797    if (!Target.useGlobalsForAutomaticVariables()) {
798      bool NRVO = getContext().getLangOpts().ElideConstructors &&
799                  D.isNRVOVariable();
800
801      // If this value is a POD array or struct with a statically
802      // determinable constant initializer, there are optimizations we can do.
803      //
804      // TODO: We should constant-evaluate the initializer of any variable,
805      // as long as it is initialized by a constant expression. Currently,
806      // isConstantInitializer produces wrong answers for structs with
807      // reference or bitfield members, and a few other cases, and checking
808      // for POD-ness protects us from some of these.
809      if (D.getInit() &&
810          (Ty->isArrayType() || Ty->isRecordType()) &&
811          (Ty.isPODType(getContext()) ||
812           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
813          D.getInit()->isConstantInitializer(getContext(), false)) {
814
815        // If the variable's a const type, and it's neither an NRVO
816        // candidate nor a __block variable and has no mutable members,
817        // emit it as a global instead.
818        if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
819            CGM.isTypeConstant(Ty, true)) {
820          EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
821
822          emission.Address = 0; // signal this condition to later callbacks
823          assert(emission.wasEmittedAsGlobal());
824          return emission;
825        }
826
827        // Otherwise, tell the initialization code that we're in this case.
828        emission.IsConstantAggregate = true;
829      }
830
831      // A normal fixed sized variable becomes an alloca in the entry block,
832      // unless it's an NRVO variable.
833      llvm::Type *LTy = ConvertTypeForMem(Ty);
834
835      if (NRVO) {
836        // The named return value optimization: allocate this variable in the
837        // return slot, so that we can elide the copy when returning this
838        // variable (C++0x [class.copy]p34).
839        DeclPtr = ReturnValue;
840
841        if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
842          if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
843            // Create a flag that is used to indicate when the NRVO was applied
844            // to this variable. Set it to zero to indicate that NRVO was not
845            // applied.
846            llvm::Value *Zero = Builder.getFalse();
847            llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
848            EnsureInsertPoint();
849            Builder.CreateStore(Zero, NRVOFlag);
850
851            // Record the NRVO flag for this variable.
852            NRVOFlags[&D] = NRVOFlag;
853            emission.NRVOFlag = NRVOFlag;
854          }
855        }
856      } else {
857        if (isByRef)
858          LTy = BuildByRefType(&D);
859
860        llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
861        Alloc->setName(D.getName());
862
863        CharUnits allocaAlignment = alignment;
864        if (isByRef)
865          allocaAlignment = std::max(allocaAlignment,
866              getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
867        Alloc->setAlignment(allocaAlignment.getQuantity());
868        DeclPtr = Alloc;
869      }
870    } else {
871      // Targets that don't support recursion emit locals as globals.
872      const char *Class =
873        D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
874      DeclPtr = CreateStaticVarDecl(D, Class,
875                                    llvm::GlobalValue::InternalLinkage);
876    }
877  } else {
878    EnsureInsertPoint();
879
880    if (!DidCallStackSave) {
881      // Save the stack.
882      llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
883
884      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
885      llvm::Value *V = Builder.CreateCall(F);
886
887      Builder.CreateStore(V, Stack);
888
889      DidCallStackSave = true;
890
891      // Push a cleanup block and restore the stack there.
892      // FIXME: in general circumstances, this should be an EH cleanup.
893      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
894    }
895
896    llvm::Value *elementCount;
897    QualType elementType;
898    llvm::tie(elementCount, elementType) = getVLASize(Ty);
899
900    llvm::Type *llvmTy = ConvertTypeForMem(elementType);
901
902    // Allocate memory for the array.
903    llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
904    vla->setAlignment(alignment.getQuantity());
905
906    DeclPtr = vla;
907  }
908
909  llvm::Value *&DMEntry = LocalDeclMap[&D];
910  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
911  DMEntry = DeclPtr;
912  emission.Address = DeclPtr;
913
914  // Emit debug info for local var declaration.
915  if (HaveInsertPoint())
916    if (CGDebugInfo *DI = getDebugInfo()) {
917      if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
918        DI->setLocation(D.getLocation());
919        if (Target.useGlobalsForAutomaticVariables()) {
920          DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr),
921                                 &D);
922        } else
923          DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
924      }
925    }
926
927  if (D.hasAttr<AnnotateAttr>())
928      EmitVarAnnotations(&D, emission.Address);
929
930  return emission;
931}
932
933/// Determines whether the given __block variable is potentially
934/// captured by the given expression.
935static bool isCapturedBy(const VarDecl &var, const Expr *e) {
936  // Skip the most common kinds of expressions that make
937  // hierarchy-walking expensive.
938  e = e->IgnoreParenCasts();
939
940  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
941    const BlockDecl *block = be->getBlockDecl();
942    for (BlockDecl::capture_const_iterator i = block->capture_begin(),
943           e = block->capture_end(); i != e; ++i) {
944      if (i->getVariable() == &var)
945        return true;
946    }
947
948    // No need to walk into the subexpressions.
949    return false;
950  }
951
952  if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
953    const CompoundStmt *CS = SE->getSubStmt();
954    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
955	   BE = CS->body_end(); BI != BE; ++BI)
956      if (Expr *E = dyn_cast<Expr>((*BI))) {
957        if (isCapturedBy(var, E))
958            return true;
959      }
960      else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
961          // special case declarations
962          for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
963               I != E; ++I) {
964              if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
965                Expr *Init = VD->getInit();
966                if (Init && isCapturedBy(var, Init))
967                  return true;
968              }
969          }
970      }
971      else
972        // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
973        // Later, provide code to poke into statements for capture analysis.
974        return true;
975    return false;
976  }
977
978  for (Stmt::const_child_range children = e->children(); children; ++children)
979    if (isCapturedBy(var, cast<Expr>(*children)))
980      return true;
981
982  return false;
983}
984
985/// \brief Determine whether the given initializer is trivial in the sense
986/// that it requires no code to be generated.
987static bool isTrivialInitializer(const Expr *Init) {
988  if (!Init)
989    return true;
990
991  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
992    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
993      if (Constructor->isTrivial() &&
994          Constructor->isDefaultConstructor() &&
995          !Construct->requiresZeroInitialization())
996        return true;
997
998  return false;
999}
1000void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1001  assert(emission.Variable && "emission was not valid!");
1002
1003  // If this was emitted as a global constant, we're done.
1004  if (emission.wasEmittedAsGlobal()) return;
1005
1006  const VarDecl &D = *emission.Variable;
1007  QualType type = D.getType();
1008
1009  // If this local has an initializer, emit it now.
1010  const Expr *Init = D.getInit();
1011
1012  // If we are at an unreachable point, we don't need to emit the initializer
1013  // unless it contains a label.
1014  if (!HaveInsertPoint()) {
1015    if (!Init || !ContainsLabel(Init)) return;
1016    EnsureInsertPoint();
1017  }
1018
1019  // Initialize the structure of a __block variable.
1020  if (emission.IsByRef)
1021    emitByrefStructureInit(emission);
1022
1023  if (isTrivialInitializer(Init))
1024    return;
1025
1026  CharUnits alignment = emission.Alignment;
1027
1028  // Check whether this is a byref variable that's potentially
1029  // captured and moved by its own initializer.  If so, we'll need to
1030  // emit the initializer first, then copy into the variable.
1031  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1032
1033  llvm::Value *Loc =
1034    capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1035
1036  llvm::Constant *constant = 0;
1037  if (emission.IsConstantAggregate) {
1038    assert(!capturedByInit && "constant init contains a capturing block?");
1039    constant = CGM.EmitConstantInit(D, this);
1040  }
1041
1042  if (!constant) {
1043    LValue lv = MakeAddrLValue(Loc, type, alignment);
1044    lv.setNonGC(true);
1045    return EmitExprAsInit(Init, &D, lv, capturedByInit);
1046  }
1047
1048  // If this is a simple aggregate initialization, we can optimize it
1049  // in various ways.
1050  bool isVolatile = type.isVolatileQualified();
1051
1052  llvm::Value *SizeVal =
1053    llvm::ConstantInt::get(IntPtrTy,
1054                           getContext().getTypeSizeInChars(type).getQuantity());
1055
1056  llvm::Type *BP = Int8PtrTy;
1057  if (Loc->getType() != BP)
1058    Loc = Builder.CreateBitCast(Loc, BP);
1059
1060  // If the initializer is all or mostly zeros, codegen with memset then do
1061  // a few stores afterward.
1062  if (shouldUseMemSetPlusStoresToInitialize(constant,
1063                CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
1064    Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1065                         alignment.getQuantity(), isVolatile);
1066    // Zero and undef don't require a stores.
1067    if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1068      Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1069      emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1070    }
1071  } else {
1072    // Otherwise, create a temporary global with the initializer then
1073    // memcpy from the global to the alloca.
1074    std::string Name = GetStaticDeclName(*this, D, ".");
1075    llvm::GlobalVariable *GV =
1076      new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1077                               llvm::GlobalValue::PrivateLinkage,
1078                               constant, Name);
1079    GV->setAlignment(alignment.getQuantity());
1080    GV->setUnnamedAddr(true);
1081
1082    llvm::Value *SrcPtr = GV;
1083    if (SrcPtr->getType() != BP)
1084      SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1085
1086    Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1087                         isVolatile);
1088  }
1089}
1090
1091/// Emit an expression as an initializer for a variable at the given
1092/// location.  The expression is not necessarily the normal
1093/// initializer for the variable, and the address is not necessarily
1094/// its normal location.
1095///
1096/// \param init the initializing expression
1097/// \param var the variable to act as if we're initializing
1098/// \param loc the address to initialize; its type is a pointer
1099///   to the LLVM mapping of the variable's type
1100/// \param alignment the alignment of the address
1101/// \param capturedByInit true if the variable is a __block variable
1102///   whose address is potentially changed by the initializer
1103void CodeGenFunction::EmitExprAsInit(const Expr *init,
1104                                     const ValueDecl *D,
1105                                     LValue lvalue,
1106                                     bool capturedByInit) {
1107  QualType type = D->getType();
1108
1109  if (type->isReferenceType()) {
1110    RValue rvalue = EmitReferenceBindingToExpr(init, D);
1111    if (capturedByInit)
1112      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1113    EmitStoreThroughLValue(rvalue, lvalue, true);
1114  } else if (!hasAggregateLLVMType(type)) {
1115    EmitScalarInit(init, D, lvalue, capturedByInit);
1116  } else if (type->isAnyComplexType()) {
1117    ComplexPairTy complex = EmitComplexExpr(init);
1118    if (capturedByInit)
1119      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1120    StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
1121  } else {
1122    // TODO: how can we delay here if D is captured by its initializer?
1123    EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1124                                              AggValueSlot::IsDestructed,
1125                                         AggValueSlot::DoesNotNeedGCBarriers,
1126                                              AggValueSlot::IsNotAliased));
1127    MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
1128  }
1129}
1130
1131/// Enter a destroy cleanup for the given local variable.
1132void CodeGenFunction::emitAutoVarTypeCleanup(
1133                            const CodeGenFunction::AutoVarEmission &emission,
1134                            QualType::DestructionKind dtorKind) {
1135  assert(dtorKind != QualType::DK_none);
1136
1137  // Note that for __block variables, we want to destroy the
1138  // original stack object, not the possibly forwarded object.
1139  llvm::Value *addr = emission.getObjectAddress(*this);
1140
1141  const VarDecl *var = emission.Variable;
1142  QualType type = var->getType();
1143
1144  CleanupKind cleanupKind = NormalAndEHCleanup;
1145  CodeGenFunction::Destroyer *destroyer = 0;
1146
1147  switch (dtorKind) {
1148  case QualType::DK_none:
1149    llvm_unreachable("no cleanup for trivially-destructible variable");
1150
1151  case QualType::DK_cxx_destructor:
1152    // If there's an NRVO flag on the emission, we need a different
1153    // cleanup.
1154    if (emission.NRVOFlag) {
1155      assert(!type->isArrayType());
1156      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1157      EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1158                                               emission.NRVOFlag);
1159      return;
1160    }
1161    break;
1162
1163  case QualType::DK_objc_strong_lifetime:
1164    // Suppress cleanups for pseudo-strong variables.
1165    if (var->isARCPseudoStrong()) return;
1166
1167    // Otherwise, consider whether to use an EH cleanup or not.
1168    cleanupKind = getARCCleanupKind();
1169
1170    // Use the imprecise destroyer by default.
1171    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1172      destroyer = CodeGenFunction::destroyARCStrongImprecise;
1173    break;
1174
1175  case QualType::DK_objc_weak_lifetime:
1176    break;
1177  }
1178
1179  // If we haven't chosen a more specific destroyer, use the default.
1180  if (!destroyer) destroyer = getDestroyer(dtorKind);
1181
1182  // Use an EH cleanup in array destructors iff the destructor itself
1183  // is being pushed as an EH cleanup.
1184  bool useEHCleanup = (cleanupKind & EHCleanup);
1185  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1186                                     useEHCleanup);
1187}
1188
1189void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1190  assert(emission.Variable && "emission was not valid!");
1191
1192  // If this was emitted as a global constant, we're done.
1193  if (emission.wasEmittedAsGlobal()) return;
1194
1195  // If we don't have an insertion point, we're done.  Sema prevents
1196  // us from jumping into any of these scopes anyway.
1197  if (!HaveInsertPoint()) return;
1198
1199  const VarDecl &D = *emission.Variable;
1200
1201  // Check the type for a cleanup.
1202  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1203    emitAutoVarTypeCleanup(emission, dtorKind);
1204
1205  // In GC mode, honor objc_precise_lifetime.
1206  if (getLangOpts().getGC() != LangOptions::NonGC &&
1207      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1208    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1209  }
1210
1211  // Handle the cleanup attribute.
1212  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1213    const FunctionDecl *FD = CA->getFunctionDecl();
1214
1215    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1216    assert(F && "Could not find function!");
1217
1218    const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1219    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1220  }
1221
1222  // If this is a block variable, call _Block_object_destroy
1223  // (on the unforwarded address).
1224  if (emission.IsByRef)
1225    enterByrefCleanup(emission);
1226}
1227
1228CodeGenFunction::Destroyer *
1229CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1230  switch (kind) {
1231  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1232  case QualType::DK_cxx_destructor:
1233    return destroyCXXObject;
1234  case QualType::DK_objc_strong_lifetime:
1235    return destroyARCStrongPrecise;
1236  case QualType::DK_objc_weak_lifetime:
1237    return destroyARCWeak;
1238  }
1239  llvm_unreachable("Unknown DestructionKind");
1240}
1241
1242/// pushDestroy - Push the standard destructor for the given type.
1243void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1244                                  llvm::Value *addr, QualType type) {
1245  assert(dtorKind && "cannot push destructor for trivial type");
1246
1247  CleanupKind cleanupKind = getCleanupKind(dtorKind);
1248  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1249              cleanupKind & EHCleanup);
1250}
1251
1252void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1253                                  QualType type, Destroyer *destroyer,
1254                                  bool useEHCleanupForArray) {
1255  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1256                                     destroyer, useEHCleanupForArray);
1257}
1258
1259/// emitDestroy - Immediately perform the destruction of the given
1260/// object.
1261///
1262/// \param addr - the address of the object; a type*
1263/// \param type - the type of the object; if an array type, all
1264///   objects are destroyed in reverse order
1265/// \param destroyer - the function to call to destroy individual
1266///   elements
1267/// \param useEHCleanupForArray - whether an EH cleanup should be
1268///   used when destroying array elements, in case one of the
1269///   destructions throws an exception
1270void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1271                                  Destroyer *destroyer,
1272                                  bool useEHCleanupForArray) {
1273  const ArrayType *arrayType = getContext().getAsArrayType(type);
1274  if (!arrayType)
1275    return destroyer(*this, addr, type);
1276
1277  llvm::Value *begin = addr;
1278  llvm::Value *length = emitArrayLength(arrayType, type, begin);
1279
1280  // Normally we have to check whether the array is zero-length.
1281  bool checkZeroLength = true;
1282
1283  // But if the array length is constant, we can suppress that.
1284  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1285    // ...and if it's constant zero, we can just skip the entire thing.
1286    if (constLength->isZero()) return;
1287    checkZeroLength = false;
1288  }
1289
1290  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1291  emitArrayDestroy(begin, end, type, destroyer,
1292                   checkZeroLength, useEHCleanupForArray);
1293}
1294
1295/// emitArrayDestroy - Destroys all the elements of the given array,
1296/// beginning from last to first.  The array cannot be zero-length.
1297///
1298/// \param begin - a type* denoting the first element of the array
1299/// \param end - a type* denoting one past the end of the array
1300/// \param type - the element type of the array
1301/// \param destroyer - the function to call to destroy elements
1302/// \param useEHCleanup - whether to push an EH cleanup to destroy
1303///   the remaining elements in case the destruction of a single
1304///   element throws
1305void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1306                                       llvm::Value *end,
1307                                       QualType type,
1308                                       Destroyer *destroyer,
1309                                       bool checkZeroLength,
1310                                       bool useEHCleanup) {
1311  assert(!type->isArrayType());
1312
1313  // The basic structure here is a do-while loop, because we don't
1314  // need to check for the zero-element case.
1315  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1316  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1317
1318  if (checkZeroLength) {
1319    llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1320                                                "arraydestroy.isempty");
1321    Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1322  }
1323
1324  // Enter the loop body, making that address the current address.
1325  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1326  EmitBlock(bodyBB);
1327  llvm::PHINode *elementPast =
1328    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1329  elementPast->addIncoming(end, entryBB);
1330
1331  // Shift the address back by one element.
1332  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1333  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1334                                                   "arraydestroy.element");
1335
1336  if (useEHCleanup)
1337    pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1338
1339  // Perform the actual destruction there.
1340  destroyer(*this, element, type);
1341
1342  if (useEHCleanup)
1343    PopCleanupBlock();
1344
1345  // Check whether we've reached the end.
1346  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1347  Builder.CreateCondBr(done, doneBB, bodyBB);
1348  elementPast->addIncoming(element, Builder.GetInsertBlock());
1349
1350  // Done.
1351  EmitBlock(doneBB);
1352}
1353
1354/// Perform partial array destruction as if in an EH cleanup.  Unlike
1355/// emitArrayDestroy, the element type here may still be an array type.
1356static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1357                                    llvm::Value *begin, llvm::Value *end,
1358                                    QualType type,
1359                                    CodeGenFunction::Destroyer *destroyer) {
1360  // If the element type is itself an array, drill down.
1361  unsigned arrayDepth = 0;
1362  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1363    // VLAs don't require a GEP index to walk into.
1364    if (!isa<VariableArrayType>(arrayType))
1365      arrayDepth++;
1366    type = arrayType->getElementType();
1367  }
1368
1369  if (arrayDepth) {
1370    llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1371
1372    SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1373    begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1374    end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1375  }
1376
1377  // Destroy the array.  We don't ever need an EH cleanup because we
1378  // assume that we're in an EH cleanup ourselves, so a throwing
1379  // destructor causes an immediate terminate.
1380  CGF.emitArrayDestroy(begin, end, type, destroyer,
1381                       /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1382}
1383
1384namespace {
1385  /// RegularPartialArrayDestroy - a cleanup which performs a partial
1386  /// array destroy where the end pointer is regularly determined and
1387  /// does not need to be loaded from a local.
1388  class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1389    llvm::Value *ArrayBegin;
1390    llvm::Value *ArrayEnd;
1391    QualType ElementType;
1392    CodeGenFunction::Destroyer *Destroyer;
1393  public:
1394    RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1395                               QualType elementType,
1396                               CodeGenFunction::Destroyer *destroyer)
1397      : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1398        ElementType(elementType), Destroyer(destroyer) {}
1399
1400    void Emit(CodeGenFunction &CGF, Flags flags) {
1401      emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1402                              ElementType, Destroyer);
1403    }
1404  };
1405
1406  /// IrregularPartialArrayDestroy - a cleanup which performs a
1407  /// partial array destroy where the end pointer is irregularly
1408  /// determined and must be loaded from a local.
1409  class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1410    llvm::Value *ArrayBegin;
1411    llvm::Value *ArrayEndPointer;
1412    QualType ElementType;
1413    CodeGenFunction::Destroyer *Destroyer;
1414  public:
1415    IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1416                                 llvm::Value *arrayEndPointer,
1417                                 QualType elementType,
1418                                 CodeGenFunction::Destroyer *destroyer)
1419      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1420        ElementType(elementType), Destroyer(destroyer) {}
1421
1422    void Emit(CodeGenFunction &CGF, Flags flags) {
1423      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1424      emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1425                              ElementType, Destroyer);
1426    }
1427  };
1428}
1429
1430/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1431/// already-constructed elements of the given array.  The cleanup
1432/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1433///
1434/// \param elementType - the immediate element type of the array;
1435///   possibly still an array type
1436/// \param array - a value of type elementType*
1437/// \param destructionKind - the kind of destruction required
1438/// \param initializedElementCount - a value of type size_t* holding
1439///   the number of successfully-constructed elements
1440void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1441                                                 llvm::Value *arrayEndPointer,
1442                                                       QualType elementType,
1443                                                       Destroyer *destroyer) {
1444  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1445                                                    arrayBegin, arrayEndPointer,
1446                                                    elementType, destroyer);
1447}
1448
1449/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1450/// already-constructed elements of the given array.  The cleanup
1451/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1452///
1453/// \param elementType - the immediate element type of the array;
1454///   possibly still an array type
1455/// \param array - a value of type elementType*
1456/// \param destructionKind - the kind of destruction required
1457/// \param initializedElementCount - a value of type size_t* holding
1458///   the number of successfully-constructed elements
1459void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1460                                                     llvm::Value *arrayEnd,
1461                                                     QualType elementType,
1462                                                     Destroyer *destroyer) {
1463  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1464                                                  arrayBegin, arrayEnd,
1465                                                  elementType, destroyer);
1466}
1467
1468namespace {
1469  /// A cleanup to perform a release of an object at the end of a
1470  /// function.  This is used to balance out the incoming +1 of a
1471  /// ns_consumed argument when we can't reasonably do that just by
1472  /// not doing the initial retain for a __block argument.
1473  struct ConsumeARCParameter : EHScopeStack::Cleanup {
1474    ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1475
1476    llvm::Value *Param;
1477
1478    void Emit(CodeGenFunction &CGF, Flags flags) {
1479      CGF.EmitARCRelease(Param, /*precise*/ false);
1480    }
1481  };
1482}
1483
1484/// Emit an alloca (or GlobalValue depending on target)
1485/// for the specified parameter and set up LocalDeclMap.
1486void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1487                                   unsigned ArgNo) {
1488  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1489  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1490         "Invalid argument to EmitParmDecl");
1491
1492  Arg->setName(D.getName());
1493
1494  // Use better IR generation for certain implicit parameters.
1495  if (isa<ImplicitParamDecl>(D)) {
1496    // The only implicit argument a block has is its literal.
1497    if (BlockInfo) {
1498      LocalDeclMap[&D] = Arg;
1499
1500      if (CGDebugInfo *DI = getDebugInfo()) {
1501        if (CGM.getCodeGenOpts().DebugInfo >=
1502            CodeGenOptions::LimitedDebugInfo) {
1503          DI->setLocation(D.getLocation());
1504          DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1505        }
1506      }
1507
1508      return;
1509    }
1510  }
1511
1512  QualType Ty = D.getType();
1513
1514  llvm::Value *DeclPtr;
1515  // If this is an aggregate or variable sized value, reuse the input pointer.
1516  if (!Ty->isConstantSizeType() ||
1517      CodeGenFunction::hasAggregateLLVMType(Ty)) {
1518    DeclPtr = Arg;
1519  } else {
1520    // Otherwise, create a temporary to hold the value.
1521    llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1522                                               D.getName() + ".addr");
1523    Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1524    DeclPtr = Alloc;
1525
1526    bool doStore = true;
1527
1528    Qualifiers qs = Ty.getQualifiers();
1529
1530    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1531      // We honor __attribute__((ns_consumed)) for types with lifetime.
1532      // For __strong, it's handled by just skipping the initial retain;
1533      // otherwise we have to balance out the initial +1 with an extra
1534      // cleanup to do the release at the end of the function.
1535      bool isConsumed = D.hasAttr<NSConsumedAttr>();
1536
1537      // 'self' is always formally __strong, but if this is not an
1538      // init method then we don't want to retain it.
1539      if (D.isARCPseudoStrong()) {
1540        const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1541        assert(&D == method->getSelfDecl());
1542        assert(lt == Qualifiers::OCL_Strong);
1543        assert(qs.hasConst());
1544        assert(method->getMethodFamily() != OMF_init);
1545        (void) method;
1546        lt = Qualifiers::OCL_ExplicitNone;
1547      }
1548
1549      if (lt == Qualifiers::OCL_Strong) {
1550        if (!isConsumed)
1551          // Don't use objc_retainBlock for block pointers, because we
1552          // don't want to Block_copy something just because we got it
1553          // as a parameter.
1554          Arg = EmitARCRetainNonBlock(Arg);
1555      } else {
1556        // Push the cleanup for a consumed parameter.
1557        if (isConsumed)
1558          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1559
1560        if (lt == Qualifiers::OCL_Weak) {
1561          EmitARCInitWeak(DeclPtr, Arg);
1562          doStore = false; // The weak init is a store, no need to do two.
1563        }
1564      }
1565
1566      // Enter the cleanup scope.
1567      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1568    }
1569
1570    // Store the initial value into the alloca.
1571    if (doStore) {
1572      LValue lv = MakeAddrLValue(DeclPtr, Ty,
1573                                 getContext().getDeclAlign(&D));
1574      EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1575    }
1576  }
1577
1578  llvm::Value *&DMEntry = LocalDeclMap[&D];
1579  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1580  DMEntry = DeclPtr;
1581
1582  // Emit debug info for param declaration.
1583  if (CGDebugInfo *DI = getDebugInfo()) {
1584    if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
1585      DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1586    }
1587  }
1588
1589  if (D.hasAttr<AnnotateAttr>())
1590      EmitVarAnnotations(&D, DeclPtr);
1591}
1592