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