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