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