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