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