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