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