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