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