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