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