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