1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Decl nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
15 #include "CGCleanup.h"
16 #include "CGDebugInfo.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CGOpenMPRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "PatternInit.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/CodeGenOptions.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/CodeGen/CGFunctionInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Type.h"
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 void CodeGenFunction::EmitDecl(const Decl &D) {
43   switch (D.getKind()) {
44   case Decl::BuiltinTemplate:
45   case Decl::TranslationUnit:
46   case Decl::ExternCContext:
47   case Decl::Namespace:
48   case Decl::UnresolvedUsingTypename:
49   case Decl::ClassTemplateSpecialization:
50   case Decl::ClassTemplatePartialSpecialization:
51   case Decl::VarTemplateSpecialization:
52   case Decl::VarTemplatePartialSpecialization:
53   case Decl::TemplateTypeParm:
54   case Decl::UnresolvedUsingValue:
55   case Decl::NonTypeTemplateParm:
56   case Decl::CXXDeductionGuide:
57   case Decl::CXXMethod:
58   case Decl::CXXConstructor:
59   case Decl::CXXDestructor:
60   case Decl::CXXConversion:
61   case Decl::Field:
62   case Decl::MSProperty:
63   case Decl::IndirectField:
64   case Decl::ObjCIvar:
65   case Decl::ObjCAtDefsField:
66   case Decl::ParmVar:
67   case Decl::ImplicitParam:
68   case Decl::ClassTemplate:
69   case Decl::VarTemplate:
70   case Decl::FunctionTemplate:
71   case Decl::TypeAliasTemplate:
72   case Decl::TemplateTemplateParm:
73   case Decl::ObjCMethod:
74   case Decl::ObjCCategory:
75   case Decl::ObjCProtocol:
76   case Decl::ObjCInterface:
77   case Decl::ObjCCategoryImpl:
78   case Decl::ObjCImplementation:
79   case Decl::ObjCProperty:
80   case Decl::ObjCCompatibleAlias:
81   case Decl::PragmaComment:
82   case Decl::PragmaDetectMismatch:
83   case Decl::AccessSpec:
84   case Decl::LinkageSpec:
85   case Decl::Export:
86   case Decl::ObjCPropertyImpl:
87   case Decl::FileScopeAsm:
88   case Decl::Friend:
89   case Decl::FriendTemplate:
90   case Decl::Block:
91   case Decl::Captured:
92   case Decl::ClassScopeFunctionSpecialization:
93   case Decl::UsingShadow:
94   case Decl::ConstructorUsingShadow:
95   case Decl::ObjCTypeParam:
96   case Decl::Binding:
97     llvm_unreachable("Declaration should not be in declstmts!");
98   case Decl::Function:  // void X();
99   case Decl::Record:    // struct/union/class X;
100   case Decl::Enum:      // enum X;
101   case Decl::EnumConstant: // enum ? { X = ? }
102   case Decl::CXXRecord: // struct/union/class X; [C++]
103   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
104   case Decl::Label:        // __label__ x;
105   case Decl::Import:
106   case Decl::OMPThreadPrivate:
107   case Decl::OMPAllocate:
108   case Decl::OMPCapturedExpr:
109   case Decl::OMPRequires:
110   case Decl::Empty:
111     // None of these decls require codegen support.
112     return;
113 
114   case Decl::NamespaceAlias:
115     if (CGDebugInfo *DI = getDebugInfo())
116         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
117     return;
118   case Decl::Using:          // using X; [C++]
119     if (CGDebugInfo *DI = getDebugInfo())
120         DI->EmitUsingDecl(cast<UsingDecl>(D));
121     return;
122   case Decl::UsingPack:
123     for (auto *Using : cast<UsingPackDecl>(D).expansions())
124       EmitDecl(*Using);
125     return;
126   case Decl::UsingDirective: // using namespace X; [C++]
127     if (CGDebugInfo *DI = getDebugInfo())
128       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
129     return;
130   case Decl::Var:
131   case Decl::Decomposition: {
132     const VarDecl &VD = cast<VarDecl>(D);
133     assert(VD.isLocalVarDecl() &&
134            "Should not see file-scope variables inside a function!");
135     EmitVarDecl(VD);
136     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
137       for (auto *B : DD->bindings())
138         if (auto *HD = B->getHoldingVar())
139           EmitVarDecl(*HD);
140     return;
141   }
142 
143   case Decl::OMPDeclareReduction:
144     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
145 
146   case Decl::OMPDeclareMapper:
147     return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
148 
149   case Decl::Typedef:      // typedef int X;
150   case Decl::TypeAlias: {  // using X = int; [C++0x]
151     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
152     QualType Ty = TD.getUnderlyingType();
153 
154     if (Ty->isVariablyModifiedType())
155       EmitVariablyModifiedType(Ty);
156   }
157   }
158 }
159 
160 /// EmitVarDecl - This method handles emission of any variable declaration
161 /// inside a function, including static vars etc.
162 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
163   if (D.hasExternalStorage())
164     // Don't emit it now, allow it to be emitted lazily on its first use.
165     return;
166 
167   // Some function-scope variable does not have static storage but still
168   // needs to be emitted like a static variable, e.g. a function-scope
169   // variable in constant address space in OpenCL.
170   if (D.getStorageDuration() != SD_Automatic) {
171     // Static sampler variables translated to function calls.
172     if (D.getType()->isSamplerT())
173       return;
174 
175     llvm::GlobalValue::LinkageTypes Linkage =
176         CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
177 
178     // FIXME: We need to force the emission/use of a guard variable for
179     // some variables even if we can constant-evaluate them because
180     // we can't guarantee every translation unit will constant-evaluate them.
181 
182     return EmitStaticVarDecl(D, Linkage);
183   }
184 
185   if (D.getType().getAddressSpace() == LangAS::opencl_local)
186     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
187 
188   assert(D.hasLocalStorage());
189   return EmitAutoVarDecl(D);
190 }
191 
192 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
193   if (CGM.getLangOpts().CPlusPlus)
194     return CGM.getMangledName(&D).str();
195 
196   // If this isn't C++, we don't need a mangled name, just a pretty one.
197   assert(!D.isExternallyVisible() && "name shouldn't matter");
198   std::string ContextName;
199   const DeclContext *DC = D.getDeclContext();
200   if (auto *CD = dyn_cast<CapturedDecl>(DC))
201     DC = cast<DeclContext>(CD->getNonClosureContext());
202   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
203     ContextName = CGM.getMangledName(FD);
204   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
205     ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
206   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
207     ContextName = OMD->getSelector().getAsString();
208   else
209     llvm_unreachable("Unknown context for static var decl");
210 
211   ContextName += "." + D.getNameAsString();
212   return ContextName;
213 }
214 
215 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
216     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
217   // In general, we don't always emit static var decls once before we reference
218   // them. It is possible to reference them before emitting the function that
219   // contains them, and it is possible to emit the containing function multiple
220   // times.
221   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
222     return ExistingGV;
223 
224   QualType Ty = D.getType();
225   assert(Ty->isConstantSizeType() && "VLAs can't be static");
226 
227   // Use the label if the variable is renamed with the asm-label extension.
228   std::string Name;
229   if (D.hasAttr<AsmLabelAttr>())
230     Name = getMangledName(&D);
231   else
232     Name = getStaticDeclName(*this, D);
233 
234   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
235   LangAS AS = GetGlobalVarAddressSpace(&D);
236   unsigned TargetAS = getContext().getTargetAddressSpace(AS);
237 
238   // OpenCL variables in local address space and CUDA shared
239   // variables cannot have an initializer.
240   llvm::Constant *Init = nullptr;
241   if (Ty.getAddressSpace() == LangAS::opencl_local ||
242       D.hasAttr<CUDASharedAttr>())
243     Init = llvm::UndefValue::get(LTy);
244   else
245     Init = EmitNullConstant(Ty);
246 
247   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
248       getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
249       nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
250   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
251 
252   if (supportsCOMDAT() && GV->isWeakForLinker())
253     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
254 
255   if (D.getTLSKind())
256     setTLSMode(GV, D);
257 
258   setGVProperties(GV, &D);
259 
260   // Make sure the result is of the correct type.
261   LangAS ExpectedAS = Ty.getAddressSpace();
262   llvm::Constant *Addr = GV;
263   if (AS != ExpectedAS) {
264     Addr = getTargetCodeGenInfo().performAddrSpaceCast(
265         *this, GV, AS, ExpectedAS,
266         LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
267   }
268 
269   setStaticLocalDeclAddress(&D, Addr);
270 
271   // Ensure that the static local gets initialized by making sure the parent
272   // function gets emitted eventually.
273   const Decl *DC = cast<Decl>(D.getDeclContext());
274 
275   // We can't name blocks or captured statements directly, so try to emit their
276   // parents.
277   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
278     DC = DC->getNonClosureContext();
279     // FIXME: Ensure that global blocks get emitted.
280     if (!DC)
281       return Addr;
282   }
283 
284   GlobalDecl GD;
285   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
286     GD = GlobalDecl(CD, Ctor_Base);
287   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
288     GD = GlobalDecl(DD, Dtor_Base);
289   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
290     GD = GlobalDecl(FD);
291   else {
292     // Don't do anything for Obj-C method decls or global closures. We should
293     // never defer them.
294     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
295   }
296   if (GD.getDecl()) {
297     // Disable emission of the parent function for the OpenMP device codegen.
298     CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
299     (void)GetAddrOfGlobal(GD);
300   }
301 
302   return Addr;
303 }
304 
305 /// hasNontrivialDestruction - Determine whether a type's destruction is
306 /// non-trivial. If so, and the variable uses static initialization, we must
307 /// register its destructor to run on exit.
308 static bool hasNontrivialDestruction(QualType T) {
309   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
310   return RD && !RD->hasTrivialDestructor();
311 }
312 
313 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
314 /// global variable that has already been created for it.  If the initializer
315 /// has a different type than GV does, this may free GV and return a different
316 /// one.  Otherwise it just returns GV.
317 llvm::GlobalVariable *
318 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
319                                                llvm::GlobalVariable *GV) {
320   ConstantEmitter emitter(*this);
321   llvm::Constant *Init = emitter.tryEmitForInitializer(D);
322 
323   // If constant emission failed, then this should be a C++ static
324   // initializer.
325   if (!Init) {
326     if (!getLangOpts().CPlusPlus)
327       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
328     else if (HaveInsertPoint()) {
329       // Since we have a static initializer, this global variable can't
330       // be constant.
331       GV->setConstant(false);
332 
333       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
334     }
335     return GV;
336   }
337 
338   // The initializer may differ in type from the global. Rewrite
339   // the global to match the initializer.  (We have to do this
340   // because some types, like unions, can't be completely represented
341   // in the LLVM type system.)
342   if (GV->getType()->getElementType() != Init->getType()) {
343     llvm::GlobalVariable *OldGV = GV;
344 
345     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
346                                   OldGV->isConstant(),
347                                   OldGV->getLinkage(), Init, "",
348                                   /*InsertBefore*/ OldGV,
349                                   OldGV->getThreadLocalMode(),
350                            CGM.getContext().getTargetAddressSpace(D.getType()));
351     GV->setVisibility(OldGV->getVisibility());
352     GV->setDSOLocal(OldGV->isDSOLocal());
353     GV->setComdat(OldGV->getComdat());
354 
355     // Steal the name of the old global
356     GV->takeName(OldGV);
357 
358     // Replace all uses of the old global with the new global
359     llvm::Constant *NewPtrForOldDecl =
360     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
361     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
362 
363     // Erase the old global, since it is no longer used.
364     OldGV->eraseFromParent();
365   }
366 
367   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
368   GV->setInitializer(Init);
369 
370   emitter.finalize(GV);
371 
372   if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
373     // We have a constant initializer, but a nontrivial destructor. We still
374     // need to perform a guarded "initialization" in order to register the
375     // destructor.
376     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
377   }
378 
379   return GV;
380 }
381 
382 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
383                                       llvm::GlobalValue::LinkageTypes Linkage) {
384   // Check to see if we already have a global variable for this
385   // declaration.  This can happen when double-emitting function
386   // bodies, e.g. with complete and base constructors.
387   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
388   CharUnits alignment = getContext().getDeclAlign(&D);
389 
390   // Store into LocalDeclMap before generating initializer to handle
391   // circular references.
392   setAddrOfLocalVar(&D, Address(addr, alignment));
393 
394   // We can't have a VLA here, but we can have a pointer to a VLA,
395   // even though that doesn't really make any sense.
396   // Make sure to evaluate VLA bounds now so that we have them for later.
397   if (D.getType()->isVariablyModifiedType())
398     EmitVariablyModifiedType(D.getType());
399 
400   // Save the type in case adding the initializer forces a type change.
401   llvm::Type *expectedType = addr->getType();
402 
403   llvm::GlobalVariable *var =
404     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
405 
406   // CUDA's local and local static __shared__ variables should not
407   // have any non-empty initializers. This is ensured by Sema.
408   // Whatever initializer such variable may have when it gets here is
409   // a no-op and should not be emitted.
410   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
411                          D.hasAttr<CUDASharedAttr>();
412   // If this value has an initializer, emit it.
413   if (D.getInit() && !isCudaSharedVar)
414     var = AddInitializerToStaticVarDecl(D, var);
415 
416   var->setAlignment(alignment.getQuantity());
417 
418   if (D.hasAttr<AnnotateAttr>())
419     CGM.AddGlobalAnnotations(&D, var);
420 
421   if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
422     var->addAttribute("bss-section", SA->getName());
423   if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
424     var->addAttribute("data-section", SA->getName());
425   if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
426     var->addAttribute("rodata-section", SA->getName());
427 
428   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
429     var->setSection(SA->getName());
430 
431   if (D.hasAttr<UsedAttr>())
432     CGM.addUsedGlobal(var);
433 
434   // We may have to cast the constant because of the initializer
435   // mismatch above.
436   //
437   // FIXME: It is really dangerous to store this in the map; if anyone
438   // RAUW's the GV uses of this constant will be invalid.
439   llvm::Constant *castedAddr =
440     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
441   if (var != castedAddr)
442     LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
443   CGM.setStaticLocalDeclAddress(&D, castedAddr);
444 
445   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
446 
447   // Emit global variable debug descriptor for static vars.
448   CGDebugInfo *DI = getDebugInfo();
449   if (DI &&
450       CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
451     DI->setLocation(D.getLocation());
452     DI->EmitGlobalVariable(var, &D);
453   }
454 }
455 
456 namespace {
457   struct DestroyObject final : EHScopeStack::Cleanup {
458     DestroyObject(Address addr, QualType type,
459                   CodeGenFunction::Destroyer *destroyer,
460                   bool useEHCleanupForArray)
461       : addr(addr), type(type), destroyer(destroyer),
462         useEHCleanupForArray(useEHCleanupForArray) {}
463 
464     Address addr;
465     QualType type;
466     CodeGenFunction::Destroyer *destroyer;
467     bool useEHCleanupForArray;
468 
469     void Emit(CodeGenFunction &CGF, Flags flags) override {
470       // Don't use an EH cleanup recursively from an EH cleanup.
471       bool useEHCleanupForArray =
472         flags.isForNormalCleanup() && this->useEHCleanupForArray;
473 
474       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
475     }
476   };
477 
478   template <class Derived>
479   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
480     DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
481         : NRVOFlag(NRVOFlag), Loc(addr) {}
482 
483     llvm::Value *NRVOFlag;
484     Address Loc;
485 
486     void Emit(CodeGenFunction &CGF, Flags flags) override {
487       // Along the exceptions path we always execute the dtor.
488       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
489 
490       llvm::BasicBlock *SkipDtorBB = nullptr;
491       if (NRVO) {
492         // If we exited via NRVO, we skip the destructor call.
493         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
494         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
495         llvm::Value *DidNRVO =
496           CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
497         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
498         CGF.EmitBlock(RunDtorBB);
499       }
500 
501       static_cast<Derived *>(this)->emitDestructorCall(CGF);
502 
503       if (NRVO) CGF.EmitBlock(SkipDtorBB);
504     }
505 
506     virtual ~DestroyNRVOVariable() = default;
507   };
508 
509   struct DestroyNRVOVariableCXX final
510       : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
511     DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
512                            llvm::Value *NRVOFlag)
513       : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
514         Dtor(Dtor) {}
515 
516     const CXXDestructorDecl *Dtor;
517 
518     void emitDestructorCall(CodeGenFunction &CGF) {
519       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
520                                 /*ForVirtualBase=*/false,
521                                 /*Delegating=*/false, Loc);
522     }
523   };
524 
525   struct DestroyNRVOVariableC final
526       : DestroyNRVOVariable<DestroyNRVOVariableC> {
527     DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
528         : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
529 
530     QualType Ty;
531 
532     void emitDestructorCall(CodeGenFunction &CGF) {
533       CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
534     }
535   };
536 
537   struct CallStackRestore final : EHScopeStack::Cleanup {
538     Address Stack;
539     CallStackRestore(Address Stack) : Stack(Stack) {}
540     void Emit(CodeGenFunction &CGF, Flags flags) override {
541       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
542       llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
543       CGF.Builder.CreateCall(F, V);
544     }
545   };
546 
547   struct ExtendGCLifetime final : EHScopeStack::Cleanup {
548     const VarDecl &Var;
549     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
550 
551     void Emit(CodeGenFunction &CGF, Flags flags) override {
552       // Compute the address of the local variable, in case it's a
553       // byref or something.
554       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
555                       Var.getType(), VK_LValue, SourceLocation());
556       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
557                                                 SourceLocation());
558       CGF.EmitExtendGCLifetime(value);
559     }
560   };
561 
562   struct CallCleanupFunction final : EHScopeStack::Cleanup {
563     llvm::Constant *CleanupFn;
564     const CGFunctionInfo &FnInfo;
565     const VarDecl &Var;
566 
567     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
568                         const VarDecl *Var)
569       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
570 
571     void Emit(CodeGenFunction &CGF, Flags flags) override {
572       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
573                       Var.getType(), VK_LValue, SourceLocation());
574       // Compute the address of the local variable, in case it's a byref
575       // or something.
576       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
577 
578       // In some cases, the type of the function argument will be different from
579       // the type of the pointer. An example of this is
580       // void f(void* arg);
581       // __attribute__((cleanup(f))) void *g;
582       //
583       // To fix this we insert a bitcast here.
584       QualType ArgTy = FnInfo.arg_begin()->type;
585       llvm::Value *Arg =
586         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
587 
588       CallArgList Args;
589       Args.add(RValue::get(Arg),
590                CGF.getContext().getPointerType(Var.getType()));
591       auto Callee = CGCallee::forDirect(CleanupFn);
592       CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
593     }
594   };
595 } // end anonymous namespace
596 
597 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
598 /// variable with lifetime.
599 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
600                                     Address addr,
601                                     Qualifiers::ObjCLifetime lifetime) {
602   switch (lifetime) {
603   case Qualifiers::OCL_None:
604     llvm_unreachable("present but none");
605 
606   case Qualifiers::OCL_ExplicitNone:
607     // nothing to do
608     break;
609 
610   case Qualifiers::OCL_Strong: {
611     CodeGenFunction::Destroyer *destroyer =
612       (var.hasAttr<ObjCPreciseLifetimeAttr>()
613        ? CodeGenFunction::destroyARCStrongPrecise
614        : CodeGenFunction::destroyARCStrongImprecise);
615 
616     CleanupKind cleanupKind = CGF.getARCCleanupKind();
617     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
618                     cleanupKind & EHCleanup);
619     break;
620   }
621   case Qualifiers::OCL_Autoreleasing:
622     // nothing to do
623     break;
624 
625   case Qualifiers::OCL_Weak:
626     // __weak objects always get EH cleanups; otherwise, exceptions
627     // could cause really nasty crashes instead of mere leaks.
628     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
629                     CodeGenFunction::destroyARCWeak,
630                     /*useEHCleanup*/ true);
631     break;
632   }
633 }
634 
635 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
636   if (const Expr *e = dyn_cast<Expr>(s)) {
637     // Skip the most common kinds of expressions that make
638     // hierarchy-walking expensive.
639     s = e = e->IgnoreParenCasts();
640 
641     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
642       return (ref->getDecl() == &var);
643     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
644       const BlockDecl *block = be->getBlockDecl();
645       for (const auto &I : block->captures()) {
646         if (I.getVariable() == &var)
647           return true;
648       }
649     }
650   }
651 
652   for (const Stmt *SubStmt : s->children())
653     // SubStmt might be null; as in missing decl or conditional of an if-stmt.
654     if (SubStmt && isAccessedBy(var, SubStmt))
655       return true;
656 
657   return false;
658 }
659 
660 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
661   if (!decl) return false;
662   if (!isa<VarDecl>(decl)) return false;
663   const VarDecl *var = cast<VarDecl>(decl);
664   return isAccessedBy(*var, e);
665 }
666 
667 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
668                                    const LValue &destLV, const Expr *init) {
669   bool needsCast = false;
670 
671   while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
672     switch (castExpr->getCastKind()) {
673     // Look through casts that don't require representation changes.
674     case CK_NoOp:
675     case CK_BitCast:
676     case CK_BlockPointerToObjCPointerCast:
677       needsCast = true;
678       break;
679 
680     // If we find an l-value to r-value cast from a __weak variable,
681     // emit this operation as a copy or move.
682     case CK_LValueToRValue: {
683       const Expr *srcExpr = castExpr->getSubExpr();
684       if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
685         return false;
686 
687       // Emit the source l-value.
688       LValue srcLV = CGF.EmitLValue(srcExpr);
689 
690       // Handle a formal type change to avoid asserting.
691       auto srcAddr = srcLV.getAddress();
692       if (needsCast) {
693         srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
694                                          destLV.getAddress().getElementType());
695       }
696 
697       // If it was an l-value, use objc_copyWeak.
698       if (srcExpr->getValueKind() == VK_LValue) {
699         CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
700       } else {
701         assert(srcExpr->getValueKind() == VK_XValue);
702         CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
703       }
704       return true;
705     }
706 
707     // Stop at anything else.
708     default:
709       return false;
710     }
711 
712     init = castExpr->getSubExpr();
713   }
714   return false;
715 }
716 
717 static void drillIntoBlockVariable(CodeGenFunction &CGF,
718                                    LValue &lvalue,
719                                    const VarDecl *var) {
720   lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
721 }
722 
723 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
724                                            SourceLocation Loc) {
725   if (!SanOpts.has(SanitizerKind::NullabilityAssign))
726     return;
727 
728   auto Nullability = LHS.getType()->getNullability(getContext());
729   if (!Nullability || *Nullability != NullabilityKind::NonNull)
730     return;
731 
732   // Check if the right hand side of the assignment is nonnull, if the left
733   // hand side must be nonnull.
734   SanitizerScope SanScope(this);
735   llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
736   llvm::Constant *StaticData[] = {
737       EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
738       llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
739       llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
740   EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
741             SanitizerHandler::TypeMismatch, StaticData, RHS);
742 }
743 
744 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
745                                      LValue lvalue, bool capturedByInit) {
746   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
747   if (!lifetime) {
748     llvm::Value *value = EmitScalarExpr(init);
749     if (capturedByInit)
750       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
751     EmitNullabilityCheck(lvalue, value, init->getExprLoc());
752     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
753     return;
754   }
755 
756   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
757     init = DIE->getExpr();
758 
759   // If we're emitting a value with lifetime, we have to do the
760   // initialization *before* we leave the cleanup scopes.
761   if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
762     enterFullExpression(fe);
763     init = fe->getSubExpr();
764   }
765   CodeGenFunction::RunCleanupsScope Scope(*this);
766 
767   // We have to maintain the illusion that the variable is
768   // zero-initialized.  If the variable might be accessed in its
769   // initializer, zero-initialize before running the initializer, then
770   // actually perform the initialization with an assign.
771   bool accessedByInit = false;
772   if (lifetime != Qualifiers::OCL_ExplicitNone)
773     accessedByInit = (capturedByInit || isAccessedBy(D, init));
774   if (accessedByInit) {
775     LValue tempLV = lvalue;
776     // Drill down to the __block object if necessary.
777     if (capturedByInit) {
778       // We can use a simple GEP for this because it can't have been
779       // moved yet.
780       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
781                                               cast<VarDecl>(D),
782                                               /*follow*/ false));
783     }
784 
785     auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
786     llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
787 
788     // If __weak, we want to use a barrier under certain conditions.
789     if (lifetime == Qualifiers::OCL_Weak)
790       EmitARCInitWeak(tempLV.getAddress(), zero);
791 
792     // Otherwise just do a simple store.
793     else
794       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
795   }
796 
797   // Emit the initializer.
798   llvm::Value *value = nullptr;
799 
800   switch (lifetime) {
801   case Qualifiers::OCL_None:
802     llvm_unreachable("present but none");
803 
804   case Qualifiers::OCL_Strong: {
805     if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
806       value = EmitARCRetainScalarExpr(init);
807       break;
808     }
809     // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
810     // that we omit the retain, and causes non-autoreleased return values to be
811     // immediately released.
812     LLVM_FALLTHROUGH;
813   }
814 
815   case Qualifiers::OCL_ExplicitNone:
816     value = EmitARCUnsafeUnretainedScalarExpr(init);
817     break;
818 
819   case Qualifiers::OCL_Weak: {
820     // If it's not accessed by the initializer, try to emit the
821     // initialization with a copy or move.
822     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
823       return;
824     }
825 
826     // No way to optimize a producing initializer into this.  It's not
827     // worth optimizing for, because the value will immediately
828     // disappear in the common case.
829     value = EmitScalarExpr(init);
830 
831     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
832     if (accessedByInit)
833       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
834     else
835       EmitARCInitWeak(lvalue.getAddress(), value);
836     return;
837   }
838 
839   case Qualifiers::OCL_Autoreleasing:
840     value = EmitARCRetainAutoreleaseScalarExpr(init);
841     break;
842   }
843 
844   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
845 
846   EmitNullabilityCheck(lvalue, value, init->getExprLoc());
847 
848   // If the variable might have been accessed by its initializer, we
849   // might have to initialize with a barrier.  We have to do this for
850   // both __weak and __strong, but __weak got filtered out above.
851   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
852     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
853     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
854     EmitARCRelease(oldValue, ARCImpreciseLifetime);
855     return;
856   }
857 
858   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
859 }
860 
861 /// Decide whether we can emit the non-zero parts of the specified initializer
862 /// with equal or fewer than NumStores scalar stores.
863 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
864                                                unsigned &NumStores) {
865   // Zero and Undef never requires any extra stores.
866   if (isa<llvm::ConstantAggregateZero>(Init) ||
867       isa<llvm::ConstantPointerNull>(Init) ||
868       isa<llvm::UndefValue>(Init))
869     return true;
870   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
871       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
872       isa<llvm::ConstantExpr>(Init))
873     return Init->isNullValue() || NumStores--;
874 
875   // See if we can emit each element.
876   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
877     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
878       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
879       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
880         return false;
881     }
882     return true;
883   }
884 
885   if (llvm::ConstantDataSequential *CDS =
886         dyn_cast<llvm::ConstantDataSequential>(Init)) {
887     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
888       llvm::Constant *Elt = CDS->getElementAsConstant(i);
889       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
890         return false;
891     }
892     return true;
893   }
894 
895   // Anything else is hard and scary.
896   return false;
897 }
898 
899 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
900 /// the scalar stores that would be required.
901 static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
902                                         llvm::Constant *Init, Address Loc,
903                                         bool isVolatile, CGBuilderTy &Builder) {
904   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
905          "called emitStoresForInitAfterBZero for zero or undef value.");
906 
907   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
908       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
909       isa<llvm::ConstantExpr>(Init)) {
910     Builder.CreateStore(Init, Loc, isVolatile);
911     return;
912   }
913 
914   if (llvm::ConstantDataSequential *CDS =
915           dyn_cast<llvm::ConstantDataSequential>(Init)) {
916     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
917       llvm::Constant *Elt = CDS->getElementAsConstant(i);
918 
919       // If necessary, get a pointer to the element and emit it.
920       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
921         emitStoresForInitAfterBZero(
922             CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
923             Builder);
924     }
925     return;
926   }
927 
928   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
929          "Unknown value type!");
930 
931   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
932     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
933 
934     // If necessary, get a pointer to the element and emit it.
935     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
936       emitStoresForInitAfterBZero(CGM, Elt,
937                                   Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
938                                   isVolatile, Builder);
939   }
940 }
941 
942 /// Decide whether we should use bzero plus some stores to initialize a local
943 /// variable instead of using a memcpy from a constant global.  It is beneficial
944 /// to use bzero if the global is all zeros, or mostly zeros and large.
945 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
946                                                  uint64_t GlobalSize) {
947   // If a global is all zeros, always use a bzero.
948   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
949 
950   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
951   // do it if it will require 6 or fewer scalar stores.
952   // TODO: Should budget depends on the size?  Avoiding a large global warrants
953   // plopping in more stores.
954   unsigned StoreBudget = 6;
955   uint64_t SizeLimit = 32;
956 
957   return GlobalSize > SizeLimit &&
958          canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
959 }
960 
961 /// Decide whether we should use memset to initialize a local variable instead
962 /// of using a memcpy from a constant global. Assumes we've already decided to
963 /// not user bzero.
964 /// FIXME We could be more clever, as we are for bzero above, and generate
965 ///       memset followed by stores. It's unclear that's worth the effort.
966 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
967                                                 uint64_t GlobalSize) {
968   uint64_t SizeLimit = 32;
969   if (GlobalSize <= SizeLimit)
970     return nullptr;
971   return llvm::isBytewiseValue(Init);
972 }
973 
974 /// Decide whether we want to split a constant structure or array store into a
975 /// sequence of its fields' stores. This may cost us code size and compilation
976 /// speed, but plays better with store optimizations.
977 static bool shouldSplitConstantStore(CodeGenModule &CGM,
978                                      uint64_t GlobalByteSize) {
979   // Don't break things that occupy more than one cacheline.
980   uint64_t ByteSizeLimit = 64;
981   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
982     return false;
983   if (GlobalByteSize <= ByteSizeLimit)
984     return true;
985   return false;
986 }
987 
988 enum class IsPattern { No, Yes };
989 
990 /// Generate a constant filled with either a pattern or zeroes.
991 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
992                                         llvm::Type *Ty) {
993   if (isPattern == IsPattern::Yes)
994     return initializationPatternFor(CGM, Ty);
995   else
996     return llvm::Constant::getNullValue(Ty);
997 }
998 
999 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1000                                         llvm::Constant *constant);
1001 
1002 /// Helper function for constWithPadding() to deal with padding in structures.
1003 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1004                                               IsPattern isPattern,
1005                                               llvm::StructType *STy,
1006                                               llvm::Constant *constant) {
1007   const llvm::DataLayout &DL = CGM.getDataLayout();
1008   const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1009   llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1010   unsigned SizeSoFar = 0;
1011   SmallVector<llvm::Constant *, 8> Values;
1012   bool NestedIntact = true;
1013   for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1014     unsigned CurOff = Layout->getElementOffset(i);
1015     if (SizeSoFar < CurOff) {
1016       assert(!STy->isPacked());
1017       auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1018       Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1019     }
1020     llvm::Constant *CurOp;
1021     if (constant->isZeroValue())
1022       CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1023     else
1024       CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1025     auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1026     if (CurOp != NewOp)
1027       NestedIntact = false;
1028     Values.push_back(NewOp);
1029     SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1030   }
1031   unsigned TotalSize = Layout->getSizeInBytes();
1032   if (SizeSoFar < TotalSize) {
1033     auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1034     Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1035   }
1036   if (NestedIntact && Values.size() == STy->getNumElements())
1037     return constant;
1038   return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1039 }
1040 
1041 /// Replace all padding bytes in a given constant with either a pattern byte or
1042 /// 0x00.
1043 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1044                                         llvm::Constant *constant) {
1045   llvm::Type *OrigTy = constant->getType();
1046   if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1047     return constStructWithPadding(CGM, isPattern, STy, constant);
1048   if (auto *STy = dyn_cast<llvm::SequentialType>(OrigTy)) {
1049     llvm::SmallVector<llvm::Constant *, 8> Values;
1050     unsigned Size = STy->getNumElements();
1051     if (!Size)
1052       return constant;
1053     llvm::Type *ElemTy = STy->getElementType();
1054     bool ZeroInitializer = constant->isZeroValue();
1055     llvm::Constant *OpValue, *PaddedOp;
1056     if (ZeroInitializer) {
1057       OpValue = llvm::Constant::getNullValue(ElemTy);
1058       PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1059     }
1060     for (unsigned Op = 0; Op != Size; ++Op) {
1061       if (!ZeroInitializer) {
1062         OpValue = constant->getAggregateElement(Op);
1063         PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1064       }
1065       Values.push_back(PaddedOp);
1066     }
1067     auto *NewElemTy = Values[0]->getType();
1068     if (NewElemTy == ElemTy)
1069       return constant;
1070     if (OrigTy->isArrayTy()) {
1071       auto *ArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1072       return llvm::ConstantArray::get(ArrayTy, Values);
1073     } else {
1074       return llvm::ConstantVector::get(Values);
1075     }
1076   }
1077   return constant;
1078 }
1079 
1080 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1081                                                llvm::Constant *Constant,
1082                                                CharUnits Align) {
1083   auto FunctionName = [&](const DeclContext *DC) -> std::string {
1084     if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1085       if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1086         return CC->getNameAsString();
1087       if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1088         return CD->getNameAsString();
1089       return getMangledName(FD);
1090     } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1091       return OM->getNameAsString();
1092     } else if (isa<BlockDecl>(DC)) {
1093       return "<block>";
1094     } else if (isa<CapturedDecl>(DC)) {
1095       return "<captured>";
1096     } else {
1097       llvm::llvm_unreachable_internal("expected a function or method");
1098     }
1099   };
1100 
1101   // Form a simple per-variable cache of these values in case we find we
1102   // want to reuse them.
1103   llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1104   if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1105     auto *Ty = Constant->getType();
1106     bool isConstant = true;
1107     llvm::GlobalVariable *InsertBefore = nullptr;
1108     unsigned AS =
1109         getContext().getTargetAddressSpace(getStringLiteralAddressSpace());
1110     llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1111         getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1112         Constant,
1113         "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
1114             D.getName(),
1115         InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1116     GV->setAlignment(Align.getQuantity());
1117     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1118     CacheEntry = GV;
1119   } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
1120     CacheEntry->setAlignment(Align.getQuantity());
1121   }
1122 
1123   return Address(CacheEntry, Align);
1124 }
1125 
1126 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1127                                                 const VarDecl &D,
1128                                                 CGBuilderTy &Builder,
1129                                                 llvm::Constant *Constant,
1130                                                 CharUnits Align) {
1131   Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1132   llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1133                                                    SrcPtr.getAddressSpace());
1134   if (SrcPtr.getType() != BP)
1135     SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1136   return SrcPtr;
1137 }
1138 
1139 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1140                                   Address Loc, bool isVolatile,
1141                                   CGBuilderTy &Builder,
1142                                   llvm::Constant *constant) {
1143   auto *Ty = constant->getType();
1144   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1145                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1146   if (canDoSingleStore) {
1147     Builder.CreateStore(constant, Loc, isVolatile);
1148     return;
1149   }
1150 
1151   auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1152   auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1153 
1154   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1155   if (!ConstantSize)
1156     return;
1157   auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1158 
1159   // If the initializer is all or mostly the same, codegen with bzero / memset
1160   // then do a few stores afterward.
1161   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1162     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1163                          isVolatile);
1164 
1165     bool valueAlreadyCorrect =
1166         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1167     if (!valueAlreadyCorrect) {
1168       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1169       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1170     }
1171     return;
1172   }
1173 
1174   // If the initializer is a repeated byte pattern, use memset.
1175   llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1176   if (Pattern) {
1177     uint64_t Value = 0x00;
1178     if (!isa<llvm::UndefValue>(Pattern)) {
1179       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1180       assert(AP.getBitWidth() <= 8);
1181       Value = AP.getLimitedValue();
1182     }
1183     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1184                          isVolatile);
1185     return;
1186   }
1187 
1188   // If the initializer is small, use a handful of stores.
1189   if (shouldSplitConstantStore(CGM, ConstantSize)) {
1190     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1191       // FIXME: handle the case when STy != Loc.getElementType().
1192       if (STy == Loc.getElementType()) {
1193         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1194           Address EltPtr = Builder.CreateStructGEP(Loc, i);
1195           emitStoresForConstant(
1196               CGM, D, EltPtr, isVolatile, Builder,
1197               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1198         }
1199         return;
1200       }
1201     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1202       // FIXME: handle the case when ATy != Loc.getElementType().
1203       if (ATy == Loc.getElementType()) {
1204         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1205           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1206           emitStoresForConstant(
1207               CGM, D, EltPtr, isVolatile, Builder,
1208               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1209         }
1210         return;
1211       }
1212     }
1213   }
1214 
1215   // Copy from a global.
1216   Builder.CreateMemCpy(Loc,
1217                        createUnnamedGlobalForMemcpyFrom(
1218                            CGM, D, Builder, constant, Loc.getAlignment()),
1219                        SizeVal, isVolatile);
1220 }
1221 
1222 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1223                                   Address Loc, bool isVolatile,
1224                                   CGBuilderTy &Builder) {
1225   llvm::Type *ElTy = Loc.getElementType();
1226   llvm::Constant *constant =
1227       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1228   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1229 }
1230 
1231 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1232                                      Address Loc, bool isVolatile,
1233                                      CGBuilderTy &Builder) {
1234   llvm::Type *ElTy = Loc.getElementType();
1235   llvm::Constant *constant = constWithPadding(
1236       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1237   assert(!isa<llvm::UndefValue>(constant));
1238   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1239 }
1240 
1241 static bool containsUndef(llvm::Constant *constant) {
1242   auto *Ty = constant->getType();
1243   if (isa<llvm::UndefValue>(constant))
1244     return true;
1245   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1246     for (llvm::Use &Op : constant->operands())
1247       if (containsUndef(cast<llvm::Constant>(Op)))
1248         return true;
1249   return false;
1250 }
1251 
1252 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1253                                     llvm::Constant *constant) {
1254   auto *Ty = constant->getType();
1255   if (isa<llvm::UndefValue>(constant))
1256     return patternOrZeroFor(CGM, isPattern, Ty);
1257   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1258     return constant;
1259   if (!containsUndef(constant))
1260     return constant;
1261   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1262   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1263     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1264     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1265   }
1266   if (Ty->isStructTy())
1267     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1268   if (Ty->isArrayTy())
1269     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1270   assert(Ty->isVectorTy());
1271   return llvm::ConstantVector::get(Values);
1272 }
1273 
1274 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1275 /// variable declaration with auto, register, or no storage class specifier.
1276 /// These turn into simple stack objects, or GlobalValues depending on target.
1277 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1278   AutoVarEmission emission = EmitAutoVarAlloca(D);
1279   EmitAutoVarInit(emission);
1280   EmitAutoVarCleanups(emission);
1281 }
1282 
1283 /// Emit a lifetime.begin marker if some criteria are satisfied.
1284 /// \return a pointer to the temporary size Value if a marker was emitted, null
1285 /// otherwise
1286 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1287                                                 llvm::Value *Addr) {
1288   if (!ShouldEmitLifetimeMarkers)
1289     return nullptr;
1290 
1291   assert(Addr->getType()->getPointerAddressSpace() ==
1292              CGM.getDataLayout().getAllocaAddrSpace() &&
1293          "Pointer should be in alloca address space");
1294   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1295   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1296   llvm::CallInst *C =
1297       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1298   C->setDoesNotThrow();
1299   return SizeV;
1300 }
1301 
1302 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1303   assert(Addr->getType()->getPointerAddressSpace() ==
1304              CGM.getDataLayout().getAllocaAddrSpace() &&
1305          "Pointer should be in alloca address space");
1306   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1307   llvm::CallInst *C =
1308       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1309   C->setDoesNotThrow();
1310 }
1311 
1312 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1313     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1314   // For each dimension stores its QualType and corresponding
1315   // size-expression Value.
1316   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1317   SmallVector<IdentifierInfo *, 4> VLAExprNames;
1318 
1319   // Break down the array into individual dimensions.
1320   QualType Type1D = D.getType();
1321   while (getContext().getAsVariableArrayType(Type1D)) {
1322     auto VlaSize = getVLAElements1D(Type1D);
1323     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1324       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1325     else {
1326       // Generate a locally unique name for the size expression.
1327       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1328       SmallString<12> Buffer;
1329       StringRef NameRef = Name.toStringRef(Buffer);
1330       auto &Ident = getContext().Idents.getOwn(NameRef);
1331       VLAExprNames.push_back(&Ident);
1332       auto SizeExprAddr =
1333           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1334       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1335       Dimensions.emplace_back(SizeExprAddr.getPointer(),
1336                               Type1D.getUnqualifiedType());
1337     }
1338     Type1D = VlaSize.Type;
1339   }
1340 
1341   if (!EmitDebugInfo)
1342     return;
1343 
1344   // Register each dimension's size-expression with a DILocalVariable,
1345   // so that it can be used by CGDebugInfo when instantiating a DISubrange
1346   // to describe this array.
1347   unsigned NameIdx = 0;
1348   for (auto &VlaSize : Dimensions) {
1349     llvm::Metadata *MD;
1350     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1351       MD = llvm::ConstantAsMetadata::get(C);
1352     else {
1353       // Create an artificial VarDecl to generate debug info for.
1354       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1355       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1356       auto QT = getContext().getIntTypeForBitwidth(
1357           VlaExprTy->getScalarSizeInBits(), false);
1358       auto *ArtificialDecl = VarDecl::Create(
1359           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1360           D.getLocation(), D.getLocation(), NameIdent, QT,
1361           getContext().CreateTypeSourceInfo(QT), SC_Auto);
1362       ArtificialDecl->setImplicit();
1363 
1364       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1365                                          Builder);
1366     }
1367     assert(MD && "No Size expression debug node created");
1368     DI->registerVLASizeExpression(VlaSize.Type, MD);
1369   }
1370 }
1371 
1372 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1373 /// local variable.  Does not emit initialization or destruction.
1374 CodeGenFunction::AutoVarEmission
1375 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1376   QualType Ty = D.getType();
1377   assert(
1378       Ty.getAddressSpace() == LangAS::Default ||
1379       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1380 
1381   AutoVarEmission emission(D);
1382 
1383   bool isEscapingByRef = D.isEscapingByref();
1384   emission.IsEscapingByRef = isEscapingByRef;
1385 
1386   CharUnits alignment = getContext().getDeclAlign(&D);
1387 
1388   // If the type is variably-modified, emit all the VLA sizes for it.
1389   if (Ty->isVariablyModifiedType())
1390     EmitVariablyModifiedType(Ty);
1391 
1392   auto *DI = getDebugInfo();
1393   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1394                                  codegenoptions::LimitedDebugInfo;
1395 
1396   Address address = Address::invalid();
1397   Address AllocaAddr = Address::invalid();
1398   Address OpenMPLocalAddr =
1399       getLangOpts().OpenMP
1400           ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1401           : Address::invalid();
1402   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1403     address = OpenMPLocalAddr;
1404   } else if (Ty->isConstantSizeType()) {
1405     bool NRVO = getLangOpts().ElideConstructors &&
1406       D.isNRVOVariable();
1407 
1408     // If this value is an array or struct with a statically determinable
1409     // constant initializer, there are optimizations we can do.
1410     //
1411     // TODO: We should constant-evaluate the initializer of any variable,
1412     // as long as it is initialized by a constant expression. Currently,
1413     // isConstantInitializer produces wrong answers for structs with
1414     // reference or bitfield members, and a few other cases, and checking
1415     // for POD-ness protects us from some of these.
1416     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1417         (D.isConstexpr() ||
1418          ((Ty.isPODType(getContext()) ||
1419            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1420           D.getInit()->isConstantInitializer(getContext(), false)))) {
1421 
1422       // If the variable's a const type, and it's neither an NRVO
1423       // candidate nor a __block variable and has no mutable members,
1424       // emit it as a global instead.
1425       // Exception is if a variable is located in non-constant address space
1426       // in OpenCL.
1427       if ((!getLangOpts().OpenCL ||
1428            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1429           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1430            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1431         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1432 
1433         // Signal this condition to later callbacks.
1434         emission.Addr = Address::invalid();
1435         assert(emission.wasEmittedAsGlobal());
1436         return emission;
1437       }
1438 
1439       // Otherwise, tell the initialization code that we're in this case.
1440       emission.IsConstantAggregate = true;
1441     }
1442 
1443     // A normal fixed sized variable becomes an alloca in the entry block,
1444     // unless:
1445     // - it's an NRVO variable.
1446     // - we are compiling OpenMP and it's an OpenMP local variable.
1447     if (NRVO) {
1448       // The named return value optimization: allocate this variable in the
1449       // return slot, so that we can elide the copy when returning this
1450       // variable (C++0x [class.copy]p34).
1451       address = ReturnValue;
1452 
1453       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1454         const auto *RD = RecordTy->getDecl();
1455         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1456         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1457             RD->isNonTrivialToPrimitiveDestroy()) {
1458           // Create a flag that is used to indicate when the NRVO was applied
1459           // to this variable. Set it to zero to indicate that NRVO was not
1460           // applied.
1461           llvm::Value *Zero = Builder.getFalse();
1462           Address NRVOFlag =
1463             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1464           EnsureInsertPoint();
1465           Builder.CreateStore(Zero, NRVOFlag);
1466 
1467           // Record the NRVO flag for this variable.
1468           NRVOFlags[&D] = NRVOFlag.getPointer();
1469           emission.NRVOFlag = NRVOFlag.getPointer();
1470         }
1471       }
1472     } else {
1473       CharUnits allocaAlignment;
1474       llvm::Type *allocaTy;
1475       if (isEscapingByRef) {
1476         auto &byrefInfo = getBlockByrefInfo(&D);
1477         allocaTy = byrefInfo.Type;
1478         allocaAlignment = byrefInfo.ByrefAlignment;
1479       } else {
1480         allocaTy = ConvertTypeForMem(Ty);
1481         allocaAlignment = alignment;
1482       }
1483 
1484       // Create the alloca.  Note that we set the name separately from
1485       // building the instruction so that it's there even in no-asserts
1486       // builds.
1487       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1488                                  /*ArraySize=*/nullptr, &AllocaAddr);
1489 
1490       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1491       // the catch parameter starts in the catchpad instruction, and we can't
1492       // insert code in those basic blocks.
1493       bool IsMSCatchParam =
1494           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1495 
1496       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1497       // if we don't have a valid insertion point (?).
1498       if (HaveInsertPoint() && !IsMSCatchParam) {
1499         // If there's a jump into the lifetime of this variable, its lifetime
1500         // gets broken up into several regions in IR, which requires more work
1501         // to handle correctly. For now, just omit the intrinsics; this is a
1502         // rare case, and it's better to just be conservatively correct.
1503         // PR28267.
1504         //
1505         // We have to do this in all language modes if there's a jump past the
1506         // declaration. We also have to do it in C if there's a jump to an
1507         // earlier point in the current block because non-VLA lifetimes begin as
1508         // soon as the containing block is entered, not when its variables
1509         // actually come into scope; suppressing the lifetime annotations
1510         // completely in this case is unnecessarily pessimistic, but again, this
1511         // is rare.
1512         if (!Bypasses.IsBypassed(&D) &&
1513             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1514           uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1515           emission.SizeForLifetimeMarkers =
1516               EmitLifetimeStart(size, AllocaAddr.getPointer());
1517         }
1518       } else {
1519         assert(!emission.useLifetimeMarkers());
1520       }
1521     }
1522   } else {
1523     EnsureInsertPoint();
1524 
1525     if (!DidCallStackSave) {
1526       // Save the stack.
1527       Address Stack =
1528         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1529 
1530       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1531       llvm::Value *V = Builder.CreateCall(F);
1532       Builder.CreateStore(V, Stack);
1533 
1534       DidCallStackSave = true;
1535 
1536       // Push a cleanup block and restore the stack there.
1537       // FIXME: in general circumstances, this should be an EH cleanup.
1538       pushStackRestore(NormalCleanup, Stack);
1539     }
1540 
1541     auto VlaSize = getVLASize(Ty);
1542     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1543 
1544     // Allocate memory for the array.
1545     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1546                                &AllocaAddr);
1547 
1548     // If we have debug info enabled, properly describe the VLA dimensions for
1549     // this type by registering the vla size expression for each of the
1550     // dimensions.
1551     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1552   }
1553 
1554   setAddrOfLocalVar(&D, address);
1555   emission.Addr = address;
1556   emission.AllocaAddr = AllocaAddr;
1557 
1558   // Emit debug info for local var declaration.
1559   if (EmitDebugInfo && HaveInsertPoint()) {
1560     DI->setLocation(D.getLocation());
1561     (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1562   }
1563 
1564   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1565     EmitVarAnnotations(&D, address.getPointer());
1566 
1567   // Make sure we call @llvm.lifetime.end.
1568   if (emission.useLifetimeMarkers())
1569     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1570                                          emission.getOriginalAllocatedAddress(),
1571                                          emission.getSizeForLifetimeMarkers());
1572 
1573   return emission;
1574 }
1575 
1576 static bool isCapturedBy(const VarDecl &, const Expr *);
1577 
1578 /// Determines whether the given __block variable is potentially
1579 /// captured by the given statement.
1580 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1581   if (const Expr *E = dyn_cast<Expr>(S))
1582     return isCapturedBy(Var, E);
1583   for (const Stmt *SubStmt : S->children())
1584     if (isCapturedBy(Var, SubStmt))
1585       return true;
1586   return false;
1587 }
1588 
1589 /// Determines whether the given __block variable is potentially
1590 /// captured by the given expression.
1591 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1592   // Skip the most common kinds of expressions that make
1593   // hierarchy-walking expensive.
1594   E = E->IgnoreParenCasts();
1595 
1596   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1597     const BlockDecl *Block = BE->getBlockDecl();
1598     for (const auto &I : Block->captures()) {
1599       if (I.getVariable() == &Var)
1600         return true;
1601     }
1602 
1603     // No need to walk into the subexpressions.
1604     return false;
1605   }
1606 
1607   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1608     const CompoundStmt *CS = SE->getSubStmt();
1609     for (const auto *BI : CS->body())
1610       if (const auto *BIE = dyn_cast<Expr>(BI)) {
1611         if (isCapturedBy(Var, BIE))
1612           return true;
1613       }
1614       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1615           // special case declarations
1616           for (const auto *I : DS->decls()) {
1617               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1618                 const Expr *Init = VD->getInit();
1619                 if (Init && isCapturedBy(Var, Init))
1620                   return true;
1621               }
1622           }
1623       }
1624       else
1625         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1626         // Later, provide code to poke into statements for capture analysis.
1627         return true;
1628     return false;
1629   }
1630 
1631   for (const Stmt *SubStmt : E->children())
1632     if (isCapturedBy(Var, SubStmt))
1633       return true;
1634 
1635   return false;
1636 }
1637 
1638 /// Determine whether the given initializer is trivial in the sense
1639 /// that it requires no code to be generated.
1640 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1641   if (!Init)
1642     return true;
1643 
1644   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1645     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1646       if (Constructor->isTrivial() &&
1647           Constructor->isDefaultConstructor() &&
1648           !Construct->requiresZeroInitialization())
1649         return true;
1650 
1651   return false;
1652 }
1653 
1654 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1655   assert(emission.Variable && "emission was not valid!");
1656 
1657   // If this was emitted as a global constant, we're done.
1658   if (emission.wasEmittedAsGlobal()) return;
1659 
1660   const VarDecl &D = *emission.Variable;
1661   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1662   QualType type = D.getType();
1663 
1664   bool isVolatile = type.isVolatileQualified();
1665 
1666   // If this local has an initializer, emit it now.
1667   const Expr *Init = D.getInit();
1668 
1669   // If we are at an unreachable point, we don't need to emit the initializer
1670   // unless it contains a label.
1671   if (!HaveInsertPoint()) {
1672     if (!Init || !ContainsLabel(Init)) return;
1673     EnsureInsertPoint();
1674   }
1675 
1676   // Initialize the structure of a __block variable.
1677   if (emission.IsEscapingByRef)
1678     emitByrefStructureInit(emission);
1679 
1680   // Initialize the variable here if it doesn't have a initializer and it is a
1681   // C struct that is non-trivial to initialize or an array containing such a
1682   // struct.
1683   if (!Init &&
1684       type.isNonTrivialToPrimitiveDefaultInitialize() ==
1685           QualType::PDIK_Struct) {
1686     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1687     if (emission.IsEscapingByRef)
1688       drillIntoBlockVariable(*this, Dst, &D);
1689     defaultInitNonTrivialCStructVar(Dst);
1690     return;
1691   }
1692 
1693   // Check whether this is a byref variable that's potentially
1694   // captured and moved by its own initializer.  If so, we'll need to
1695   // emit the initializer first, then copy into the variable.
1696   bool capturedByInit =
1697       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1698 
1699   bool locIsByrefHeader = !capturedByInit;
1700   const Address Loc =
1701       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1702 
1703   // Note: constexpr already initializes everything correctly.
1704   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1705       (D.isConstexpr()
1706            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1707            : (D.getAttr<UninitializedAttr>()
1708                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1709                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1710 
1711   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1712     if (trivialAutoVarInit ==
1713         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1714       return;
1715 
1716     // Only initialize a __block's storage: we always initialize the header.
1717     if (emission.IsEscapingByRef && !locIsByrefHeader)
1718       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1719 
1720     CharUnits Size = getContext().getTypeSizeInChars(type);
1721     if (!Size.isZero()) {
1722       switch (trivialAutoVarInit) {
1723       case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1724         llvm_unreachable("Uninitialized handled above");
1725       case LangOptions::TrivialAutoVarInitKind::Zero:
1726         emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1727         break;
1728       case LangOptions::TrivialAutoVarInitKind::Pattern:
1729         emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1730         break;
1731       }
1732       return;
1733     }
1734 
1735     // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1736     // them, so emit a memcpy with the VLA size to initialize each element.
1737     // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1738     // will catch that code, but there exists code which generates zero-sized
1739     // VLAs. Be nice and initialize whatever they requested.
1740     const auto *VlaType = getContext().getAsVariableArrayType(type);
1741     if (!VlaType)
1742       return;
1743     auto VlaSize = getVLASize(VlaType);
1744     auto SizeVal = VlaSize.NumElts;
1745     CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1746     switch (trivialAutoVarInit) {
1747     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1748       llvm_unreachable("Uninitialized handled above");
1749 
1750     case LangOptions::TrivialAutoVarInitKind::Zero:
1751       if (!EltSize.isOne())
1752         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1753       Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1754                            isVolatile);
1755       break;
1756 
1757     case LangOptions::TrivialAutoVarInitKind::Pattern: {
1758       llvm::Type *ElTy = Loc.getElementType();
1759       llvm::Constant *Constant = constWithPadding(
1760           CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1761       CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1762       llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1763       llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1764       llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1765       llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1766           SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1767           "vla.iszerosized");
1768       Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1769       EmitBlock(SetupBB);
1770       if (!EltSize.isOne())
1771         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1772       llvm::Value *BaseSizeInChars =
1773           llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1774       Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1775       llvm::Value *End =
1776           Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1777       llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1778       EmitBlock(LoopBB);
1779       llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1780       Cur->addIncoming(Begin.getPointer(), OriginBB);
1781       CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1782       Builder.CreateMemCpy(Address(Cur, CurAlign),
1783                            createUnnamedGlobalForMemcpyFrom(
1784                                CGM, D, Builder, Constant, ConstantAlign),
1785                            BaseSizeInChars, isVolatile);
1786       llvm::Value *Next =
1787           Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1788       llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1789       Builder.CreateCondBr(Done, ContBB, LoopBB);
1790       Cur->addIncoming(Next, LoopBB);
1791       EmitBlock(ContBB);
1792     } break;
1793     }
1794   };
1795 
1796   if (isTrivialInitializer(Init)) {
1797     initializeWhatIsTechnicallyUninitialized(Loc);
1798     return;
1799   }
1800 
1801   llvm::Constant *constant = nullptr;
1802   if (emission.IsConstantAggregate ||
1803       D.mightBeUsableInConstantExpressions(getContext())) {
1804     assert(!capturedByInit && "constant init contains a capturing block?");
1805     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1806     if (constant && !constant->isZeroValue() &&
1807         (trivialAutoVarInit !=
1808          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1809       IsPattern isPattern =
1810           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1811               ? IsPattern::Yes
1812               : IsPattern::No;
1813       // C guarantees that brace-init with fewer initializers than members in
1814       // the aggregate will initialize the rest of the aggregate as-if it were
1815       // static initialization. In turn static initialization guarantees that
1816       // padding is initialized to zero bits. We could instead pattern-init if D
1817       // has any ImplicitValueInitExpr, but that seems to be unintuitive
1818       // behavior.
1819       constant = constWithPadding(CGM, IsPattern::No,
1820                                   replaceUndef(CGM, isPattern, constant));
1821     }
1822   }
1823 
1824   if (!constant) {
1825     initializeWhatIsTechnicallyUninitialized(Loc);
1826     LValue lv = MakeAddrLValue(Loc, type);
1827     lv.setNonGC(true);
1828     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1829   }
1830 
1831   if (!emission.IsConstantAggregate) {
1832     // For simple scalar/complex initialization, store the value directly.
1833     LValue lv = MakeAddrLValue(Loc, type);
1834     lv.setNonGC(true);
1835     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1836   }
1837 
1838   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1839   emitStoresForConstant(
1840       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1841       isVolatile, Builder, constant);
1842 }
1843 
1844 /// Emit an expression as an initializer for an object (variable, field, etc.)
1845 /// at the given location.  The expression is not necessarily the normal
1846 /// initializer for the object, and the address is not necessarily
1847 /// its normal location.
1848 ///
1849 /// \param init the initializing expression
1850 /// \param D the object to act as if we're initializing
1851 /// \param loc the address to initialize; its type is a pointer
1852 ///   to the LLVM mapping of the object's type
1853 /// \param alignment the alignment of the address
1854 /// \param capturedByInit true if \p D is a __block variable
1855 ///   whose address is potentially changed by the initializer
1856 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1857                                      LValue lvalue, bool capturedByInit) {
1858   QualType type = D->getType();
1859 
1860   if (type->isReferenceType()) {
1861     RValue rvalue = EmitReferenceBindingToExpr(init);
1862     if (capturedByInit)
1863       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1864     EmitStoreThroughLValue(rvalue, lvalue, true);
1865     return;
1866   }
1867   switch (getEvaluationKind(type)) {
1868   case TEK_Scalar:
1869     EmitScalarInit(init, D, lvalue, capturedByInit);
1870     return;
1871   case TEK_Complex: {
1872     ComplexPairTy complex = EmitComplexExpr(init);
1873     if (capturedByInit)
1874       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1875     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1876     return;
1877   }
1878   case TEK_Aggregate:
1879     if (type->isAtomicType()) {
1880       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1881     } else {
1882       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1883       if (isa<VarDecl>(D))
1884         Overlap = AggValueSlot::DoesNotOverlap;
1885       else if (auto *FD = dyn_cast<FieldDecl>(D))
1886         Overlap = overlapForFieldInit(FD);
1887       // TODO: how can we delay here if D is captured by its initializer?
1888       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1889                                               AggValueSlot::IsDestructed,
1890                                          AggValueSlot::DoesNotNeedGCBarriers,
1891                                               AggValueSlot::IsNotAliased,
1892                                               Overlap));
1893     }
1894     return;
1895   }
1896   llvm_unreachable("bad evaluation kind");
1897 }
1898 
1899 /// Enter a destroy cleanup for the given local variable.
1900 void CodeGenFunction::emitAutoVarTypeCleanup(
1901                             const CodeGenFunction::AutoVarEmission &emission,
1902                             QualType::DestructionKind dtorKind) {
1903   assert(dtorKind != QualType::DK_none);
1904 
1905   // Note that for __block variables, we want to destroy the
1906   // original stack object, not the possibly forwarded object.
1907   Address addr = emission.getObjectAddress(*this);
1908 
1909   const VarDecl *var = emission.Variable;
1910   QualType type = var->getType();
1911 
1912   CleanupKind cleanupKind = NormalAndEHCleanup;
1913   CodeGenFunction::Destroyer *destroyer = nullptr;
1914 
1915   switch (dtorKind) {
1916   case QualType::DK_none:
1917     llvm_unreachable("no cleanup for trivially-destructible variable");
1918 
1919   case QualType::DK_cxx_destructor:
1920     // If there's an NRVO flag on the emission, we need a different
1921     // cleanup.
1922     if (emission.NRVOFlag) {
1923       assert(!type->isArrayType());
1924       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1925       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1926                                                   emission.NRVOFlag);
1927       return;
1928     }
1929     break;
1930 
1931   case QualType::DK_objc_strong_lifetime:
1932     // Suppress cleanups for pseudo-strong variables.
1933     if (var->isARCPseudoStrong()) return;
1934 
1935     // Otherwise, consider whether to use an EH cleanup or not.
1936     cleanupKind = getARCCleanupKind();
1937 
1938     // Use the imprecise destroyer by default.
1939     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1940       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1941     break;
1942 
1943   case QualType::DK_objc_weak_lifetime:
1944     break;
1945 
1946   case QualType::DK_nontrivial_c_struct:
1947     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
1948     if (emission.NRVOFlag) {
1949       assert(!type->isArrayType());
1950       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1951                                                 emission.NRVOFlag, type);
1952       return;
1953     }
1954     break;
1955   }
1956 
1957   // If we haven't chosen a more specific destroyer, use the default.
1958   if (!destroyer) destroyer = getDestroyer(dtorKind);
1959 
1960   // Use an EH cleanup in array destructors iff the destructor itself
1961   // is being pushed as an EH cleanup.
1962   bool useEHCleanup = (cleanupKind & EHCleanup);
1963   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1964                                      useEHCleanup);
1965 }
1966 
1967 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1968   assert(emission.Variable && "emission was not valid!");
1969 
1970   // If this was emitted as a global constant, we're done.
1971   if (emission.wasEmittedAsGlobal()) return;
1972 
1973   // If we don't have an insertion point, we're done.  Sema prevents
1974   // us from jumping into any of these scopes anyway.
1975   if (!HaveInsertPoint()) return;
1976 
1977   const VarDecl &D = *emission.Variable;
1978 
1979   // Check the type for a cleanup.
1980   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1981     emitAutoVarTypeCleanup(emission, dtorKind);
1982 
1983   // In GC mode, honor objc_precise_lifetime.
1984   if (getLangOpts().getGC() != LangOptions::NonGC &&
1985       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1986     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1987   }
1988 
1989   // Handle the cleanup attribute.
1990   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1991     const FunctionDecl *FD = CA->getFunctionDecl();
1992 
1993     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1994     assert(F && "Could not find function!");
1995 
1996     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1997     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1998   }
1999 
2000   // If this is a block variable, call _Block_object_destroy
2001   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2002   // mode.
2003   if (emission.IsEscapingByRef &&
2004       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2005     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2006     if (emission.Variable->getType().isObjCGCWeak())
2007       Flags |= BLOCK_FIELD_IS_WEAK;
2008     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2009                       /*LoadBlockVarAddr*/ false,
2010                       cxxDestructorCanThrow(emission.Variable->getType()));
2011   }
2012 }
2013 
2014 CodeGenFunction::Destroyer *
2015 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2016   switch (kind) {
2017   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2018   case QualType::DK_cxx_destructor:
2019     return destroyCXXObject;
2020   case QualType::DK_objc_strong_lifetime:
2021     return destroyARCStrongPrecise;
2022   case QualType::DK_objc_weak_lifetime:
2023     return destroyARCWeak;
2024   case QualType::DK_nontrivial_c_struct:
2025     return destroyNonTrivialCStruct;
2026   }
2027   llvm_unreachable("Unknown DestructionKind");
2028 }
2029 
2030 /// pushEHDestroy - Push the standard destructor for the given type as
2031 /// an EH-only cleanup.
2032 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2033                                     Address addr, QualType type) {
2034   assert(dtorKind && "cannot push destructor for trivial type");
2035   assert(needsEHCleanup(dtorKind));
2036 
2037   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2038 }
2039 
2040 /// pushDestroy - Push the standard destructor for the given type as
2041 /// at least a normal cleanup.
2042 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2043                                   Address addr, QualType type) {
2044   assert(dtorKind && "cannot push destructor for trivial type");
2045 
2046   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2047   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2048               cleanupKind & EHCleanup);
2049 }
2050 
2051 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2052                                   QualType type, Destroyer *destroyer,
2053                                   bool useEHCleanupForArray) {
2054   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2055                                      destroyer, useEHCleanupForArray);
2056 }
2057 
2058 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2059   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2060 }
2061 
2062 void CodeGenFunction::pushLifetimeExtendedDestroy(
2063     CleanupKind cleanupKind, Address addr, QualType type,
2064     Destroyer *destroyer, bool useEHCleanupForArray) {
2065   // Push an EH-only cleanup for the object now.
2066   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2067   // around in case a temporary's destructor throws an exception.
2068   if (cleanupKind & EHCleanup)
2069     EHStack.pushCleanup<DestroyObject>(
2070         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2071         destroyer, useEHCleanupForArray);
2072 
2073   // Remember that we need to push a full cleanup for the object at the
2074   // end of the full-expression.
2075   pushCleanupAfterFullExpr<DestroyObject>(
2076       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2077 }
2078 
2079 /// emitDestroy - Immediately perform the destruction of the given
2080 /// object.
2081 ///
2082 /// \param addr - the address of the object; a type*
2083 /// \param type - the type of the object; if an array type, all
2084 ///   objects are destroyed in reverse order
2085 /// \param destroyer - the function to call to destroy individual
2086 ///   elements
2087 /// \param useEHCleanupForArray - whether an EH cleanup should be
2088 ///   used when destroying array elements, in case one of the
2089 ///   destructions throws an exception
2090 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2091                                   Destroyer *destroyer,
2092                                   bool useEHCleanupForArray) {
2093   const ArrayType *arrayType = getContext().getAsArrayType(type);
2094   if (!arrayType)
2095     return destroyer(*this, addr, type);
2096 
2097   llvm::Value *length = emitArrayLength(arrayType, type, addr);
2098 
2099   CharUnits elementAlign =
2100     addr.getAlignment()
2101         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2102 
2103   // Normally we have to check whether the array is zero-length.
2104   bool checkZeroLength = true;
2105 
2106   // But if the array length is constant, we can suppress that.
2107   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2108     // ...and if it's constant zero, we can just skip the entire thing.
2109     if (constLength->isZero()) return;
2110     checkZeroLength = false;
2111   }
2112 
2113   llvm::Value *begin = addr.getPointer();
2114   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
2115   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2116                    checkZeroLength, useEHCleanupForArray);
2117 }
2118 
2119 /// emitArrayDestroy - Destroys all the elements of the given array,
2120 /// beginning from last to first.  The array cannot be zero-length.
2121 ///
2122 /// \param begin - a type* denoting the first element of the array
2123 /// \param end - a type* denoting one past the end of the array
2124 /// \param elementType - the element type of the array
2125 /// \param destroyer - the function to call to destroy elements
2126 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2127 ///   the remaining elements in case the destruction of a single
2128 ///   element throws
2129 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2130                                        llvm::Value *end,
2131                                        QualType elementType,
2132                                        CharUnits elementAlign,
2133                                        Destroyer *destroyer,
2134                                        bool checkZeroLength,
2135                                        bool useEHCleanup) {
2136   assert(!elementType->isArrayType());
2137 
2138   // The basic structure here is a do-while loop, because we don't
2139   // need to check for the zero-element case.
2140   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2141   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2142 
2143   if (checkZeroLength) {
2144     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2145                                                 "arraydestroy.isempty");
2146     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2147   }
2148 
2149   // Enter the loop body, making that address the current address.
2150   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2151   EmitBlock(bodyBB);
2152   llvm::PHINode *elementPast =
2153     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2154   elementPast->addIncoming(end, entryBB);
2155 
2156   // Shift the address back by one element.
2157   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2158   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2159                                                    "arraydestroy.element");
2160 
2161   if (useEHCleanup)
2162     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2163                                    destroyer);
2164 
2165   // Perform the actual destruction there.
2166   destroyer(*this, Address(element, elementAlign), elementType);
2167 
2168   if (useEHCleanup)
2169     PopCleanupBlock();
2170 
2171   // Check whether we've reached the end.
2172   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2173   Builder.CreateCondBr(done, doneBB, bodyBB);
2174   elementPast->addIncoming(element, Builder.GetInsertBlock());
2175 
2176   // Done.
2177   EmitBlock(doneBB);
2178 }
2179 
2180 /// Perform partial array destruction as if in an EH cleanup.  Unlike
2181 /// emitArrayDestroy, the element type here may still be an array type.
2182 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2183                                     llvm::Value *begin, llvm::Value *end,
2184                                     QualType type, CharUnits elementAlign,
2185                                     CodeGenFunction::Destroyer *destroyer) {
2186   // If the element type is itself an array, drill down.
2187   unsigned arrayDepth = 0;
2188   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2189     // VLAs don't require a GEP index to walk into.
2190     if (!isa<VariableArrayType>(arrayType))
2191       arrayDepth++;
2192     type = arrayType->getElementType();
2193   }
2194 
2195   if (arrayDepth) {
2196     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2197 
2198     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2199     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2200     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
2201   }
2202 
2203   // Destroy the array.  We don't ever need an EH cleanup because we
2204   // assume that we're in an EH cleanup ourselves, so a throwing
2205   // destructor causes an immediate terminate.
2206   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2207                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2208 }
2209 
2210 namespace {
2211   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2212   /// array destroy where the end pointer is regularly determined and
2213   /// does not need to be loaded from a local.
2214   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2215     llvm::Value *ArrayBegin;
2216     llvm::Value *ArrayEnd;
2217     QualType ElementType;
2218     CodeGenFunction::Destroyer *Destroyer;
2219     CharUnits ElementAlign;
2220   public:
2221     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2222                                QualType elementType, CharUnits elementAlign,
2223                                CodeGenFunction::Destroyer *destroyer)
2224       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2225         ElementType(elementType), Destroyer(destroyer),
2226         ElementAlign(elementAlign) {}
2227 
2228     void Emit(CodeGenFunction &CGF, Flags flags) override {
2229       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2230                               ElementType, ElementAlign, Destroyer);
2231     }
2232   };
2233 
2234   /// IrregularPartialArrayDestroy - a cleanup which performs a
2235   /// partial array destroy where the end pointer is irregularly
2236   /// determined and must be loaded from a local.
2237   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2238     llvm::Value *ArrayBegin;
2239     Address ArrayEndPointer;
2240     QualType ElementType;
2241     CodeGenFunction::Destroyer *Destroyer;
2242     CharUnits ElementAlign;
2243   public:
2244     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2245                                  Address arrayEndPointer,
2246                                  QualType elementType,
2247                                  CharUnits elementAlign,
2248                                  CodeGenFunction::Destroyer *destroyer)
2249       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2250         ElementType(elementType), Destroyer(destroyer),
2251         ElementAlign(elementAlign) {}
2252 
2253     void Emit(CodeGenFunction &CGF, Flags flags) override {
2254       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2255       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2256                               ElementType, ElementAlign, Destroyer);
2257     }
2258   };
2259 } // end anonymous namespace
2260 
2261 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2262 /// already-constructed elements of the given array.  The cleanup
2263 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2264 ///
2265 /// \param elementType - the immediate element type of the array;
2266 ///   possibly still an array type
2267 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2268                                                        Address arrayEndPointer,
2269                                                        QualType elementType,
2270                                                        CharUnits elementAlign,
2271                                                        Destroyer *destroyer) {
2272   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2273                                                     arrayBegin, arrayEndPointer,
2274                                                     elementType, elementAlign,
2275                                                     destroyer);
2276 }
2277 
2278 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2279 /// already-constructed elements of the given array.  The cleanup
2280 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2281 ///
2282 /// \param elementType - the immediate element type of the array;
2283 ///   possibly still an array type
2284 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2285                                                      llvm::Value *arrayEnd,
2286                                                      QualType elementType,
2287                                                      CharUnits elementAlign,
2288                                                      Destroyer *destroyer) {
2289   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2290                                                   arrayBegin, arrayEnd,
2291                                                   elementType, elementAlign,
2292                                                   destroyer);
2293 }
2294 
2295 /// Lazily declare the @llvm.lifetime.start intrinsic.
2296 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2297   if (LifetimeStartFn)
2298     return LifetimeStartFn;
2299   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2300     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2301   return LifetimeStartFn;
2302 }
2303 
2304 /// Lazily declare the @llvm.lifetime.end intrinsic.
2305 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2306   if (LifetimeEndFn)
2307     return LifetimeEndFn;
2308   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2309     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2310   return LifetimeEndFn;
2311 }
2312 
2313 namespace {
2314   /// A cleanup to perform a release of an object at the end of a
2315   /// function.  This is used to balance out the incoming +1 of a
2316   /// ns_consumed argument when we can't reasonably do that just by
2317   /// not doing the initial retain for a __block argument.
2318   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2319     ConsumeARCParameter(llvm::Value *param,
2320                         ARCPreciseLifetime_t precise)
2321       : Param(param), Precise(precise) {}
2322 
2323     llvm::Value *Param;
2324     ARCPreciseLifetime_t Precise;
2325 
2326     void Emit(CodeGenFunction &CGF, Flags flags) override {
2327       CGF.EmitARCRelease(Param, Precise);
2328     }
2329   };
2330 } // end anonymous namespace
2331 
2332 /// Emit an alloca (or GlobalValue depending on target)
2333 /// for the specified parameter and set up LocalDeclMap.
2334 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2335                                    unsigned ArgNo) {
2336   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2337   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2338          "Invalid argument to EmitParmDecl");
2339 
2340   Arg.getAnyValue()->setName(D.getName());
2341 
2342   QualType Ty = D.getType();
2343 
2344   // Use better IR generation for certain implicit parameters.
2345   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2346     // The only implicit argument a block has is its literal.
2347     // This may be passed as an inalloca'ed value on Windows x86.
2348     if (BlockInfo) {
2349       llvm::Value *V = Arg.isIndirect()
2350                            ? Builder.CreateLoad(Arg.getIndirectAddress())
2351                            : Arg.getDirectValue();
2352       setBlockContextParameter(IPD, ArgNo, V);
2353       return;
2354     }
2355   }
2356 
2357   Address DeclPtr = Address::invalid();
2358   bool DoStore = false;
2359   bool IsScalar = hasScalarEvaluationKind(Ty);
2360   // If we already have a pointer to the argument, reuse the input pointer.
2361   if (Arg.isIndirect()) {
2362     DeclPtr = Arg.getIndirectAddress();
2363     // If we have a prettier pointer type at this point, bitcast to that.
2364     unsigned AS = DeclPtr.getType()->getAddressSpace();
2365     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2366     if (DeclPtr.getType() != IRTy)
2367       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2368     // Indirect argument is in alloca address space, which may be different
2369     // from the default address space.
2370     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2371     auto *V = DeclPtr.getPointer();
2372     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2373     auto DestLangAS =
2374         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2375     if (SrcLangAS != DestLangAS) {
2376       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2377              CGM.getDataLayout().getAllocaAddrSpace());
2378       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2379       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2380       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2381                             *this, V, SrcLangAS, DestLangAS, T, true),
2382                         DeclPtr.getAlignment());
2383     }
2384 
2385     // Push a destructor cleanup for this parameter if the ABI requires it.
2386     // Don't push a cleanup in a thunk for a method that will also emit a
2387     // cleanup.
2388     if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2389         Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2390       if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2391         assert((DtorKind == QualType::DK_cxx_destructor ||
2392                 DtorKind == QualType::DK_nontrivial_c_struct) &&
2393                "unexpected destructor type");
2394         pushDestroy(DtorKind, DeclPtr, Ty);
2395         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2396             EHStack.stable_begin();
2397       }
2398     }
2399   } else {
2400     // Check if the parameter address is controlled by OpenMP runtime.
2401     Address OpenMPLocalAddr =
2402         getLangOpts().OpenMP
2403             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2404             : Address::invalid();
2405     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2406       DeclPtr = OpenMPLocalAddr;
2407     } else {
2408       // Otherwise, create a temporary to hold the value.
2409       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2410                               D.getName() + ".addr");
2411     }
2412     DoStore = true;
2413   }
2414 
2415   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2416 
2417   LValue lv = MakeAddrLValue(DeclPtr, Ty);
2418   if (IsScalar) {
2419     Qualifiers qs = Ty.getQualifiers();
2420     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2421       // We honor __attribute__((ns_consumed)) for types with lifetime.
2422       // For __strong, it's handled by just skipping the initial retain;
2423       // otherwise we have to balance out the initial +1 with an extra
2424       // cleanup to do the release at the end of the function.
2425       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2426 
2427       // If a parameter is pseudo-strong then we can omit the implicit retain.
2428       if (D.isARCPseudoStrong()) {
2429         assert(lt == Qualifiers::OCL_Strong &&
2430                "pseudo-strong variable isn't strong?");
2431         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2432         lt = Qualifiers::OCL_ExplicitNone;
2433       }
2434 
2435       // Load objects passed indirectly.
2436       if (Arg.isIndirect() && !ArgVal)
2437         ArgVal = Builder.CreateLoad(DeclPtr);
2438 
2439       if (lt == Qualifiers::OCL_Strong) {
2440         if (!isConsumed) {
2441           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2442             // use objc_storeStrong(&dest, value) for retaining the
2443             // object. But first, store a null into 'dest' because
2444             // objc_storeStrong attempts to release its old value.
2445             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2446             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2447             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
2448             DoStore = false;
2449           }
2450           else
2451           // Don't use objc_retainBlock for block pointers, because we
2452           // don't want to Block_copy something just because we got it
2453           // as a parameter.
2454             ArgVal = EmitARCRetainNonBlock(ArgVal);
2455         }
2456       } else {
2457         // Push the cleanup for a consumed parameter.
2458         if (isConsumed) {
2459           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2460                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2461           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2462                                                    precise);
2463         }
2464 
2465         if (lt == Qualifiers::OCL_Weak) {
2466           EmitARCInitWeak(DeclPtr, ArgVal);
2467           DoStore = false; // The weak init is a store, no need to do two.
2468         }
2469       }
2470 
2471       // Enter the cleanup scope.
2472       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2473     }
2474   }
2475 
2476   // Store the initial value into the alloca.
2477   if (DoStore)
2478     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2479 
2480   setAddrOfLocalVar(&D, DeclPtr);
2481 
2482   // Emit debug info for param declaration.
2483   if (CGDebugInfo *DI = getDebugInfo()) {
2484     if (CGM.getCodeGenOpts().getDebugInfo() >=
2485         codegenoptions::LimitedDebugInfo) {
2486       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2487     }
2488   }
2489 
2490   if (D.hasAttr<AnnotateAttr>())
2491     EmitVarAnnotations(&D, DeclPtr.getPointer());
2492 
2493   // We can only check return value nullability if all arguments to the
2494   // function satisfy their nullability preconditions. This makes it necessary
2495   // to emit null checks for args in the function body itself.
2496   if (requiresReturnValueNullabilityCheck()) {
2497     auto Nullability = Ty->getNullability(getContext());
2498     if (Nullability && *Nullability == NullabilityKind::NonNull) {
2499       SanitizerScope SanScope(this);
2500       RetValNullabilityPrecondition =
2501           Builder.CreateAnd(RetValNullabilityPrecondition,
2502                             Builder.CreateIsNotNull(Arg.getAnyValue()));
2503     }
2504   }
2505 }
2506 
2507 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2508                                             CodeGenFunction *CGF) {
2509   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2510     return;
2511   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2512 }
2513 
2514 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2515                                             CodeGenFunction *CGF) {
2516   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2517     return;
2518   // FIXME: need to implement mapper code generation
2519 }
2520 
2521 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2522   getOpenMPRuntime().checkArchForUnifiedAddressing(D);
2523 }
2524