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     enterFullExpression(fe);
767     init = fe->getSubExpr();
768   }
769   CodeGenFunction::RunCleanupsScope Scope(*this);
770 
771   // We have to maintain the illusion that the variable is
772   // zero-initialized.  If the variable might be accessed in its
773   // initializer, zero-initialize before running the initializer, then
774   // actually perform the initialization with an assign.
775   bool accessedByInit = false;
776   if (lifetime != Qualifiers::OCL_ExplicitNone)
777     accessedByInit = (capturedByInit || isAccessedBy(D, init));
778   if (accessedByInit) {
779     LValue tempLV = lvalue;
780     // Drill down to the __block object if necessary.
781     if (capturedByInit) {
782       // We can use a simple GEP for this because it can't have been
783       // moved yet.
784       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
785                                               cast<VarDecl>(D),
786                                               /*follow*/ false));
787     }
788 
789     auto ty =
790         cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
791     llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
792 
793     // If __weak, we want to use a barrier under certain conditions.
794     if (lifetime == Qualifiers::OCL_Weak)
795       EmitARCInitWeak(tempLV.getAddress(*this), zero);
796 
797     // Otherwise just do a simple store.
798     else
799       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
800   }
801 
802   // Emit the initializer.
803   llvm::Value *value = nullptr;
804 
805   switch (lifetime) {
806   case Qualifiers::OCL_None:
807     llvm_unreachable("present but none");
808 
809   case Qualifiers::OCL_Strong: {
810     if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
811       value = EmitARCRetainScalarExpr(init);
812       break;
813     }
814     // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
815     // that we omit the retain, and causes non-autoreleased return values to be
816     // immediately released.
817     LLVM_FALLTHROUGH;
818   }
819 
820   case Qualifiers::OCL_ExplicitNone:
821     value = EmitARCUnsafeUnretainedScalarExpr(init);
822     break;
823 
824   case Qualifiers::OCL_Weak: {
825     // If it's not accessed by the initializer, try to emit the
826     // initialization with a copy or move.
827     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
828       return;
829     }
830 
831     // No way to optimize a producing initializer into this.  It's not
832     // worth optimizing for, because the value will immediately
833     // disappear in the common case.
834     value = EmitScalarExpr(init);
835 
836     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
837     if (accessedByInit)
838       EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
839     else
840       EmitARCInitWeak(lvalue.getAddress(*this), value);
841     return;
842   }
843 
844   case Qualifiers::OCL_Autoreleasing:
845     value = EmitARCRetainAutoreleaseScalarExpr(init);
846     break;
847   }
848 
849   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
850 
851   EmitNullabilityCheck(lvalue, value, init->getExprLoc());
852 
853   // If the variable might have been accessed by its initializer, we
854   // might have to initialize with a barrier.  We have to do this for
855   // both __weak and __strong, but __weak got filtered out above.
856   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
857     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
858     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
859     EmitARCRelease(oldValue, ARCImpreciseLifetime);
860     return;
861   }
862 
863   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
864 }
865 
866 /// Decide whether we can emit the non-zero parts of the specified initializer
867 /// with equal or fewer than NumStores scalar stores.
868 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
869                                                unsigned &NumStores) {
870   // Zero and Undef never requires any extra stores.
871   if (isa<llvm::ConstantAggregateZero>(Init) ||
872       isa<llvm::ConstantPointerNull>(Init) ||
873       isa<llvm::UndefValue>(Init))
874     return true;
875   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
876       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
877       isa<llvm::ConstantExpr>(Init))
878     return Init->isNullValue() || NumStores--;
879 
880   // See if we can emit each element.
881   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
882     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
883       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
884       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
885         return false;
886     }
887     return true;
888   }
889 
890   if (llvm::ConstantDataSequential *CDS =
891         dyn_cast<llvm::ConstantDataSequential>(Init)) {
892     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
893       llvm::Constant *Elt = CDS->getElementAsConstant(i);
894       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
895         return false;
896     }
897     return true;
898   }
899 
900   // Anything else is hard and scary.
901   return false;
902 }
903 
904 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
905 /// the scalar stores that would be required.
906 static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
907                                         llvm::Constant *Init, Address Loc,
908                                         bool isVolatile, CGBuilderTy &Builder) {
909   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
910          "called emitStoresForInitAfterBZero for zero or undef value.");
911 
912   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
913       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
914       isa<llvm::ConstantExpr>(Init)) {
915     Builder.CreateStore(Init, Loc, isVolatile);
916     return;
917   }
918 
919   if (llvm::ConstantDataSequential *CDS =
920           dyn_cast<llvm::ConstantDataSequential>(Init)) {
921     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
922       llvm::Constant *Elt = CDS->getElementAsConstant(i);
923 
924       // If necessary, get a pointer to the element and emit it.
925       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
926         emitStoresForInitAfterBZero(
927             CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
928             Builder);
929     }
930     return;
931   }
932 
933   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
934          "Unknown value type!");
935 
936   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
937     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
938 
939     // If necessary, get a pointer to the element and emit it.
940     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
941       emitStoresForInitAfterBZero(CGM, Elt,
942                                   Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
943                                   isVolatile, Builder);
944   }
945 }
946 
947 /// Decide whether we should use bzero plus some stores to initialize a local
948 /// variable instead of using a memcpy from a constant global.  It is beneficial
949 /// to use bzero if the global is all zeros, or mostly zeros and large.
950 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
951                                                  uint64_t GlobalSize) {
952   // If a global is all zeros, always use a bzero.
953   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
954 
955   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
956   // do it if it will require 6 or fewer scalar stores.
957   // TODO: Should budget depends on the size?  Avoiding a large global warrants
958   // plopping in more stores.
959   unsigned StoreBudget = 6;
960   uint64_t SizeLimit = 32;
961 
962   return GlobalSize > SizeLimit &&
963          canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
964 }
965 
966 /// Decide whether we should use memset to initialize a local variable instead
967 /// of using a memcpy from a constant global. Assumes we've already decided to
968 /// not user bzero.
969 /// FIXME We could be more clever, as we are for bzero above, and generate
970 ///       memset followed by stores. It's unclear that's worth the effort.
971 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
972                                                 uint64_t GlobalSize,
973                                                 const llvm::DataLayout &DL) {
974   uint64_t SizeLimit = 32;
975   if (GlobalSize <= SizeLimit)
976     return nullptr;
977   return llvm::isBytewiseValue(Init, DL);
978 }
979 
980 /// Decide whether we want to split a constant structure or array store into a
981 /// sequence of its fields' stores. This may cost us code size and compilation
982 /// speed, but plays better with store optimizations.
983 static bool shouldSplitConstantStore(CodeGenModule &CGM,
984                                      uint64_t GlobalByteSize) {
985   // Don't break things that occupy more than one cacheline.
986   uint64_t ByteSizeLimit = 64;
987   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
988     return false;
989   if (GlobalByteSize <= ByteSizeLimit)
990     return true;
991   return false;
992 }
993 
994 enum class IsPattern { No, Yes };
995 
996 /// Generate a constant filled with either a pattern or zeroes.
997 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
998                                         llvm::Type *Ty) {
999   if (isPattern == IsPattern::Yes)
1000     return initializationPatternFor(CGM, Ty);
1001   else
1002     return llvm::Constant::getNullValue(Ty);
1003 }
1004 
1005 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1006                                         llvm::Constant *constant);
1007 
1008 /// Helper function for constWithPadding() to deal with padding in structures.
1009 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1010                                               IsPattern isPattern,
1011                                               llvm::StructType *STy,
1012                                               llvm::Constant *constant) {
1013   const llvm::DataLayout &DL = CGM.getDataLayout();
1014   const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1015   llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1016   unsigned SizeSoFar = 0;
1017   SmallVector<llvm::Constant *, 8> Values;
1018   bool NestedIntact = true;
1019   for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1020     unsigned CurOff = Layout->getElementOffset(i);
1021     if (SizeSoFar < CurOff) {
1022       assert(!STy->isPacked());
1023       auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1024       Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1025     }
1026     llvm::Constant *CurOp;
1027     if (constant->isZeroValue())
1028       CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1029     else
1030       CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1031     auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1032     if (CurOp != NewOp)
1033       NestedIntact = false;
1034     Values.push_back(NewOp);
1035     SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1036   }
1037   unsigned TotalSize = Layout->getSizeInBytes();
1038   if (SizeSoFar < TotalSize) {
1039     auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1040     Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1041   }
1042   if (NestedIntact && Values.size() == STy->getNumElements())
1043     return constant;
1044   return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1045 }
1046 
1047 /// Replace all padding bytes in a given constant with either a pattern byte or
1048 /// 0x00.
1049 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1050                                         llvm::Constant *constant) {
1051   llvm::Type *OrigTy = constant->getType();
1052   if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1053     return constStructWithPadding(CGM, isPattern, STy, constant);
1054   if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1055     llvm::SmallVector<llvm::Constant *, 8> Values;
1056     uint64_t Size = ArrayTy->getNumElements();
1057     if (!Size)
1058       return constant;
1059     llvm::Type *ElemTy = ArrayTy->getElementType();
1060     bool ZeroInitializer = constant->isNullValue();
1061     llvm::Constant *OpValue, *PaddedOp;
1062     if (ZeroInitializer) {
1063       OpValue = llvm::Constant::getNullValue(ElemTy);
1064       PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1065     }
1066     for (unsigned Op = 0; Op != Size; ++Op) {
1067       if (!ZeroInitializer) {
1068         OpValue = constant->getAggregateElement(Op);
1069         PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1070       }
1071       Values.push_back(PaddedOp);
1072     }
1073     auto *NewElemTy = Values[0]->getType();
1074     if (NewElemTy == ElemTy)
1075       return constant;
1076     auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1077     return llvm::ConstantArray::get(NewArrayTy, Values);
1078   }
1079   // FIXME: Add handling for tail padding in vectors. Vectors don't
1080   // have padding between or inside elements, but the total amount of
1081   // data can be less than the allocated size.
1082   return constant;
1083 }
1084 
1085 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1086                                                llvm::Constant *Constant,
1087                                                CharUnits Align) {
1088   auto FunctionName = [&](const DeclContext *DC) -> std::string {
1089     if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1090       if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1091         return CC->getNameAsString();
1092       if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1093         return CD->getNameAsString();
1094       return std::string(getMangledName(FD));
1095     } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1096       return OM->getNameAsString();
1097     } else if (isa<BlockDecl>(DC)) {
1098       return "<block>";
1099     } else if (isa<CapturedDecl>(DC)) {
1100       return "<captured>";
1101     } else {
1102       llvm_unreachable("expected a function or method");
1103     }
1104   };
1105 
1106   // Form a simple per-variable cache of these values in case we find we
1107   // want to reuse them.
1108   llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1109   if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1110     auto *Ty = Constant->getType();
1111     bool isConstant = true;
1112     llvm::GlobalVariable *InsertBefore = nullptr;
1113     unsigned AS =
1114         getContext().getTargetAddressSpace(getStringLiteralAddressSpace());
1115     std::string Name;
1116     if (D.hasGlobalStorage())
1117       Name = getMangledName(&D).str() + ".const";
1118     else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1119       Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1120     else
1121       llvm_unreachable("local variable has no parent function or method");
1122     llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1123         getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1124         Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1125     GV->setAlignment(Align.getAsAlign());
1126     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1127     CacheEntry = GV;
1128   } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
1129     CacheEntry->setAlignment(Align.getAsAlign());
1130   }
1131 
1132   return Address(CacheEntry, Align);
1133 }
1134 
1135 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1136                                                 const VarDecl &D,
1137                                                 CGBuilderTy &Builder,
1138                                                 llvm::Constant *Constant,
1139                                                 CharUnits Align) {
1140   Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1141   llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1142                                                    SrcPtr.getAddressSpace());
1143   if (SrcPtr.getType() != BP)
1144     SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1145   return SrcPtr;
1146 }
1147 
1148 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1149                                   Address Loc, bool isVolatile,
1150                                   CGBuilderTy &Builder,
1151                                   llvm::Constant *constant) {
1152   auto *Ty = constant->getType();
1153   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1154   if (!ConstantSize)
1155     return;
1156 
1157   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1158                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1159   if (canDoSingleStore) {
1160     Builder.CreateStore(constant, Loc, isVolatile);
1161     return;
1162   }
1163 
1164   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1165 
1166   // If the initializer is all or mostly the same, codegen with bzero / memset
1167   // then do a few stores afterward.
1168   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1169     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), SizeVal,
1170                          isVolatile);
1171 
1172     bool valueAlreadyCorrect =
1173         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1174     if (!valueAlreadyCorrect) {
1175       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1176       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1177     }
1178     return;
1179   }
1180 
1181   // If the initializer is a repeated byte pattern, use memset.
1182   llvm::Value *Pattern =
1183       shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1184   if (Pattern) {
1185     uint64_t Value = 0x00;
1186     if (!isa<llvm::UndefValue>(Pattern)) {
1187       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1188       assert(AP.getBitWidth() <= 8);
1189       Value = AP.getLimitedValue();
1190     }
1191     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal,
1192                          isVolatile);
1193     return;
1194   }
1195 
1196   // If the initializer is small, use a handful of stores.
1197   if (shouldSplitConstantStore(CGM, ConstantSize)) {
1198     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1199       // FIXME: handle the case when STy != Loc.getElementType().
1200       if (STy == Loc.getElementType()) {
1201         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1202           Address EltPtr = Builder.CreateStructGEP(Loc, i);
1203           emitStoresForConstant(
1204               CGM, D, EltPtr, isVolatile, Builder,
1205               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1206         }
1207         return;
1208       }
1209     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1210       // FIXME: handle the case when ATy != Loc.getElementType().
1211       if (ATy == Loc.getElementType()) {
1212         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1213           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1214           emitStoresForConstant(
1215               CGM, D, EltPtr, isVolatile, Builder,
1216               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1217         }
1218         return;
1219       }
1220     }
1221   }
1222 
1223   // Copy from a global.
1224   Builder.CreateMemCpy(Loc,
1225                        createUnnamedGlobalForMemcpyFrom(
1226                            CGM, D, Builder, constant, Loc.getAlignment()),
1227                        SizeVal, isVolatile);
1228 }
1229 
1230 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1231                                   Address Loc, bool isVolatile,
1232                                   CGBuilderTy &Builder) {
1233   llvm::Type *ElTy = Loc.getElementType();
1234   llvm::Constant *constant =
1235       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1236   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1237 }
1238 
1239 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1240                                      Address Loc, bool isVolatile,
1241                                      CGBuilderTy &Builder) {
1242   llvm::Type *ElTy = Loc.getElementType();
1243   llvm::Constant *constant = constWithPadding(
1244       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1245   assert(!isa<llvm::UndefValue>(constant));
1246   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1247 }
1248 
1249 static bool containsUndef(llvm::Constant *constant) {
1250   auto *Ty = constant->getType();
1251   if (isa<llvm::UndefValue>(constant))
1252     return true;
1253   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1254     for (llvm::Use &Op : constant->operands())
1255       if (containsUndef(cast<llvm::Constant>(Op)))
1256         return true;
1257   return false;
1258 }
1259 
1260 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1261                                     llvm::Constant *constant) {
1262   auto *Ty = constant->getType();
1263   if (isa<llvm::UndefValue>(constant))
1264     return patternOrZeroFor(CGM, isPattern, Ty);
1265   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1266     return constant;
1267   if (!containsUndef(constant))
1268     return constant;
1269   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1270   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1271     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1272     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1273   }
1274   if (Ty->isStructTy())
1275     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1276   if (Ty->isArrayTy())
1277     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1278   assert(Ty->isVectorTy());
1279   return llvm::ConstantVector::get(Values);
1280 }
1281 
1282 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1283 /// variable declaration with auto, register, or no storage class specifier.
1284 /// These turn into simple stack objects, or GlobalValues depending on target.
1285 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1286   AutoVarEmission emission = EmitAutoVarAlloca(D);
1287   EmitAutoVarInit(emission);
1288   EmitAutoVarCleanups(emission);
1289 }
1290 
1291 /// Emit a lifetime.begin marker if some criteria are satisfied.
1292 /// \return a pointer to the temporary size Value if a marker was emitted, null
1293 /// otherwise
1294 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1295                                                 llvm::Value *Addr) {
1296   if (!ShouldEmitLifetimeMarkers)
1297     return nullptr;
1298 
1299   assert(Addr->getType()->getPointerAddressSpace() ==
1300              CGM.getDataLayout().getAllocaAddrSpace() &&
1301          "Pointer should be in alloca address space");
1302   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1303   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1304   llvm::CallInst *C =
1305       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1306   C->setDoesNotThrow();
1307   return SizeV;
1308 }
1309 
1310 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1311   assert(Addr->getType()->getPointerAddressSpace() ==
1312              CGM.getDataLayout().getAllocaAddrSpace() &&
1313          "Pointer should be in alloca address space");
1314   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1315   llvm::CallInst *C =
1316       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1317   C->setDoesNotThrow();
1318 }
1319 
1320 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1321     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1322   // For each dimension stores its QualType and corresponding
1323   // size-expression Value.
1324   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1325   SmallVector<IdentifierInfo *, 4> VLAExprNames;
1326 
1327   // Break down the array into individual dimensions.
1328   QualType Type1D = D.getType();
1329   while (getContext().getAsVariableArrayType(Type1D)) {
1330     auto VlaSize = getVLAElements1D(Type1D);
1331     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1332       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1333     else {
1334       // Generate a locally unique name for the size expression.
1335       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1336       SmallString<12> Buffer;
1337       StringRef NameRef = Name.toStringRef(Buffer);
1338       auto &Ident = getContext().Idents.getOwn(NameRef);
1339       VLAExprNames.push_back(&Ident);
1340       auto SizeExprAddr =
1341           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1342       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1343       Dimensions.emplace_back(SizeExprAddr.getPointer(),
1344                               Type1D.getUnqualifiedType());
1345     }
1346     Type1D = VlaSize.Type;
1347   }
1348 
1349   if (!EmitDebugInfo)
1350     return;
1351 
1352   // Register each dimension's size-expression with a DILocalVariable,
1353   // so that it can be used by CGDebugInfo when instantiating a DISubrange
1354   // to describe this array.
1355   unsigned NameIdx = 0;
1356   for (auto &VlaSize : Dimensions) {
1357     llvm::Metadata *MD;
1358     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1359       MD = llvm::ConstantAsMetadata::get(C);
1360     else {
1361       // Create an artificial VarDecl to generate debug info for.
1362       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1363       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1364       auto QT = getContext().getIntTypeForBitwidth(
1365           VlaExprTy->getScalarSizeInBits(), false);
1366       auto *ArtificialDecl = VarDecl::Create(
1367           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1368           D.getLocation(), D.getLocation(), NameIdent, QT,
1369           getContext().CreateTypeSourceInfo(QT), SC_Auto);
1370       ArtificialDecl->setImplicit();
1371 
1372       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1373                                          Builder);
1374     }
1375     assert(MD && "No Size expression debug node created");
1376     DI->registerVLASizeExpression(VlaSize.Type, MD);
1377   }
1378 }
1379 
1380 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1381 /// local variable.  Does not emit initialization or destruction.
1382 CodeGenFunction::AutoVarEmission
1383 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1384   QualType Ty = D.getType();
1385   assert(
1386       Ty.getAddressSpace() == LangAS::Default ||
1387       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1388 
1389   AutoVarEmission emission(D);
1390 
1391   bool isEscapingByRef = D.isEscapingByref();
1392   emission.IsEscapingByRef = isEscapingByRef;
1393 
1394   CharUnits alignment = getContext().getDeclAlign(&D);
1395 
1396   // If the type is variably-modified, emit all the VLA sizes for it.
1397   if (Ty->isVariablyModifiedType())
1398     EmitVariablyModifiedType(Ty);
1399 
1400   auto *DI = getDebugInfo();
1401   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1402 
1403   Address address = Address::invalid();
1404   Address AllocaAddr = Address::invalid();
1405   Address OpenMPLocalAddr =
1406       getLangOpts().OpenMP
1407           ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1408           : Address::invalid();
1409   bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1410 
1411   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1412     address = OpenMPLocalAddr;
1413   } else if (Ty->isConstantSizeType()) {
1414     // If this value is an array or struct with a statically determinable
1415     // constant initializer, there are optimizations we can do.
1416     //
1417     // TODO: We should constant-evaluate the initializer of any variable,
1418     // as long as it is initialized by a constant expression. Currently,
1419     // isConstantInitializer produces wrong answers for structs with
1420     // reference or bitfield members, and a few other cases, and checking
1421     // for POD-ness protects us from some of these.
1422     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1423         (D.isConstexpr() ||
1424          ((Ty.isPODType(getContext()) ||
1425            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1426           D.getInit()->isConstantInitializer(getContext(), false)))) {
1427 
1428       // If the variable's a const type, and it's neither an NRVO
1429       // candidate nor a __block variable and has no mutable members,
1430       // emit it as a global instead.
1431       // Exception is if a variable is located in non-constant address space
1432       // in OpenCL.
1433       if ((!getLangOpts().OpenCL ||
1434            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1435           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1436            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1437         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1438 
1439         // Signal this condition to later callbacks.
1440         emission.Addr = Address::invalid();
1441         assert(emission.wasEmittedAsGlobal());
1442         return emission;
1443       }
1444 
1445       // Otherwise, tell the initialization code that we're in this case.
1446       emission.IsConstantAggregate = true;
1447     }
1448 
1449     // A normal fixed sized variable becomes an alloca in the entry block,
1450     // unless:
1451     // - it's an NRVO variable.
1452     // - we are compiling OpenMP and it's an OpenMP local variable.
1453     if (NRVO) {
1454       // The named return value optimization: allocate this variable in the
1455       // return slot, so that we can elide the copy when returning this
1456       // variable (C++0x [class.copy]p34).
1457       address = ReturnValue;
1458 
1459       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1460         const auto *RD = RecordTy->getDecl();
1461         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1462         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1463             RD->isNonTrivialToPrimitiveDestroy()) {
1464           // Create a flag that is used to indicate when the NRVO was applied
1465           // to this variable. Set it to zero to indicate that NRVO was not
1466           // applied.
1467           llvm::Value *Zero = Builder.getFalse();
1468           Address NRVOFlag =
1469             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1470           EnsureInsertPoint();
1471           Builder.CreateStore(Zero, NRVOFlag);
1472 
1473           // Record the NRVO flag for this variable.
1474           NRVOFlags[&D] = NRVOFlag.getPointer();
1475           emission.NRVOFlag = NRVOFlag.getPointer();
1476         }
1477       }
1478     } else {
1479       CharUnits allocaAlignment;
1480       llvm::Type *allocaTy;
1481       if (isEscapingByRef) {
1482         auto &byrefInfo = getBlockByrefInfo(&D);
1483         allocaTy = byrefInfo.Type;
1484         allocaAlignment = byrefInfo.ByrefAlignment;
1485       } else {
1486         allocaTy = ConvertTypeForMem(Ty);
1487         allocaAlignment = alignment;
1488       }
1489 
1490       // Create the alloca.  Note that we set the name separately from
1491       // building the instruction so that it's there even in no-asserts
1492       // builds.
1493       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1494                                  /*ArraySize=*/nullptr, &AllocaAddr);
1495 
1496       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1497       // the catch parameter starts in the catchpad instruction, and we can't
1498       // insert code in those basic blocks.
1499       bool IsMSCatchParam =
1500           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1501 
1502       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1503       // if we don't have a valid insertion point (?).
1504       if (HaveInsertPoint() && !IsMSCatchParam) {
1505         // If there's a jump into the lifetime of this variable, its lifetime
1506         // gets broken up into several regions in IR, which requires more work
1507         // to handle correctly. For now, just omit the intrinsics; this is a
1508         // rare case, and it's better to just be conservatively correct.
1509         // PR28267.
1510         //
1511         // We have to do this in all language modes if there's a jump past the
1512         // declaration. We also have to do it in C if there's a jump to an
1513         // earlier point in the current block because non-VLA lifetimes begin as
1514         // soon as the containing block is entered, not when its variables
1515         // actually come into scope; suppressing the lifetime annotations
1516         // completely in this case is unnecessarily pessimistic, but again, this
1517         // is rare.
1518         if (!Bypasses.IsBypassed(&D) &&
1519             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1520           llvm::TypeSize size =
1521               CGM.getDataLayout().getTypeAllocSize(allocaTy);
1522           emission.SizeForLifetimeMarkers =
1523               size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer())
1524                                 : EmitLifetimeStart(size.getFixedSize(),
1525                                                     AllocaAddr.getPointer());
1526         }
1527       } else {
1528         assert(!emission.useLifetimeMarkers());
1529       }
1530     }
1531   } else {
1532     EnsureInsertPoint();
1533 
1534     if (!DidCallStackSave) {
1535       // Save the stack.
1536       Address Stack =
1537         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1538 
1539       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1540       llvm::Value *V = Builder.CreateCall(F);
1541       Builder.CreateStore(V, Stack);
1542 
1543       DidCallStackSave = true;
1544 
1545       // Push a cleanup block and restore the stack there.
1546       // FIXME: in general circumstances, this should be an EH cleanup.
1547       pushStackRestore(NormalCleanup, Stack);
1548     }
1549 
1550     auto VlaSize = getVLASize(Ty);
1551     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1552 
1553     // Allocate memory for the array.
1554     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1555                                &AllocaAddr);
1556 
1557     // If we have debug info enabled, properly describe the VLA dimensions for
1558     // this type by registering the vla size expression for each of the
1559     // dimensions.
1560     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1561   }
1562 
1563   setAddrOfLocalVar(&D, address);
1564   emission.Addr = address;
1565   emission.AllocaAddr = AllocaAddr;
1566 
1567   // Emit debug info for local var declaration.
1568   if (EmitDebugInfo && HaveInsertPoint()) {
1569     Address DebugAddr = address;
1570     bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1571     DI->setLocation(D.getLocation());
1572 
1573     // If NRVO, use a pointer to the return address.
1574     if (UsePointerValue)
1575       DebugAddr = ReturnValuePointer;
1576 
1577     (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder,
1578                                         UsePointerValue);
1579   }
1580 
1581   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1582     EmitVarAnnotations(&D, address.getPointer());
1583 
1584   // Make sure we call @llvm.lifetime.end.
1585   if (emission.useLifetimeMarkers())
1586     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1587                                          emission.getOriginalAllocatedAddress(),
1588                                          emission.getSizeForLifetimeMarkers());
1589 
1590   return emission;
1591 }
1592 
1593 static bool isCapturedBy(const VarDecl &, const Expr *);
1594 
1595 /// Determines whether the given __block variable is potentially
1596 /// captured by the given statement.
1597 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1598   if (const Expr *E = dyn_cast<Expr>(S))
1599     return isCapturedBy(Var, E);
1600   for (const Stmt *SubStmt : S->children())
1601     if (isCapturedBy(Var, SubStmt))
1602       return true;
1603   return false;
1604 }
1605 
1606 /// Determines whether the given __block variable is potentially
1607 /// captured by the given expression.
1608 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1609   // Skip the most common kinds of expressions that make
1610   // hierarchy-walking expensive.
1611   E = E->IgnoreParenCasts();
1612 
1613   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1614     const BlockDecl *Block = BE->getBlockDecl();
1615     for (const auto &I : Block->captures()) {
1616       if (I.getVariable() == &Var)
1617         return true;
1618     }
1619 
1620     // No need to walk into the subexpressions.
1621     return false;
1622   }
1623 
1624   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1625     const CompoundStmt *CS = SE->getSubStmt();
1626     for (const auto *BI : CS->body())
1627       if (const auto *BIE = dyn_cast<Expr>(BI)) {
1628         if (isCapturedBy(Var, BIE))
1629           return true;
1630       }
1631       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1632           // special case declarations
1633           for (const auto *I : DS->decls()) {
1634               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1635                 const Expr *Init = VD->getInit();
1636                 if (Init && isCapturedBy(Var, Init))
1637                   return true;
1638               }
1639           }
1640       }
1641       else
1642         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1643         // Later, provide code to poke into statements for capture analysis.
1644         return true;
1645     return false;
1646   }
1647 
1648   for (const Stmt *SubStmt : E->children())
1649     if (isCapturedBy(Var, SubStmt))
1650       return true;
1651 
1652   return false;
1653 }
1654 
1655 /// Determine whether the given initializer is trivial in the sense
1656 /// that it requires no code to be generated.
1657 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1658   if (!Init)
1659     return true;
1660 
1661   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1662     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1663       if (Constructor->isTrivial() &&
1664           Constructor->isDefaultConstructor() &&
1665           !Construct->requiresZeroInitialization())
1666         return true;
1667 
1668   return false;
1669 }
1670 
1671 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1672                                                       const VarDecl &D,
1673                                                       Address Loc) {
1674   auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1675   CharUnits Size = getContext().getTypeSizeInChars(type);
1676   bool isVolatile = type.isVolatileQualified();
1677   if (!Size.isZero()) {
1678     switch (trivialAutoVarInit) {
1679     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1680       llvm_unreachable("Uninitialized handled by caller");
1681     case LangOptions::TrivialAutoVarInitKind::Zero:
1682       if (CGM.stopAutoInit())
1683         return;
1684       emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1685       break;
1686     case LangOptions::TrivialAutoVarInitKind::Pattern:
1687       if (CGM.stopAutoInit())
1688         return;
1689       emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1690       break;
1691     }
1692     return;
1693   }
1694 
1695   // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1696   // them, so emit a memcpy with the VLA size to initialize each element.
1697   // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1698   // will catch that code, but there exists code which generates zero-sized
1699   // VLAs. Be nice and initialize whatever they requested.
1700   const auto *VlaType = getContext().getAsVariableArrayType(type);
1701   if (!VlaType)
1702     return;
1703   auto VlaSize = getVLASize(VlaType);
1704   auto SizeVal = VlaSize.NumElts;
1705   CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1706   switch (trivialAutoVarInit) {
1707   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1708     llvm_unreachable("Uninitialized handled by caller");
1709 
1710   case LangOptions::TrivialAutoVarInitKind::Zero:
1711     if (CGM.stopAutoInit())
1712       return;
1713     if (!EltSize.isOne())
1714       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1715     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1716                          isVolatile);
1717     break;
1718 
1719   case LangOptions::TrivialAutoVarInitKind::Pattern: {
1720     if (CGM.stopAutoInit())
1721       return;
1722     llvm::Type *ElTy = Loc.getElementType();
1723     llvm::Constant *Constant = constWithPadding(
1724         CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1725     CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1726     llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1727     llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1728     llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1729     llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1730         SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1731         "vla.iszerosized");
1732     Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1733     EmitBlock(SetupBB);
1734     if (!EltSize.isOne())
1735       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1736     llvm::Value *BaseSizeInChars =
1737         llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1738     Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1739     llvm::Value *End =
1740         Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1741     llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1742     EmitBlock(LoopBB);
1743     llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1744     Cur->addIncoming(Begin.getPointer(), OriginBB);
1745     CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1746     Builder.CreateMemCpy(Address(Cur, CurAlign),
1747                          createUnnamedGlobalForMemcpyFrom(
1748                              CGM, D, Builder, Constant, ConstantAlign),
1749                          BaseSizeInChars, isVolatile);
1750     llvm::Value *Next =
1751         Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1752     llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1753     Builder.CreateCondBr(Done, ContBB, LoopBB);
1754     Cur->addIncoming(Next, LoopBB);
1755     EmitBlock(ContBB);
1756   } break;
1757   }
1758 }
1759 
1760 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1761   assert(emission.Variable && "emission was not valid!");
1762 
1763   // If this was emitted as a global constant, we're done.
1764   if (emission.wasEmittedAsGlobal()) return;
1765 
1766   const VarDecl &D = *emission.Variable;
1767   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1768   QualType type = D.getType();
1769 
1770   // If this local has an initializer, emit it now.
1771   const Expr *Init = D.getInit();
1772 
1773   // If we are at an unreachable point, we don't need to emit the initializer
1774   // unless it contains a label.
1775   if (!HaveInsertPoint()) {
1776     if (!Init || !ContainsLabel(Init)) return;
1777     EnsureInsertPoint();
1778   }
1779 
1780   // Initialize the structure of a __block variable.
1781   if (emission.IsEscapingByRef)
1782     emitByrefStructureInit(emission);
1783 
1784   // Initialize the variable here if it doesn't have a initializer and it is a
1785   // C struct that is non-trivial to initialize or an array containing such a
1786   // struct.
1787   if (!Init &&
1788       type.isNonTrivialToPrimitiveDefaultInitialize() ==
1789           QualType::PDIK_Struct) {
1790     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1791     if (emission.IsEscapingByRef)
1792       drillIntoBlockVariable(*this, Dst, &D);
1793     defaultInitNonTrivialCStructVar(Dst);
1794     return;
1795   }
1796 
1797   // Check whether this is a byref variable that's potentially
1798   // captured and moved by its own initializer.  If so, we'll need to
1799   // emit the initializer first, then copy into the variable.
1800   bool capturedByInit =
1801       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1802 
1803   bool locIsByrefHeader = !capturedByInit;
1804   const Address Loc =
1805       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1806 
1807   // Note: constexpr already initializes everything correctly.
1808   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1809       (D.isConstexpr()
1810            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1811            : (D.getAttr<UninitializedAttr>()
1812                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1813                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1814 
1815   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1816     if (trivialAutoVarInit ==
1817         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1818       return;
1819 
1820     // Only initialize a __block's storage: we always initialize the header.
1821     if (emission.IsEscapingByRef && !locIsByrefHeader)
1822       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1823 
1824     return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1825   };
1826 
1827   if (isTrivialInitializer(Init))
1828     return initializeWhatIsTechnicallyUninitialized(Loc);
1829 
1830   llvm::Constant *constant = nullptr;
1831   if (emission.IsConstantAggregate ||
1832       D.mightBeUsableInConstantExpressions(getContext())) {
1833     assert(!capturedByInit && "constant init contains a capturing block?");
1834     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1835     if (constant && !constant->isZeroValue() &&
1836         (trivialAutoVarInit !=
1837          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1838       IsPattern isPattern =
1839           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1840               ? IsPattern::Yes
1841               : IsPattern::No;
1842       // C guarantees that brace-init with fewer initializers than members in
1843       // the aggregate will initialize the rest of the aggregate as-if it were
1844       // static initialization. In turn static initialization guarantees that
1845       // padding is initialized to zero bits. We could instead pattern-init if D
1846       // has any ImplicitValueInitExpr, but that seems to be unintuitive
1847       // behavior.
1848       constant = constWithPadding(CGM, IsPattern::No,
1849                                   replaceUndef(CGM, isPattern, constant));
1850     }
1851   }
1852 
1853   if (!constant) {
1854     initializeWhatIsTechnicallyUninitialized(Loc);
1855     LValue lv = MakeAddrLValue(Loc, type);
1856     lv.setNonGC(true);
1857     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1858   }
1859 
1860   if (!emission.IsConstantAggregate) {
1861     // For simple scalar/complex initialization, store the value directly.
1862     LValue lv = MakeAddrLValue(Loc, type);
1863     lv.setNonGC(true);
1864     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1865   }
1866 
1867   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1868   emitStoresForConstant(
1869       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1870       type.isVolatileQualified(), Builder, constant);
1871 }
1872 
1873 /// Emit an expression as an initializer for an object (variable, field, etc.)
1874 /// at the given location.  The expression is not necessarily the normal
1875 /// initializer for the object, and the address is not necessarily
1876 /// its normal location.
1877 ///
1878 /// \param init the initializing expression
1879 /// \param D the object to act as if we're initializing
1880 /// \param loc the address to initialize; its type is a pointer
1881 ///   to the LLVM mapping of the object's type
1882 /// \param alignment the alignment of the address
1883 /// \param capturedByInit true if \p D is a __block variable
1884 ///   whose address is potentially changed by the initializer
1885 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1886                                      LValue lvalue, bool capturedByInit) {
1887   QualType type = D->getType();
1888 
1889   if (type->isReferenceType()) {
1890     RValue rvalue = EmitReferenceBindingToExpr(init);
1891     if (capturedByInit)
1892       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1893     EmitStoreThroughLValue(rvalue, lvalue, true);
1894     return;
1895   }
1896   switch (getEvaluationKind(type)) {
1897   case TEK_Scalar:
1898     EmitScalarInit(init, D, lvalue, capturedByInit);
1899     return;
1900   case TEK_Complex: {
1901     ComplexPairTy complex = EmitComplexExpr(init);
1902     if (capturedByInit)
1903       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1904     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1905     return;
1906   }
1907   case TEK_Aggregate:
1908     if (type->isAtomicType()) {
1909       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1910     } else {
1911       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1912       if (isa<VarDecl>(D))
1913         Overlap = AggValueSlot::DoesNotOverlap;
1914       else if (auto *FD = dyn_cast<FieldDecl>(D))
1915         Overlap = getOverlapForFieldInit(FD);
1916       // TODO: how can we delay here if D is captured by its initializer?
1917       EmitAggExpr(init, AggValueSlot::forLValue(
1918                             lvalue, *this, AggValueSlot::IsDestructed,
1919                             AggValueSlot::DoesNotNeedGCBarriers,
1920                             AggValueSlot::IsNotAliased, Overlap));
1921     }
1922     return;
1923   }
1924   llvm_unreachable("bad evaluation kind");
1925 }
1926 
1927 /// Enter a destroy cleanup for the given local variable.
1928 void CodeGenFunction::emitAutoVarTypeCleanup(
1929                             const CodeGenFunction::AutoVarEmission &emission,
1930                             QualType::DestructionKind dtorKind) {
1931   assert(dtorKind != QualType::DK_none);
1932 
1933   // Note that for __block variables, we want to destroy the
1934   // original stack object, not the possibly forwarded object.
1935   Address addr = emission.getObjectAddress(*this);
1936 
1937   const VarDecl *var = emission.Variable;
1938   QualType type = var->getType();
1939 
1940   CleanupKind cleanupKind = NormalAndEHCleanup;
1941   CodeGenFunction::Destroyer *destroyer = nullptr;
1942 
1943   switch (dtorKind) {
1944   case QualType::DK_none:
1945     llvm_unreachable("no cleanup for trivially-destructible variable");
1946 
1947   case QualType::DK_cxx_destructor:
1948     // If there's an NRVO flag on the emission, we need a different
1949     // cleanup.
1950     if (emission.NRVOFlag) {
1951       assert(!type->isArrayType());
1952       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1953       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1954                                                   emission.NRVOFlag);
1955       return;
1956     }
1957     break;
1958 
1959   case QualType::DK_objc_strong_lifetime:
1960     // Suppress cleanups for pseudo-strong variables.
1961     if (var->isARCPseudoStrong()) return;
1962 
1963     // Otherwise, consider whether to use an EH cleanup or not.
1964     cleanupKind = getARCCleanupKind();
1965 
1966     // Use the imprecise destroyer by default.
1967     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1968       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1969     break;
1970 
1971   case QualType::DK_objc_weak_lifetime:
1972     break;
1973 
1974   case QualType::DK_nontrivial_c_struct:
1975     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
1976     if (emission.NRVOFlag) {
1977       assert(!type->isArrayType());
1978       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1979                                                 emission.NRVOFlag, type);
1980       return;
1981     }
1982     break;
1983   }
1984 
1985   // If we haven't chosen a more specific destroyer, use the default.
1986   if (!destroyer) destroyer = getDestroyer(dtorKind);
1987 
1988   // Use an EH cleanup in array destructors iff the destructor itself
1989   // is being pushed as an EH cleanup.
1990   bool useEHCleanup = (cleanupKind & EHCleanup);
1991   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1992                                      useEHCleanup);
1993 }
1994 
1995 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1996   assert(emission.Variable && "emission was not valid!");
1997 
1998   // If this was emitted as a global constant, we're done.
1999   if (emission.wasEmittedAsGlobal()) return;
2000 
2001   // If we don't have an insertion point, we're done.  Sema prevents
2002   // us from jumping into any of these scopes anyway.
2003   if (!HaveInsertPoint()) return;
2004 
2005   const VarDecl &D = *emission.Variable;
2006 
2007   // Check the type for a cleanup.
2008   if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2009     emitAutoVarTypeCleanup(emission, dtorKind);
2010 
2011   // In GC mode, honor objc_precise_lifetime.
2012   if (getLangOpts().getGC() != LangOptions::NonGC &&
2013       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2014     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2015   }
2016 
2017   // Handle the cleanup attribute.
2018   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2019     const FunctionDecl *FD = CA->getFunctionDecl();
2020 
2021     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2022     assert(F && "Could not find function!");
2023 
2024     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2025     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2026   }
2027 
2028   // If this is a block variable, call _Block_object_destroy
2029   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2030   // mode.
2031   if (emission.IsEscapingByRef &&
2032       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2033     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2034     if (emission.Variable->getType().isObjCGCWeak())
2035       Flags |= BLOCK_FIELD_IS_WEAK;
2036     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2037                       /*LoadBlockVarAddr*/ false,
2038                       cxxDestructorCanThrow(emission.Variable->getType()));
2039   }
2040 }
2041 
2042 CodeGenFunction::Destroyer *
2043 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2044   switch (kind) {
2045   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2046   case QualType::DK_cxx_destructor:
2047     return destroyCXXObject;
2048   case QualType::DK_objc_strong_lifetime:
2049     return destroyARCStrongPrecise;
2050   case QualType::DK_objc_weak_lifetime:
2051     return destroyARCWeak;
2052   case QualType::DK_nontrivial_c_struct:
2053     return destroyNonTrivialCStruct;
2054   }
2055   llvm_unreachable("Unknown DestructionKind");
2056 }
2057 
2058 /// pushEHDestroy - Push the standard destructor for the given type as
2059 /// an EH-only cleanup.
2060 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2061                                     Address addr, QualType type) {
2062   assert(dtorKind && "cannot push destructor for trivial type");
2063   assert(needsEHCleanup(dtorKind));
2064 
2065   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2066 }
2067 
2068 /// pushDestroy - Push the standard destructor for the given type as
2069 /// at least a normal cleanup.
2070 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2071                                   Address addr, QualType type) {
2072   assert(dtorKind && "cannot push destructor for trivial type");
2073 
2074   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2075   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2076               cleanupKind & EHCleanup);
2077 }
2078 
2079 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2080                                   QualType type, Destroyer *destroyer,
2081                                   bool useEHCleanupForArray) {
2082   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2083                                      destroyer, useEHCleanupForArray);
2084 }
2085 
2086 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2087   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2088 }
2089 
2090 void CodeGenFunction::pushLifetimeExtendedDestroy(
2091     CleanupKind cleanupKind, Address addr, QualType type,
2092     Destroyer *destroyer, bool useEHCleanupForArray) {
2093   // Push an EH-only cleanup for the object now.
2094   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2095   // around in case a temporary's destructor throws an exception.
2096   if (cleanupKind & EHCleanup)
2097     EHStack.pushCleanup<DestroyObject>(
2098         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2099         destroyer, useEHCleanupForArray);
2100 
2101   // Remember that we need to push a full cleanup for the object at the
2102   // end of the full-expression.
2103   pushCleanupAfterFullExpr<DestroyObject>(
2104       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2105 }
2106 
2107 /// emitDestroy - Immediately perform the destruction of the given
2108 /// object.
2109 ///
2110 /// \param addr - the address of the object; a type*
2111 /// \param type - the type of the object; if an array type, all
2112 ///   objects are destroyed in reverse order
2113 /// \param destroyer - the function to call to destroy individual
2114 ///   elements
2115 /// \param useEHCleanupForArray - whether an EH cleanup should be
2116 ///   used when destroying array elements, in case one of the
2117 ///   destructions throws an exception
2118 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2119                                   Destroyer *destroyer,
2120                                   bool useEHCleanupForArray) {
2121   const ArrayType *arrayType = getContext().getAsArrayType(type);
2122   if (!arrayType)
2123     return destroyer(*this, addr, type);
2124 
2125   llvm::Value *length = emitArrayLength(arrayType, type, addr);
2126 
2127   CharUnits elementAlign =
2128     addr.getAlignment()
2129         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2130 
2131   // Normally we have to check whether the array is zero-length.
2132   bool checkZeroLength = true;
2133 
2134   // But if the array length is constant, we can suppress that.
2135   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2136     // ...and if it's constant zero, we can just skip the entire thing.
2137     if (constLength->isZero()) return;
2138     checkZeroLength = false;
2139   }
2140 
2141   llvm::Value *begin = addr.getPointer();
2142   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
2143   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2144                    checkZeroLength, useEHCleanupForArray);
2145 }
2146 
2147 /// emitArrayDestroy - Destroys all the elements of the given array,
2148 /// beginning from last to first.  The array cannot be zero-length.
2149 ///
2150 /// \param begin - a type* denoting the first element of the array
2151 /// \param end - a type* denoting one past the end of the array
2152 /// \param elementType - the element type of the array
2153 /// \param destroyer - the function to call to destroy elements
2154 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2155 ///   the remaining elements in case the destruction of a single
2156 ///   element throws
2157 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2158                                        llvm::Value *end,
2159                                        QualType elementType,
2160                                        CharUnits elementAlign,
2161                                        Destroyer *destroyer,
2162                                        bool checkZeroLength,
2163                                        bool useEHCleanup) {
2164   assert(!elementType->isArrayType());
2165 
2166   // The basic structure here is a do-while loop, because we don't
2167   // need to check for the zero-element case.
2168   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2169   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2170 
2171   if (checkZeroLength) {
2172     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2173                                                 "arraydestroy.isempty");
2174     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2175   }
2176 
2177   // Enter the loop body, making that address the current address.
2178   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2179   EmitBlock(bodyBB);
2180   llvm::PHINode *elementPast =
2181     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2182   elementPast->addIncoming(end, entryBB);
2183 
2184   // Shift the address back by one element.
2185   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2186   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2187                                                    "arraydestroy.element");
2188 
2189   if (useEHCleanup)
2190     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2191                                    destroyer);
2192 
2193   // Perform the actual destruction there.
2194   destroyer(*this, Address(element, elementAlign), elementType);
2195 
2196   if (useEHCleanup)
2197     PopCleanupBlock();
2198 
2199   // Check whether we've reached the end.
2200   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2201   Builder.CreateCondBr(done, doneBB, bodyBB);
2202   elementPast->addIncoming(element, Builder.GetInsertBlock());
2203 
2204   // Done.
2205   EmitBlock(doneBB);
2206 }
2207 
2208 /// Perform partial array destruction as if in an EH cleanup.  Unlike
2209 /// emitArrayDestroy, the element type here may still be an array type.
2210 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2211                                     llvm::Value *begin, llvm::Value *end,
2212                                     QualType type, CharUnits elementAlign,
2213                                     CodeGenFunction::Destroyer *destroyer) {
2214   // If the element type is itself an array, drill down.
2215   unsigned arrayDepth = 0;
2216   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2217     // VLAs don't require a GEP index to walk into.
2218     if (!isa<VariableArrayType>(arrayType))
2219       arrayDepth++;
2220     type = arrayType->getElementType();
2221   }
2222 
2223   if (arrayDepth) {
2224     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2225 
2226     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2227     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2228     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
2229   }
2230 
2231   // Destroy the array.  We don't ever need an EH cleanup because we
2232   // assume that we're in an EH cleanup ourselves, so a throwing
2233   // destructor causes an immediate terminate.
2234   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2235                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2236 }
2237 
2238 namespace {
2239   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2240   /// array destroy where the end pointer is regularly determined and
2241   /// does not need to be loaded from a local.
2242   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2243     llvm::Value *ArrayBegin;
2244     llvm::Value *ArrayEnd;
2245     QualType ElementType;
2246     CodeGenFunction::Destroyer *Destroyer;
2247     CharUnits ElementAlign;
2248   public:
2249     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2250                                QualType elementType, CharUnits elementAlign,
2251                                CodeGenFunction::Destroyer *destroyer)
2252       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2253         ElementType(elementType), Destroyer(destroyer),
2254         ElementAlign(elementAlign) {}
2255 
2256     void Emit(CodeGenFunction &CGF, Flags flags) override {
2257       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2258                               ElementType, ElementAlign, Destroyer);
2259     }
2260   };
2261 
2262   /// IrregularPartialArrayDestroy - a cleanup which performs a
2263   /// partial array destroy where the end pointer is irregularly
2264   /// determined and must be loaded from a local.
2265   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2266     llvm::Value *ArrayBegin;
2267     Address ArrayEndPointer;
2268     QualType ElementType;
2269     CodeGenFunction::Destroyer *Destroyer;
2270     CharUnits ElementAlign;
2271   public:
2272     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2273                                  Address arrayEndPointer,
2274                                  QualType elementType,
2275                                  CharUnits elementAlign,
2276                                  CodeGenFunction::Destroyer *destroyer)
2277       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2278         ElementType(elementType), Destroyer(destroyer),
2279         ElementAlign(elementAlign) {}
2280 
2281     void Emit(CodeGenFunction &CGF, Flags flags) override {
2282       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2283       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2284                               ElementType, ElementAlign, Destroyer);
2285     }
2286   };
2287 } // end anonymous namespace
2288 
2289 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2290 /// already-constructed elements of the given array.  The cleanup
2291 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2292 ///
2293 /// \param elementType - the immediate element type of the array;
2294 ///   possibly still an array type
2295 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2296                                                        Address arrayEndPointer,
2297                                                        QualType elementType,
2298                                                        CharUnits elementAlign,
2299                                                        Destroyer *destroyer) {
2300   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2301                                                     arrayBegin, arrayEndPointer,
2302                                                     elementType, elementAlign,
2303                                                     destroyer);
2304 }
2305 
2306 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2307 /// already-constructed elements of the given array.  The cleanup
2308 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2309 ///
2310 /// \param elementType - the immediate element type of the array;
2311 ///   possibly still an array type
2312 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2313                                                      llvm::Value *arrayEnd,
2314                                                      QualType elementType,
2315                                                      CharUnits elementAlign,
2316                                                      Destroyer *destroyer) {
2317   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2318                                                   arrayBegin, arrayEnd,
2319                                                   elementType, elementAlign,
2320                                                   destroyer);
2321 }
2322 
2323 /// Lazily declare the @llvm.lifetime.start intrinsic.
2324 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2325   if (LifetimeStartFn)
2326     return LifetimeStartFn;
2327   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2328     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2329   return LifetimeStartFn;
2330 }
2331 
2332 /// Lazily declare the @llvm.lifetime.end intrinsic.
2333 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2334   if (LifetimeEndFn)
2335     return LifetimeEndFn;
2336   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2337     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2338   return LifetimeEndFn;
2339 }
2340 
2341 namespace {
2342   /// A cleanup to perform a release of an object at the end of a
2343   /// function.  This is used to balance out the incoming +1 of a
2344   /// ns_consumed argument when we can't reasonably do that just by
2345   /// not doing the initial retain for a __block argument.
2346   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2347     ConsumeARCParameter(llvm::Value *param,
2348                         ARCPreciseLifetime_t precise)
2349       : Param(param), Precise(precise) {}
2350 
2351     llvm::Value *Param;
2352     ARCPreciseLifetime_t Precise;
2353 
2354     void Emit(CodeGenFunction &CGF, Flags flags) override {
2355       CGF.EmitARCRelease(Param, Precise);
2356     }
2357   };
2358 } // end anonymous namespace
2359 
2360 /// Emit an alloca (or GlobalValue depending on target)
2361 /// for the specified parameter and set up LocalDeclMap.
2362 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2363                                    unsigned ArgNo) {
2364   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2365   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2366          "Invalid argument to EmitParmDecl");
2367 
2368   Arg.getAnyValue()->setName(D.getName());
2369 
2370   QualType Ty = D.getType();
2371 
2372   // Use better IR generation for certain implicit parameters.
2373   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2374     // The only implicit argument a block has is its literal.
2375     // This may be passed as an inalloca'ed value on Windows x86.
2376     if (BlockInfo) {
2377       llvm::Value *V = Arg.isIndirect()
2378                            ? Builder.CreateLoad(Arg.getIndirectAddress())
2379                            : Arg.getDirectValue();
2380       setBlockContextParameter(IPD, ArgNo, V);
2381       return;
2382     }
2383   }
2384 
2385   Address DeclPtr = Address::invalid();
2386   bool DoStore = false;
2387   bool IsScalar = hasScalarEvaluationKind(Ty);
2388   // If we already have a pointer to the argument, reuse the input pointer.
2389   if (Arg.isIndirect()) {
2390     DeclPtr = Arg.getIndirectAddress();
2391     // If we have a prettier pointer type at this point, bitcast to that.
2392     unsigned AS = DeclPtr.getType()->getAddressSpace();
2393     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2394     if (DeclPtr.getType() != IRTy)
2395       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2396     // Indirect argument is in alloca address space, which may be different
2397     // from the default address space.
2398     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2399     auto *V = DeclPtr.getPointer();
2400     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2401     auto DestLangAS =
2402         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2403     if (SrcLangAS != DestLangAS) {
2404       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2405              CGM.getDataLayout().getAllocaAddrSpace());
2406       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2407       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2408       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2409                             *this, V, SrcLangAS, DestLangAS, T, true),
2410                         DeclPtr.getAlignment());
2411     }
2412 
2413     // Push a destructor cleanup for this parameter if the ABI requires it.
2414     // Don't push a cleanup in a thunk for a method that will also emit a
2415     // cleanup.
2416     if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2417         Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2418       if (QualType::DestructionKind DtorKind =
2419               D.needsDestruction(getContext())) {
2420         assert((DtorKind == QualType::DK_cxx_destructor ||
2421                 DtorKind == QualType::DK_nontrivial_c_struct) &&
2422                "unexpected destructor type");
2423         pushDestroy(DtorKind, DeclPtr, Ty);
2424         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2425             EHStack.stable_begin();
2426       }
2427     }
2428   } else {
2429     // Check if the parameter address is controlled by OpenMP runtime.
2430     Address OpenMPLocalAddr =
2431         getLangOpts().OpenMP
2432             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2433             : Address::invalid();
2434     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2435       DeclPtr = OpenMPLocalAddr;
2436     } else {
2437       // Otherwise, create a temporary to hold the value.
2438       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2439                               D.getName() + ".addr");
2440     }
2441     DoStore = true;
2442   }
2443 
2444   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2445 
2446   LValue lv = MakeAddrLValue(DeclPtr, Ty);
2447   if (IsScalar) {
2448     Qualifiers qs = Ty.getQualifiers();
2449     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2450       // We honor __attribute__((ns_consumed)) for types with lifetime.
2451       // For __strong, it's handled by just skipping the initial retain;
2452       // otherwise we have to balance out the initial +1 with an extra
2453       // cleanup to do the release at the end of the function.
2454       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2455 
2456       // If a parameter is pseudo-strong then we can omit the implicit retain.
2457       if (D.isARCPseudoStrong()) {
2458         assert(lt == Qualifiers::OCL_Strong &&
2459                "pseudo-strong variable isn't strong?");
2460         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2461         lt = Qualifiers::OCL_ExplicitNone;
2462       }
2463 
2464       // Load objects passed indirectly.
2465       if (Arg.isIndirect() && !ArgVal)
2466         ArgVal = Builder.CreateLoad(DeclPtr);
2467 
2468       if (lt == Qualifiers::OCL_Strong) {
2469         if (!isConsumed) {
2470           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2471             // use objc_storeStrong(&dest, value) for retaining the
2472             // object. But first, store a null into 'dest' because
2473             // objc_storeStrong attempts to release its old value.
2474             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2475             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2476             EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2477             DoStore = false;
2478           }
2479           else
2480           // Don't use objc_retainBlock for block pointers, because we
2481           // don't want to Block_copy something just because we got it
2482           // as a parameter.
2483             ArgVal = EmitARCRetainNonBlock(ArgVal);
2484         }
2485       } else {
2486         // Push the cleanup for a consumed parameter.
2487         if (isConsumed) {
2488           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2489                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2490           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2491                                                    precise);
2492         }
2493 
2494         if (lt == Qualifiers::OCL_Weak) {
2495           EmitARCInitWeak(DeclPtr, ArgVal);
2496           DoStore = false; // The weak init is a store, no need to do two.
2497         }
2498       }
2499 
2500       // Enter the cleanup scope.
2501       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2502     }
2503   }
2504 
2505   // Store the initial value into the alloca.
2506   if (DoStore)
2507     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2508 
2509   setAddrOfLocalVar(&D, DeclPtr);
2510 
2511   // Emit debug info for param declarations in non-thunk functions.
2512   if (CGDebugInfo *DI = getDebugInfo()) {
2513     if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
2514       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2515     }
2516   }
2517 
2518   if (D.hasAttr<AnnotateAttr>())
2519     EmitVarAnnotations(&D, DeclPtr.getPointer());
2520 
2521   // We can only check return value nullability if all arguments to the
2522   // function satisfy their nullability preconditions. This makes it necessary
2523   // to emit null checks for args in the function body itself.
2524   if (requiresReturnValueNullabilityCheck()) {
2525     auto Nullability = Ty->getNullability(getContext());
2526     if (Nullability && *Nullability == NullabilityKind::NonNull) {
2527       SanitizerScope SanScope(this);
2528       RetValNullabilityPrecondition =
2529           Builder.CreateAnd(RetValNullabilityPrecondition,
2530                             Builder.CreateIsNotNull(Arg.getAnyValue()));
2531     }
2532   }
2533 }
2534 
2535 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2536                                             CodeGenFunction *CGF) {
2537   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2538     return;
2539   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2540 }
2541 
2542 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2543                                          CodeGenFunction *CGF) {
2544   if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2545       (!LangOpts.EmitAllDecls && !D->isUsed()))
2546     return;
2547   getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2548 }
2549 
2550 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2551   getOpenMPRuntime().processRequiresDirective(D);
2552 }
2553