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