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