1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Decl nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGBlocks.h"
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenCLRuntime.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclOpenMP.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/CodeGen/CGFunctionInfo.h"
30 #include "clang/Frontend/CodeGenOptions.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Type.h"
35 
36 using namespace clang;
37 using namespace CodeGen;
38 
39 void CodeGenFunction::EmitDecl(const Decl &D) {
40   switch (D.getKind()) {
41   case Decl::BuiltinTemplate:
42   case Decl::TranslationUnit:
43   case Decl::ExternCContext:
44   case Decl::Namespace:
45   case Decl::UnresolvedUsingTypename:
46   case Decl::ClassTemplateSpecialization:
47   case Decl::ClassTemplatePartialSpecialization:
48   case Decl::VarTemplateSpecialization:
49   case Decl::VarTemplatePartialSpecialization:
50   case Decl::TemplateTypeParm:
51   case Decl::UnresolvedUsingValue:
52   case Decl::NonTypeTemplateParm:
53   case Decl::CXXMethod:
54   case Decl::CXXConstructor:
55   case Decl::CXXDestructor:
56   case Decl::CXXConversion:
57   case Decl::Field:
58   case Decl::MSProperty:
59   case Decl::IndirectField:
60   case Decl::ObjCIvar:
61   case Decl::ObjCAtDefsField:
62   case Decl::ParmVar:
63   case Decl::ImplicitParam:
64   case Decl::ClassTemplate:
65   case Decl::VarTemplate:
66   case Decl::FunctionTemplate:
67   case Decl::TypeAliasTemplate:
68   case Decl::TemplateTemplateParm:
69   case Decl::ObjCMethod:
70   case Decl::ObjCCategory:
71   case Decl::ObjCProtocol:
72   case Decl::ObjCInterface:
73   case Decl::ObjCCategoryImpl:
74   case Decl::ObjCImplementation:
75   case Decl::ObjCProperty:
76   case Decl::ObjCCompatibleAlias:
77   case Decl::PragmaComment:
78   case Decl::PragmaDetectMismatch:
79   case Decl::AccessSpec:
80   case Decl::LinkageSpec:
81   case Decl::Export:
82   case Decl::ObjCPropertyImpl:
83   case Decl::FileScopeAsm:
84   case Decl::Friend:
85   case Decl::FriendTemplate:
86   case Decl::Block:
87   case Decl::Captured:
88   case Decl::ClassScopeFunctionSpecialization:
89   case Decl::UsingShadow:
90   case Decl::ConstructorUsingShadow:
91   case Decl::ObjCTypeParam:
92   case Decl::Binding:
93     llvm_unreachable("Declaration should not be in declstmts!");
94   case Decl::Function:  // void X();
95   case Decl::Record:    // struct/union/class X;
96   case Decl::Enum:      // enum X;
97   case Decl::EnumConstant: // enum ? { X = ? }
98   case Decl::CXXRecord: // struct/union/class X; [C++]
99   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
100   case Decl::Label:        // __label__ x;
101   case Decl::Import:
102   case Decl::OMPThreadPrivate:
103   case Decl::OMPCapturedExpr:
104   case Decl::Empty:
105     // None of these decls require codegen support.
106     return;
107 
108   case Decl::NamespaceAlias:
109     if (CGDebugInfo *DI = getDebugInfo())
110         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
111     return;
112   case Decl::Using:          // using X; [C++]
113     if (CGDebugInfo *DI = getDebugInfo())
114         DI->EmitUsingDecl(cast<UsingDecl>(D));
115     return;
116   case Decl::UsingDirective: // using namespace X; [C++]
117     if (CGDebugInfo *DI = getDebugInfo())
118       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
119     return;
120   case Decl::Var:
121   case Decl::Decomposition: {
122     const VarDecl &VD = cast<VarDecl>(D);
123     assert(VD.isLocalVarDecl() &&
124            "Should not see file-scope variables inside a function!");
125     EmitVarDecl(VD);
126     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
127       for (auto *B : DD->bindings())
128         if (auto *HD = B->getHoldingVar())
129           EmitVarDecl(*HD);
130     return;
131   }
132 
133   case Decl::OMPDeclareReduction:
134     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
135 
136   case Decl::Typedef:      // typedef int X;
137   case Decl::TypeAlias: {  // using X = int; [C++0x]
138     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
139     QualType Ty = TD.getUnderlyingType();
140 
141     if (Ty->isVariablyModifiedType())
142       EmitVariablyModifiedType(Ty);
143   }
144   }
145 }
146 
147 /// EmitVarDecl - This method handles emission of any variable declaration
148 /// inside a function, including static vars etc.
149 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
150   if (D.isStaticLocal()) {
151     llvm::GlobalValue::LinkageTypes Linkage =
152         CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
153 
154     // FIXME: We need to force the emission/use of a guard variable for
155     // some variables even if we can constant-evaluate them because
156     // we can't guarantee every translation unit will constant-evaluate them.
157 
158     return EmitStaticVarDecl(D, Linkage);
159   }
160 
161   if (D.hasExternalStorage())
162     // Don't emit it now, allow it to be emitted lazily on its first use.
163     return;
164 
165   if (D.getType().getAddressSpace() == LangAS::opencl_local)
166     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
167 
168   assert(D.hasLocalStorage());
169   return EmitAutoVarDecl(D);
170 }
171 
172 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
173   if (CGM.getLangOpts().CPlusPlus)
174     return CGM.getMangledName(&D).str();
175 
176   // If this isn't C++, we don't need a mangled name, just a pretty one.
177   assert(!D.isExternallyVisible() && "name shouldn't matter");
178   std::string ContextName;
179   const DeclContext *DC = D.getDeclContext();
180   if (auto *CD = dyn_cast<CapturedDecl>(DC))
181     DC = cast<DeclContext>(CD->getNonClosureContext());
182   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
183     ContextName = CGM.getMangledName(FD);
184   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
185     ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
186   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
187     ContextName = OMD->getSelector().getAsString();
188   else
189     llvm_unreachable("Unknown context for static var decl");
190 
191   ContextName += "." + D.getNameAsString();
192   return ContextName;
193 }
194 
195 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
196     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
197   // In general, we don't always emit static var decls once before we reference
198   // them. It is possible to reference them before emitting the function that
199   // contains them, and it is possible to emit the containing function multiple
200   // times.
201   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
202     return ExistingGV;
203 
204   QualType Ty = D.getType();
205   assert(Ty->isConstantSizeType() && "VLAs can't be static");
206 
207   // Use the label if the variable is renamed with the asm-label extension.
208   std::string Name;
209   if (D.hasAttr<AsmLabelAttr>())
210     Name = getMangledName(&D);
211   else
212     Name = getStaticDeclName(*this, D);
213 
214   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
215   unsigned AddrSpace =
216       GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
217 
218   // Local address space cannot have an initializer.
219   llvm::Constant *Init = nullptr;
220   if (Ty.getAddressSpace() != LangAS::opencl_local)
221     Init = EmitNullConstant(Ty);
222   else
223     Init = llvm::UndefValue::get(LTy);
224 
225   llvm::GlobalVariable *GV =
226     new llvm::GlobalVariable(getModule(), LTy,
227                              Ty.isConstant(getContext()), Linkage,
228                              Init, Name, nullptr,
229                              llvm::GlobalVariable::NotThreadLocal,
230                              AddrSpace);
231   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
232   setGlobalVisibility(GV, &D);
233 
234   if (supportsCOMDAT() && GV->isWeakForLinker())
235     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
236 
237   if (D.getTLSKind())
238     setTLSMode(GV, D);
239 
240   if (D.isExternallyVisible()) {
241     if (D.hasAttr<DLLImportAttr>())
242       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
243     else if (D.hasAttr<DLLExportAttr>())
244       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
245   }
246 
247   // Make sure the result is of the correct type.
248   unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
249   llvm::Constant *Addr = GV;
250   if (AddrSpace != ExpectedAddrSpace) {
251     llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
252     Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
253   }
254 
255   setStaticLocalDeclAddress(&D, Addr);
256 
257   // Ensure that the static local gets initialized by making sure the parent
258   // function gets emitted eventually.
259   const Decl *DC = cast<Decl>(D.getDeclContext());
260 
261   // We can't name blocks or captured statements directly, so try to emit their
262   // parents.
263   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
264     DC = DC->getNonClosureContext();
265     // FIXME: Ensure that global blocks get emitted.
266     if (!DC)
267       return Addr;
268   }
269 
270   GlobalDecl GD;
271   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
272     GD = GlobalDecl(CD, Ctor_Base);
273   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
274     GD = GlobalDecl(DD, Dtor_Base);
275   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
276     GD = GlobalDecl(FD);
277   else {
278     // Don't do anything for Obj-C method decls or global closures. We should
279     // never defer them.
280     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
281   }
282   if (GD.getDecl())
283     (void)GetAddrOfGlobal(GD);
284 
285   return Addr;
286 }
287 
288 /// hasNontrivialDestruction - Determine whether a type's destruction is
289 /// non-trivial. If so, and the variable uses static initialization, we must
290 /// register its destructor to run on exit.
291 static bool hasNontrivialDestruction(QualType T) {
292   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
293   return RD && !RD->hasTrivialDestructor();
294 }
295 
296 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
297 /// global variable that has already been created for it.  If the initializer
298 /// has a different type than GV does, this may free GV and return a different
299 /// one.  Otherwise it just returns GV.
300 llvm::GlobalVariable *
301 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
302                                                llvm::GlobalVariable *GV) {
303   llvm::Constant *Init = CGM.EmitConstantInit(D, this);
304 
305   // If constant emission failed, then this should be a C++ static
306   // initializer.
307   if (!Init) {
308     if (!getLangOpts().CPlusPlus)
309       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
310     else if (Builder.GetInsertBlock()) {
311       // Since we have a static initializer, this global variable can't
312       // be constant.
313       GV->setConstant(false);
314 
315       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
316     }
317     return GV;
318   }
319 
320   // The initializer may differ in type from the global. Rewrite
321   // the global to match the initializer.  (We have to do this
322   // because some types, like unions, can't be completely represented
323   // in the LLVM type system.)
324   if (GV->getType()->getElementType() != Init->getType()) {
325     llvm::GlobalVariable *OldGV = GV;
326 
327     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
328                                   OldGV->isConstant(),
329                                   OldGV->getLinkage(), Init, "",
330                                   /*InsertBefore*/ OldGV,
331                                   OldGV->getThreadLocalMode(),
332                            CGM.getContext().getTargetAddressSpace(D.getType()));
333     GV->setVisibility(OldGV->getVisibility());
334     GV->setComdat(OldGV->getComdat());
335 
336     // Steal the name of the old global
337     GV->takeName(OldGV);
338 
339     // Replace all uses of the old global with the new global
340     llvm::Constant *NewPtrForOldDecl =
341     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
342     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
343 
344     // Erase the old global, since it is no longer used.
345     OldGV->eraseFromParent();
346   }
347 
348   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
349   GV->setInitializer(Init);
350 
351   if (hasNontrivialDestruction(D.getType())) {
352     // We have a constant initializer, but a nontrivial destructor. We still
353     // need to perform a guarded "initialization" in order to register the
354     // destructor.
355     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
356   }
357 
358   return GV;
359 }
360 
361 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
362                                       llvm::GlobalValue::LinkageTypes Linkage) {
363   // Check to see if we already have a global variable for this
364   // declaration.  This can happen when double-emitting function
365   // bodies, e.g. with complete and base constructors.
366   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
367   CharUnits alignment = getContext().getDeclAlign(&D);
368 
369   // Store into LocalDeclMap before generating initializer to handle
370   // circular references.
371   setAddrOfLocalVar(&D, Address(addr, alignment));
372 
373   // We can't have a VLA here, but we can have a pointer to a VLA,
374   // even though that doesn't really make any sense.
375   // Make sure to evaluate VLA bounds now so that we have them for later.
376   if (D.getType()->isVariablyModifiedType())
377     EmitVariablyModifiedType(D.getType());
378 
379   // Save the type in case adding the initializer forces a type change.
380   llvm::Type *expectedType = addr->getType();
381 
382   llvm::GlobalVariable *var =
383     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
384 
385   // CUDA's local and local static __shared__ variables should not
386   // have any non-empty initializers. This is ensured by Sema.
387   // Whatever initializer such variable may have when it gets here is
388   // a no-op and should not be emitted.
389   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
390                          D.hasAttr<CUDASharedAttr>();
391   // If this value has an initializer, emit it.
392   if (D.getInit() && !isCudaSharedVar)
393     var = AddInitializerToStaticVarDecl(D, var);
394 
395   var->setAlignment(alignment.getQuantity());
396 
397   if (D.hasAttr<AnnotateAttr>())
398     CGM.AddGlobalAnnotations(&D, var);
399 
400   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
401     var->setSection(SA->getName());
402 
403   if (D.hasAttr<UsedAttr>())
404     CGM.addUsedGlobal(var);
405 
406   // We may have to cast the constant because of the initializer
407   // mismatch above.
408   //
409   // FIXME: It is really dangerous to store this in the map; if anyone
410   // RAUW's the GV uses of this constant will be invalid.
411   llvm::Constant *castedAddr =
412     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
413   if (var != castedAddr)
414     LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
415   CGM.setStaticLocalDeclAddress(&D, castedAddr);
416 
417   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
418 
419   // Emit global variable debug descriptor for static vars.
420   CGDebugInfo *DI = getDebugInfo();
421   if (DI &&
422       CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
423     DI->setLocation(D.getLocation());
424     DI->EmitGlobalVariable(var, &D);
425   }
426 }
427 
428 namespace {
429   struct DestroyObject final : EHScopeStack::Cleanup {
430     DestroyObject(Address addr, QualType type,
431                   CodeGenFunction::Destroyer *destroyer,
432                   bool useEHCleanupForArray)
433       : addr(addr), type(type), destroyer(destroyer),
434         useEHCleanupForArray(useEHCleanupForArray) {}
435 
436     Address addr;
437     QualType type;
438     CodeGenFunction::Destroyer *destroyer;
439     bool useEHCleanupForArray;
440 
441     void Emit(CodeGenFunction &CGF, Flags flags) override {
442       // Don't use an EH cleanup recursively from an EH cleanup.
443       bool useEHCleanupForArray =
444         flags.isForNormalCleanup() && this->useEHCleanupForArray;
445 
446       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
447     }
448   };
449 
450   struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
451     DestroyNRVOVariable(Address addr,
452                         const CXXDestructorDecl *Dtor,
453                         llvm::Value *NRVOFlag)
454       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
455 
456     const CXXDestructorDecl *Dtor;
457     llvm::Value *NRVOFlag;
458     Address Loc;
459 
460     void Emit(CodeGenFunction &CGF, Flags flags) override {
461       // Along the exceptions path we always execute the dtor.
462       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
463 
464       llvm::BasicBlock *SkipDtorBB = nullptr;
465       if (NRVO) {
466         // If we exited via NRVO, we skip the destructor call.
467         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
468         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
469         llvm::Value *DidNRVO =
470           CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
471         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
472         CGF.EmitBlock(RunDtorBB);
473       }
474 
475       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
476                                 /*ForVirtualBase=*/false,
477                                 /*Delegating=*/false,
478                                 Loc);
479 
480       if (NRVO) CGF.EmitBlock(SkipDtorBB);
481     }
482   };
483 
484   struct CallStackRestore final : EHScopeStack::Cleanup {
485     Address Stack;
486     CallStackRestore(Address Stack) : Stack(Stack) {}
487     void Emit(CodeGenFunction &CGF, Flags flags) override {
488       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
489       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
490       CGF.Builder.CreateCall(F, V);
491     }
492   };
493 
494   struct ExtendGCLifetime final : EHScopeStack::Cleanup {
495     const VarDecl &Var;
496     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
497 
498     void Emit(CodeGenFunction &CGF, Flags flags) override {
499       // Compute the address of the local variable, in case it's a
500       // byref or something.
501       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
502                       Var.getType(), VK_LValue, SourceLocation());
503       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
504                                                 SourceLocation());
505       CGF.EmitExtendGCLifetime(value);
506     }
507   };
508 
509   struct CallCleanupFunction final : EHScopeStack::Cleanup {
510     llvm::Constant *CleanupFn;
511     const CGFunctionInfo &FnInfo;
512     const VarDecl &Var;
513 
514     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
515                         const VarDecl *Var)
516       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
517 
518     void Emit(CodeGenFunction &CGF, Flags flags) override {
519       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
520                       Var.getType(), VK_LValue, SourceLocation());
521       // Compute the address of the local variable, in case it's a byref
522       // or something.
523       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
524 
525       // In some cases, the type of the function argument will be different from
526       // the type of the pointer. An example of this is
527       // void f(void* arg);
528       // __attribute__((cleanup(f))) void *g;
529       //
530       // To fix this we insert a bitcast here.
531       QualType ArgTy = FnInfo.arg_begin()->type;
532       llvm::Value *Arg =
533         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
534 
535       CallArgList Args;
536       Args.add(RValue::get(Arg),
537                CGF.getContext().getPointerType(Var.getType()));
538       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
539     }
540   };
541 } // end anonymous namespace
542 
543 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
544 /// variable with lifetime.
545 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
546                                     Address addr,
547                                     Qualifiers::ObjCLifetime lifetime) {
548   switch (lifetime) {
549   case Qualifiers::OCL_None:
550     llvm_unreachable("present but none");
551 
552   case Qualifiers::OCL_ExplicitNone:
553     // nothing to do
554     break;
555 
556   case Qualifiers::OCL_Strong: {
557     CodeGenFunction::Destroyer *destroyer =
558       (var.hasAttr<ObjCPreciseLifetimeAttr>()
559        ? CodeGenFunction::destroyARCStrongPrecise
560        : CodeGenFunction::destroyARCStrongImprecise);
561 
562     CleanupKind cleanupKind = CGF.getARCCleanupKind();
563     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
564                     cleanupKind & EHCleanup);
565     break;
566   }
567   case Qualifiers::OCL_Autoreleasing:
568     // nothing to do
569     break;
570 
571   case Qualifiers::OCL_Weak:
572     // __weak objects always get EH cleanups; otherwise, exceptions
573     // could cause really nasty crashes instead of mere leaks.
574     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
575                     CodeGenFunction::destroyARCWeak,
576                     /*useEHCleanup*/ true);
577     break;
578   }
579 }
580 
581 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
582   if (const Expr *e = dyn_cast<Expr>(s)) {
583     // Skip the most common kinds of expressions that make
584     // hierarchy-walking expensive.
585     s = e = e->IgnoreParenCasts();
586 
587     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
588       return (ref->getDecl() == &var);
589     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
590       const BlockDecl *block = be->getBlockDecl();
591       for (const auto &I : block->captures()) {
592         if (I.getVariable() == &var)
593           return true;
594       }
595     }
596   }
597 
598   for (const Stmt *SubStmt : s->children())
599     // SubStmt might be null; as in missing decl or conditional of an if-stmt.
600     if (SubStmt && isAccessedBy(var, SubStmt))
601       return true;
602 
603   return false;
604 }
605 
606 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
607   if (!decl) return false;
608   if (!isa<VarDecl>(decl)) return false;
609   const VarDecl *var = cast<VarDecl>(decl);
610   return isAccessedBy(*var, e);
611 }
612 
613 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
614                                    const LValue &destLV, const Expr *init) {
615   bool needsCast = false;
616 
617   while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
618     switch (castExpr->getCastKind()) {
619     // Look through casts that don't require representation changes.
620     case CK_NoOp:
621     case CK_BitCast:
622     case CK_BlockPointerToObjCPointerCast:
623       needsCast = true;
624       break;
625 
626     // If we find an l-value to r-value cast from a __weak variable,
627     // emit this operation as a copy or move.
628     case CK_LValueToRValue: {
629       const Expr *srcExpr = castExpr->getSubExpr();
630       if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
631         return false;
632 
633       // Emit the source l-value.
634       LValue srcLV = CGF.EmitLValue(srcExpr);
635 
636       // Handle a formal type change to avoid asserting.
637       auto srcAddr = srcLV.getAddress();
638       if (needsCast) {
639         srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
640                                          destLV.getAddress().getElementType());
641       }
642 
643       // If it was an l-value, use objc_copyWeak.
644       if (srcExpr->getValueKind() == VK_LValue) {
645         CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
646       } else {
647         assert(srcExpr->getValueKind() == VK_XValue);
648         CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
649       }
650       return true;
651     }
652 
653     // Stop at anything else.
654     default:
655       return false;
656     }
657 
658     init = castExpr->getSubExpr();
659   }
660   return false;
661 }
662 
663 static void drillIntoBlockVariable(CodeGenFunction &CGF,
664                                    LValue &lvalue,
665                                    const VarDecl *var) {
666   lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
667 }
668 
669 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
670                                      LValue lvalue, bool capturedByInit) {
671   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
672   if (!lifetime) {
673     llvm::Value *value = EmitScalarExpr(init);
674     if (capturedByInit)
675       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
676     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
677     return;
678   }
679 
680   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
681     init = DIE->getExpr();
682 
683   // If we're emitting a value with lifetime, we have to do the
684   // initialization *before* we leave the cleanup scopes.
685   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
686     enterFullExpression(ewc);
687     init = ewc->getSubExpr();
688   }
689   CodeGenFunction::RunCleanupsScope Scope(*this);
690 
691   // We have to maintain the illusion that the variable is
692   // zero-initialized.  If the variable might be accessed in its
693   // initializer, zero-initialize before running the initializer, then
694   // actually perform the initialization with an assign.
695   bool accessedByInit = false;
696   if (lifetime != Qualifiers::OCL_ExplicitNone)
697     accessedByInit = (capturedByInit || isAccessedBy(D, init));
698   if (accessedByInit) {
699     LValue tempLV = lvalue;
700     // Drill down to the __block object if necessary.
701     if (capturedByInit) {
702       // We can use a simple GEP for this because it can't have been
703       // moved yet.
704       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
705                                               cast<VarDecl>(D),
706                                               /*follow*/ false));
707     }
708 
709     auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
710     llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
711 
712     // If __weak, we want to use a barrier under certain conditions.
713     if (lifetime == Qualifiers::OCL_Weak)
714       EmitARCInitWeak(tempLV.getAddress(), zero);
715 
716     // Otherwise just do a simple store.
717     else
718       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
719   }
720 
721   // Emit the initializer.
722   llvm::Value *value = nullptr;
723 
724   switch (lifetime) {
725   case Qualifiers::OCL_None:
726     llvm_unreachable("present but none");
727 
728   case Qualifiers::OCL_ExplicitNone:
729     value = EmitARCUnsafeUnretainedScalarExpr(init);
730     break;
731 
732   case Qualifiers::OCL_Strong: {
733     value = EmitARCRetainScalarExpr(init);
734     break;
735   }
736 
737   case Qualifiers::OCL_Weak: {
738     // If it's not accessed by the initializer, try to emit the
739     // initialization with a copy or move.
740     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
741       return;
742     }
743 
744     // No way to optimize a producing initializer into this.  It's not
745     // worth optimizing for, because the value will immediately
746     // disappear in the common case.
747     value = EmitScalarExpr(init);
748 
749     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
750     if (accessedByInit)
751       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
752     else
753       EmitARCInitWeak(lvalue.getAddress(), value);
754     return;
755   }
756 
757   case Qualifiers::OCL_Autoreleasing:
758     value = EmitARCRetainAutoreleaseScalarExpr(init);
759     break;
760   }
761 
762   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
763 
764   // If the variable might have been accessed by its initializer, we
765   // might have to initialize with a barrier.  We have to do this for
766   // both __weak and __strong, but __weak got filtered out above.
767   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
768     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
769     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
770     EmitARCRelease(oldValue, ARCImpreciseLifetime);
771     return;
772   }
773 
774   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
775 }
776 
777 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
778 /// non-zero parts of the specified initializer with equal or fewer than
779 /// NumStores scalar stores.
780 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
781                                                 unsigned &NumStores) {
782   // Zero and Undef never requires any extra stores.
783   if (isa<llvm::ConstantAggregateZero>(Init) ||
784       isa<llvm::ConstantPointerNull>(Init) ||
785       isa<llvm::UndefValue>(Init))
786     return true;
787   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
788       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
789       isa<llvm::ConstantExpr>(Init))
790     return Init->isNullValue() || NumStores--;
791 
792   // See if we can emit each element.
793   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
794     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
795       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
796       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
797         return false;
798     }
799     return true;
800   }
801 
802   if (llvm::ConstantDataSequential *CDS =
803         dyn_cast<llvm::ConstantDataSequential>(Init)) {
804     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
805       llvm::Constant *Elt = CDS->getElementAsConstant(i);
806       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
807         return false;
808     }
809     return true;
810   }
811 
812   // Anything else is hard and scary.
813   return false;
814 }
815 
816 /// emitStoresForInitAfterMemset - For inits that
817 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
818 /// stores that would be required.
819 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
820                                          bool isVolatile, CGBuilderTy &Builder) {
821   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
822          "called emitStoresForInitAfterMemset for zero or undef value.");
823 
824   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
825       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
826       isa<llvm::ConstantExpr>(Init)) {
827     Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
828     return;
829   }
830 
831   if (llvm::ConstantDataSequential *CDS =
832           dyn_cast<llvm::ConstantDataSequential>(Init)) {
833     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
834       llvm::Constant *Elt = CDS->getElementAsConstant(i);
835 
836       // If necessary, get a pointer to the element and emit it.
837       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
838         emitStoresForInitAfterMemset(
839             Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
840             isVolatile, Builder);
841     }
842     return;
843   }
844 
845   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
846          "Unknown value type!");
847 
848   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
849     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
850 
851     // If necessary, get a pointer to the element and emit it.
852     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
853       emitStoresForInitAfterMemset(
854           Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
855           isVolatile, Builder);
856   }
857 }
858 
859 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
860 /// plus some stores to initialize a local variable instead of using a memcpy
861 /// from a constant global.  It is beneficial to use memset if the global is all
862 /// zeros, or mostly zeros and large.
863 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
864                                                   uint64_t GlobalSize) {
865   // If a global is all zeros, always use a memset.
866   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
867 
868   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
869   // do it if it will require 6 or fewer scalar stores.
870   // TODO: Should budget depends on the size?  Avoiding a large global warrants
871   // plopping in more stores.
872   unsigned StoreBudget = 6;
873   uint64_t SizeLimit = 32;
874 
875   return GlobalSize > SizeLimit &&
876          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
877 }
878 
879 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
880 /// variable declaration with auto, register, or no storage class specifier.
881 /// These turn into simple stack objects, or GlobalValues depending on target.
882 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
883   AutoVarEmission emission = EmitAutoVarAlloca(D);
884   EmitAutoVarInit(emission);
885   EmitAutoVarCleanups(emission);
886 }
887 
888 /// Emit a lifetime.begin marker if some criteria are satisfied.
889 /// \return a pointer to the temporary size Value if a marker was emitted, null
890 /// otherwise
891 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
892                                                 llvm::Value *Addr) {
893   if (!ShouldEmitLifetimeMarkers)
894     return nullptr;
895 
896   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
897   Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
898   llvm::CallInst *C =
899       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
900   C->setDoesNotThrow();
901   return SizeV;
902 }
903 
904 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
905   Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
906   llvm::CallInst *C =
907       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
908   C->setDoesNotThrow();
909 }
910 
911 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
912 /// local variable.  Does not emit initialization or destruction.
913 CodeGenFunction::AutoVarEmission
914 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
915   QualType Ty = D.getType();
916 
917   AutoVarEmission emission(D);
918 
919   bool isByRef = D.hasAttr<BlocksAttr>();
920   emission.IsByRef = isByRef;
921 
922   CharUnits alignment = getContext().getDeclAlign(&D);
923 
924   // If the type is variably-modified, emit all the VLA sizes for it.
925   if (Ty->isVariablyModifiedType())
926     EmitVariablyModifiedType(Ty);
927 
928   Address address = Address::invalid();
929   if (Ty->isConstantSizeType()) {
930     bool NRVO = getLangOpts().ElideConstructors &&
931       D.isNRVOVariable();
932 
933     // If this value is an array or struct with a statically determinable
934     // constant initializer, there are optimizations we can do.
935     //
936     // TODO: We should constant-evaluate the initializer of any variable,
937     // as long as it is initialized by a constant expression. Currently,
938     // isConstantInitializer produces wrong answers for structs with
939     // reference or bitfield members, and a few other cases, and checking
940     // for POD-ness protects us from some of these.
941     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
942         (D.isConstexpr() ||
943          ((Ty.isPODType(getContext()) ||
944            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
945           D.getInit()->isConstantInitializer(getContext(), false)))) {
946 
947       // If the variable's a const type, and it's neither an NRVO
948       // candidate nor a __block variable and has no mutable members,
949       // emit it as a global instead.
950       if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
951           CGM.isTypeConstant(Ty, true)) {
952         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
953 
954         // Signal this condition to later callbacks.
955         emission.Addr = Address::invalid();
956         assert(emission.wasEmittedAsGlobal());
957         return emission;
958       }
959 
960       // Otherwise, tell the initialization code that we're in this case.
961       emission.IsConstantAggregate = true;
962     }
963 
964     // A normal fixed sized variable becomes an alloca in the entry block,
965     // unless it's an NRVO variable.
966 
967     if (NRVO) {
968       // The named return value optimization: allocate this variable in the
969       // return slot, so that we can elide the copy when returning this
970       // variable (C++0x [class.copy]p34).
971       address = ReturnValue;
972 
973       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
974         if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
975           // Create a flag that is used to indicate when the NRVO was applied
976           // to this variable. Set it to zero to indicate that NRVO was not
977           // applied.
978           llvm::Value *Zero = Builder.getFalse();
979           Address NRVOFlag =
980             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
981           EnsureInsertPoint();
982           Builder.CreateStore(Zero, NRVOFlag);
983 
984           // Record the NRVO flag for this variable.
985           NRVOFlags[&D] = NRVOFlag.getPointer();
986           emission.NRVOFlag = NRVOFlag.getPointer();
987         }
988       }
989     } else {
990       CharUnits allocaAlignment;
991       llvm::Type *allocaTy;
992       if (isByRef) {
993         auto &byrefInfo = getBlockByrefInfo(&D);
994         allocaTy = byrefInfo.Type;
995         allocaAlignment = byrefInfo.ByrefAlignment;
996       } else {
997         allocaTy = ConvertTypeForMem(Ty);
998         allocaAlignment = alignment;
999       }
1000 
1001       // Create the alloca.  Note that we set the name separately from
1002       // building the instruction so that it's there even in no-asserts
1003       // builds.
1004       address = CreateTempAlloca(allocaTy, allocaAlignment);
1005       address.getPointer()->setName(D.getName());
1006 
1007       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1008       // the catch parameter starts in the catchpad instruction, and we can't
1009       // insert code in those basic blocks.
1010       bool IsMSCatchParam =
1011           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1012 
1013       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1014       // if we don't have a valid insertion point (?).
1015       if (HaveInsertPoint() && !IsMSCatchParam) {
1016         // goto or switch-case statements can break lifetime into several
1017         // regions which need more efforts to handle them correctly. PR28267
1018         // This is rare case, but it's better just omit intrinsics than have
1019         // them incorrectly placed.
1020         if (!Bypasses.IsBypassed(&D)) {
1021           uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1022           emission.SizeForLifetimeMarkers =
1023               EmitLifetimeStart(size, address.getPointer());
1024         }
1025       } else {
1026         assert(!emission.useLifetimeMarkers());
1027       }
1028     }
1029   } else {
1030     EnsureInsertPoint();
1031 
1032     if (!DidCallStackSave) {
1033       // Save the stack.
1034       Address Stack =
1035         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1036 
1037       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1038       llvm::Value *V = Builder.CreateCall(F);
1039       Builder.CreateStore(V, Stack);
1040 
1041       DidCallStackSave = true;
1042 
1043       // Push a cleanup block and restore the stack there.
1044       // FIXME: in general circumstances, this should be an EH cleanup.
1045       pushStackRestore(NormalCleanup, Stack);
1046     }
1047 
1048     llvm::Value *elementCount;
1049     QualType elementType;
1050     std::tie(elementCount, elementType) = getVLASize(Ty);
1051 
1052     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1053 
1054     // Allocate memory for the array.
1055     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1056     vla->setAlignment(alignment.getQuantity());
1057 
1058     address = Address(vla, alignment);
1059   }
1060 
1061   setAddrOfLocalVar(&D, address);
1062   emission.Addr = address;
1063 
1064   // Emit debug info for local var declaration.
1065   if (HaveInsertPoint())
1066     if (CGDebugInfo *DI = getDebugInfo()) {
1067       if (CGM.getCodeGenOpts().getDebugInfo() >=
1068           codegenoptions::LimitedDebugInfo) {
1069         DI->setLocation(D.getLocation());
1070         DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1071       }
1072     }
1073 
1074   if (D.hasAttr<AnnotateAttr>())
1075     EmitVarAnnotations(&D, address.getPointer());
1076 
1077   return emission;
1078 }
1079 
1080 /// Determines whether the given __block variable is potentially
1081 /// captured by the given expression.
1082 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1083   // Skip the most common kinds of expressions that make
1084   // hierarchy-walking expensive.
1085   e = e->IgnoreParenCasts();
1086 
1087   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1088     const BlockDecl *block = be->getBlockDecl();
1089     for (const auto &I : block->captures()) {
1090       if (I.getVariable() == &var)
1091         return true;
1092     }
1093 
1094     // No need to walk into the subexpressions.
1095     return false;
1096   }
1097 
1098   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1099     const CompoundStmt *CS = SE->getSubStmt();
1100     for (const auto *BI : CS->body())
1101       if (const auto *E = dyn_cast<Expr>(BI)) {
1102         if (isCapturedBy(var, E))
1103             return true;
1104       }
1105       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1106           // special case declarations
1107           for (const auto *I : DS->decls()) {
1108               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1109                 const Expr *Init = VD->getInit();
1110                 if (Init && isCapturedBy(var, Init))
1111                   return true;
1112               }
1113           }
1114       }
1115       else
1116         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1117         // Later, provide code to poke into statements for capture analysis.
1118         return true;
1119     return false;
1120   }
1121 
1122   for (const Stmt *SubStmt : e->children())
1123     if (isCapturedBy(var, cast<Expr>(SubStmt)))
1124       return true;
1125 
1126   return false;
1127 }
1128 
1129 /// \brief Determine whether the given initializer is trivial in the sense
1130 /// that it requires no code to be generated.
1131 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1132   if (!Init)
1133     return true;
1134 
1135   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1136     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1137       if (Constructor->isTrivial() &&
1138           Constructor->isDefaultConstructor() &&
1139           !Construct->requiresZeroInitialization())
1140         return true;
1141 
1142   return false;
1143 }
1144 
1145 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1146   assert(emission.Variable && "emission was not valid!");
1147 
1148   // If this was emitted as a global constant, we're done.
1149   if (emission.wasEmittedAsGlobal()) return;
1150 
1151   const VarDecl &D = *emission.Variable;
1152   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1153   QualType type = D.getType();
1154 
1155   // If this local has an initializer, emit it now.
1156   const Expr *Init = D.getInit();
1157 
1158   // If we are at an unreachable point, we don't need to emit the initializer
1159   // unless it contains a label.
1160   if (!HaveInsertPoint()) {
1161     if (!Init || !ContainsLabel(Init)) return;
1162     EnsureInsertPoint();
1163   }
1164 
1165   // Initialize the structure of a __block variable.
1166   if (emission.IsByRef)
1167     emitByrefStructureInit(emission);
1168 
1169   if (isTrivialInitializer(Init))
1170     return;
1171 
1172   // Check whether this is a byref variable that's potentially
1173   // captured and moved by its own initializer.  If so, we'll need to
1174   // emit the initializer first, then copy into the variable.
1175   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1176 
1177   Address Loc =
1178     capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1179 
1180   llvm::Constant *constant = nullptr;
1181   if (emission.IsConstantAggregate || D.isConstexpr()) {
1182     assert(!capturedByInit && "constant init contains a capturing block?");
1183     constant = CGM.EmitConstantInit(D, this);
1184   }
1185 
1186   if (!constant) {
1187     LValue lv = MakeAddrLValue(Loc, type);
1188     lv.setNonGC(true);
1189     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1190   }
1191 
1192   if (!emission.IsConstantAggregate) {
1193     // For simple scalar/complex initialization, store the value directly.
1194     LValue lv = MakeAddrLValue(Loc, type);
1195     lv.setNonGC(true);
1196     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1197   }
1198 
1199   // If this is a simple aggregate initialization, we can optimize it
1200   // in various ways.
1201   bool isVolatile = type.isVolatileQualified();
1202 
1203   llvm::Value *SizeVal =
1204     llvm::ConstantInt::get(IntPtrTy,
1205                            getContext().getTypeSizeInChars(type).getQuantity());
1206 
1207   llvm::Type *BP = Int8PtrTy;
1208   if (Loc.getType() != BP)
1209     Loc = Builder.CreateBitCast(Loc, BP);
1210 
1211   // If the initializer is all or mostly zeros, codegen with memset then do
1212   // a few stores afterward.
1213   if (shouldUseMemSetPlusStoresToInitialize(constant,
1214                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1215     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1216                          isVolatile);
1217     // Zero and undef don't require a stores.
1218     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1219       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1220       emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1221                                    isVolatile, Builder);
1222     }
1223   } else {
1224     // Otherwise, create a temporary global with the initializer then
1225     // memcpy from the global to the alloca.
1226     std::string Name = getStaticDeclName(CGM, D);
1227     llvm::GlobalVariable *GV =
1228       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1229                                llvm::GlobalValue::PrivateLinkage,
1230                                constant, Name);
1231     GV->setAlignment(Loc.getAlignment().getQuantity());
1232     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1233 
1234     Address SrcPtr = Address(GV, Loc.getAlignment());
1235     if (SrcPtr.getType() != BP)
1236       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1237 
1238     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1239   }
1240 }
1241 
1242 /// Emit an expression as an initializer for a variable at the given
1243 /// location.  The expression is not necessarily the normal
1244 /// initializer for the variable, and the address is not necessarily
1245 /// its normal location.
1246 ///
1247 /// \param init the initializing expression
1248 /// \param var the variable to act as if we're initializing
1249 /// \param loc the address to initialize; its type is a pointer
1250 ///   to the LLVM mapping of the variable's type
1251 /// \param alignment the alignment of the address
1252 /// \param capturedByInit true if the variable is a __block variable
1253 ///   whose address is potentially changed by the initializer
1254 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1255                                      LValue lvalue, bool capturedByInit) {
1256   QualType type = D->getType();
1257 
1258   if (type->isReferenceType()) {
1259     RValue rvalue = EmitReferenceBindingToExpr(init);
1260     if (capturedByInit)
1261       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1262     EmitStoreThroughLValue(rvalue, lvalue, true);
1263     return;
1264   }
1265   switch (getEvaluationKind(type)) {
1266   case TEK_Scalar:
1267     EmitScalarInit(init, D, lvalue, capturedByInit);
1268     return;
1269   case TEK_Complex: {
1270     ComplexPairTy complex = EmitComplexExpr(init);
1271     if (capturedByInit)
1272       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1273     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1274     return;
1275   }
1276   case TEK_Aggregate:
1277     if (type->isAtomicType()) {
1278       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1279     } else {
1280       // TODO: how can we delay here if D is captured by its initializer?
1281       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1282                                               AggValueSlot::IsDestructed,
1283                                          AggValueSlot::DoesNotNeedGCBarriers,
1284                                               AggValueSlot::IsNotAliased));
1285     }
1286     return;
1287   }
1288   llvm_unreachable("bad evaluation kind");
1289 }
1290 
1291 /// Enter a destroy cleanup for the given local variable.
1292 void CodeGenFunction::emitAutoVarTypeCleanup(
1293                             const CodeGenFunction::AutoVarEmission &emission,
1294                             QualType::DestructionKind dtorKind) {
1295   assert(dtorKind != QualType::DK_none);
1296 
1297   // Note that for __block variables, we want to destroy the
1298   // original stack object, not the possibly forwarded object.
1299   Address addr = emission.getObjectAddress(*this);
1300 
1301   const VarDecl *var = emission.Variable;
1302   QualType type = var->getType();
1303 
1304   CleanupKind cleanupKind = NormalAndEHCleanup;
1305   CodeGenFunction::Destroyer *destroyer = nullptr;
1306 
1307   switch (dtorKind) {
1308   case QualType::DK_none:
1309     llvm_unreachable("no cleanup for trivially-destructible variable");
1310 
1311   case QualType::DK_cxx_destructor:
1312     // If there's an NRVO flag on the emission, we need a different
1313     // cleanup.
1314     if (emission.NRVOFlag) {
1315       assert(!type->isArrayType());
1316       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1317       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1318                                                dtor, emission.NRVOFlag);
1319       return;
1320     }
1321     break;
1322 
1323   case QualType::DK_objc_strong_lifetime:
1324     // Suppress cleanups for pseudo-strong variables.
1325     if (var->isARCPseudoStrong()) return;
1326 
1327     // Otherwise, consider whether to use an EH cleanup or not.
1328     cleanupKind = getARCCleanupKind();
1329 
1330     // Use the imprecise destroyer by default.
1331     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1332       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1333     break;
1334 
1335   case QualType::DK_objc_weak_lifetime:
1336     break;
1337   }
1338 
1339   // If we haven't chosen a more specific destroyer, use the default.
1340   if (!destroyer) destroyer = getDestroyer(dtorKind);
1341 
1342   // Use an EH cleanup in array destructors iff the destructor itself
1343   // is being pushed as an EH cleanup.
1344   bool useEHCleanup = (cleanupKind & EHCleanup);
1345   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1346                                      useEHCleanup);
1347 }
1348 
1349 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1350   assert(emission.Variable && "emission was not valid!");
1351 
1352   // If this was emitted as a global constant, we're done.
1353   if (emission.wasEmittedAsGlobal()) return;
1354 
1355   // If we don't have an insertion point, we're done.  Sema prevents
1356   // us from jumping into any of these scopes anyway.
1357   if (!HaveInsertPoint()) return;
1358 
1359   const VarDecl &D = *emission.Variable;
1360 
1361   // Make sure we call @llvm.lifetime.end.  This needs to happen
1362   // *last*, so the cleanup needs to be pushed *first*.
1363   if (emission.useLifetimeMarkers())
1364     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1365                                          emission.getAllocatedAddress(),
1366                                          emission.getSizeForLifetimeMarkers());
1367 
1368   // Check the type for a cleanup.
1369   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1370     emitAutoVarTypeCleanup(emission, dtorKind);
1371 
1372   // In GC mode, honor objc_precise_lifetime.
1373   if (getLangOpts().getGC() != LangOptions::NonGC &&
1374       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1375     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1376   }
1377 
1378   // Handle the cleanup attribute.
1379   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1380     const FunctionDecl *FD = CA->getFunctionDecl();
1381 
1382     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1383     assert(F && "Could not find function!");
1384 
1385     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1386     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1387   }
1388 
1389   // If this is a block variable, call _Block_object_destroy
1390   // (on the unforwarded address).
1391   if (emission.IsByRef)
1392     enterByrefCleanup(emission);
1393 }
1394 
1395 CodeGenFunction::Destroyer *
1396 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1397   switch (kind) {
1398   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1399   case QualType::DK_cxx_destructor:
1400     return destroyCXXObject;
1401   case QualType::DK_objc_strong_lifetime:
1402     return destroyARCStrongPrecise;
1403   case QualType::DK_objc_weak_lifetime:
1404     return destroyARCWeak;
1405   }
1406   llvm_unreachable("Unknown DestructionKind");
1407 }
1408 
1409 /// pushEHDestroy - Push the standard destructor for the given type as
1410 /// an EH-only cleanup.
1411 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1412                                     Address addr, QualType type) {
1413   assert(dtorKind && "cannot push destructor for trivial type");
1414   assert(needsEHCleanup(dtorKind));
1415 
1416   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1417 }
1418 
1419 /// pushDestroy - Push the standard destructor for the given type as
1420 /// at least a normal cleanup.
1421 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1422                                   Address addr, QualType type) {
1423   assert(dtorKind && "cannot push destructor for trivial type");
1424 
1425   CleanupKind cleanupKind = getCleanupKind(dtorKind);
1426   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1427               cleanupKind & EHCleanup);
1428 }
1429 
1430 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1431                                   QualType type, Destroyer *destroyer,
1432                                   bool useEHCleanupForArray) {
1433   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1434                                      destroyer, useEHCleanupForArray);
1435 }
1436 
1437 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1438   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1439 }
1440 
1441 void CodeGenFunction::pushLifetimeExtendedDestroy(
1442     CleanupKind cleanupKind, Address addr, QualType type,
1443     Destroyer *destroyer, bool useEHCleanupForArray) {
1444   assert(!isInConditionalBranch() &&
1445          "performing lifetime extension from within conditional");
1446 
1447   // Push an EH-only cleanup for the object now.
1448   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1449   // around in case a temporary's destructor throws an exception.
1450   if (cleanupKind & EHCleanup)
1451     EHStack.pushCleanup<DestroyObject>(
1452         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1453         destroyer, useEHCleanupForArray);
1454 
1455   // Remember that we need to push a full cleanup for the object at the
1456   // end of the full-expression.
1457   pushCleanupAfterFullExpr<DestroyObject>(
1458       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1459 }
1460 
1461 /// emitDestroy - Immediately perform the destruction of the given
1462 /// object.
1463 ///
1464 /// \param addr - the address of the object; a type*
1465 /// \param type - the type of the object; if an array type, all
1466 ///   objects are destroyed in reverse order
1467 /// \param destroyer - the function to call to destroy individual
1468 ///   elements
1469 /// \param useEHCleanupForArray - whether an EH cleanup should be
1470 ///   used when destroying array elements, in case one of the
1471 ///   destructions throws an exception
1472 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1473                                   Destroyer *destroyer,
1474                                   bool useEHCleanupForArray) {
1475   const ArrayType *arrayType = getContext().getAsArrayType(type);
1476   if (!arrayType)
1477     return destroyer(*this, addr, type);
1478 
1479   llvm::Value *length = emitArrayLength(arrayType, type, addr);
1480 
1481   CharUnits elementAlign =
1482     addr.getAlignment()
1483         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1484 
1485   // Normally we have to check whether the array is zero-length.
1486   bool checkZeroLength = true;
1487 
1488   // But if the array length is constant, we can suppress that.
1489   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1490     // ...and if it's constant zero, we can just skip the entire thing.
1491     if (constLength->isZero()) return;
1492     checkZeroLength = false;
1493   }
1494 
1495   llvm::Value *begin = addr.getPointer();
1496   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1497   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1498                    checkZeroLength, useEHCleanupForArray);
1499 }
1500 
1501 /// emitArrayDestroy - Destroys all the elements of the given array,
1502 /// beginning from last to first.  The array cannot be zero-length.
1503 ///
1504 /// \param begin - a type* denoting the first element of the array
1505 /// \param end - a type* denoting one past the end of the array
1506 /// \param elementType - the element type of the array
1507 /// \param destroyer - the function to call to destroy elements
1508 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1509 ///   the remaining elements in case the destruction of a single
1510 ///   element throws
1511 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1512                                        llvm::Value *end,
1513                                        QualType elementType,
1514                                        CharUnits elementAlign,
1515                                        Destroyer *destroyer,
1516                                        bool checkZeroLength,
1517                                        bool useEHCleanup) {
1518   assert(!elementType->isArrayType());
1519 
1520   // The basic structure here is a do-while loop, because we don't
1521   // need to check for the zero-element case.
1522   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1523   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1524 
1525   if (checkZeroLength) {
1526     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1527                                                 "arraydestroy.isempty");
1528     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1529   }
1530 
1531   // Enter the loop body, making that address the current address.
1532   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1533   EmitBlock(bodyBB);
1534   llvm::PHINode *elementPast =
1535     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1536   elementPast->addIncoming(end, entryBB);
1537 
1538   // Shift the address back by one element.
1539   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1540   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1541                                                    "arraydestroy.element");
1542 
1543   if (useEHCleanup)
1544     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1545                                    destroyer);
1546 
1547   // Perform the actual destruction there.
1548   destroyer(*this, Address(element, elementAlign), elementType);
1549 
1550   if (useEHCleanup)
1551     PopCleanupBlock();
1552 
1553   // Check whether we've reached the end.
1554   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1555   Builder.CreateCondBr(done, doneBB, bodyBB);
1556   elementPast->addIncoming(element, Builder.GetInsertBlock());
1557 
1558   // Done.
1559   EmitBlock(doneBB);
1560 }
1561 
1562 /// Perform partial array destruction as if in an EH cleanup.  Unlike
1563 /// emitArrayDestroy, the element type here may still be an array type.
1564 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1565                                     llvm::Value *begin, llvm::Value *end,
1566                                     QualType type, CharUnits elementAlign,
1567                                     CodeGenFunction::Destroyer *destroyer) {
1568   // If the element type is itself an array, drill down.
1569   unsigned arrayDepth = 0;
1570   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1571     // VLAs don't require a GEP index to walk into.
1572     if (!isa<VariableArrayType>(arrayType))
1573       arrayDepth++;
1574     type = arrayType->getElementType();
1575   }
1576 
1577   if (arrayDepth) {
1578     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1579 
1580     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1581     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1582     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1583   }
1584 
1585   // Destroy the array.  We don't ever need an EH cleanup because we
1586   // assume that we're in an EH cleanup ourselves, so a throwing
1587   // destructor causes an immediate terminate.
1588   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1589                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1590 }
1591 
1592 namespace {
1593   /// RegularPartialArrayDestroy - a cleanup which performs a partial
1594   /// array destroy where the end pointer is regularly determined and
1595   /// does not need to be loaded from a local.
1596   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1597     llvm::Value *ArrayBegin;
1598     llvm::Value *ArrayEnd;
1599     QualType ElementType;
1600     CodeGenFunction::Destroyer *Destroyer;
1601     CharUnits ElementAlign;
1602   public:
1603     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1604                                QualType elementType, CharUnits elementAlign,
1605                                CodeGenFunction::Destroyer *destroyer)
1606       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1607         ElementType(elementType), Destroyer(destroyer),
1608         ElementAlign(elementAlign) {}
1609 
1610     void Emit(CodeGenFunction &CGF, Flags flags) override {
1611       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1612                               ElementType, ElementAlign, Destroyer);
1613     }
1614   };
1615 
1616   /// IrregularPartialArrayDestroy - a cleanup which performs a
1617   /// partial array destroy where the end pointer is irregularly
1618   /// determined and must be loaded from a local.
1619   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1620     llvm::Value *ArrayBegin;
1621     Address ArrayEndPointer;
1622     QualType ElementType;
1623     CodeGenFunction::Destroyer *Destroyer;
1624     CharUnits ElementAlign;
1625   public:
1626     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1627                                  Address arrayEndPointer,
1628                                  QualType elementType,
1629                                  CharUnits elementAlign,
1630                                  CodeGenFunction::Destroyer *destroyer)
1631       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1632         ElementType(elementType), Destroyer(destroyer),
1633         ElementAlign(elementAlign) {}
1634 
1635     void Emit(CodeGenFunction &CGF, Flags flags) override {
1636       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1637       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1638                               ElementType, ElementAlign, Destroyer);
1639     }
1640   };
1641 } // end anonymous namespace
1642 
1643 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1644 /// already-constructed elements of the given array.  The cleanup
1645 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1646 ///
1647 /// \param elementType - the immediate element type of the array;
1648 ///   possibly still an array type
1649 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1650                                                        Address arrayEndPointer,
1651                                                        QualType elementType,
1652                                                        CharUnits elementAlign,
1653                                                        Destroyer *destroyer) {
1654   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1655                                                     arrayBegin, arrayEndPointer,
1656                                                     elementType, elementAlign,
1657                                                     destroyer);
1658 }
1659 
1660 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1661 /// already-constructed elements of the given array.  The cleanup
1662 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1663 ///
1664 /// \param elementType - the immediate element type of the array;
1665 ///   possibly still an array type
1666 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1667                                                      llvm::Value *arrayEnd,
1668                                                      QualType elementType,
1669                                                      CharUnits elementAlign,
1670                                                      Destroyer *destroyer) {
1671   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1672                                                   arrayBegin, arrayEnd,
1673                                                   elementType, elementAlign,
1674                                                   destroyer);
1675 }
1676 
1677 /// Lazily declare the @llvm.lifetime.start intrinsic.
1678 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1679   if (LifetimeStartFn) return LifetimeStartFn;
1680   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1681                                             llvm::Intrinsic::lifetime_start);
1682   return LifetimeStartFn;
1683 }
1684 
1685 /// Lazily declare the @llvm.lifetime.end intrinsic.
1686 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1687   if (LifetimeEndFn) return LifetimeEndFn;
1688   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1689                                               llvm::Intrinsic::lifetime_end);
1690   return LifetimeEndFn;
1691 }
1692 
1693 namespace {
1694   /// A cleanup to perform a release of an object at the end of a
1695   /// function.  This is used to balance out the incoming +1 of a
1696   /// ns_consumed argument when we can't reasonably do that just by
1697   /// not doing the initial retain for a __block argument.
1698   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1699     ConsumeARCParameter(llvm::Value *param,
1700                         ARCPreciseLifetime_t precise)
1701       : Param(param), Precise(precise) {}
1702 
1703     llvm::Value *Param;
1704     ARCPreciseLifetime_t Precise;
1705 
1706     void Emit(CodeGenFunction &CGF, Flags flags) override {
1707       CGF.EmitARCRelease(Param, Precise);
1708     }
1709   };
1710 } // end anonymous namespace
1711 
1712 /// Emit an alloca (or GlobalValue depending on target)
1713 /// for the specified parameter and set up LocalDeclMap.
1714 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1715                                    unsigned ArgNo) {
1716   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1717   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1718          "Invalid argument to EmitParmDecl");
1719 
1720   Arg.getAnyValue()->setName(D.getName());
1721 
1722   QualType Ty = D.getType();
1723 
1724   // Use better IR generation for certain implicit parameters.
1725   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1726     // The only implicit argument a block has is its literal.
1727     // We assume this is always passed directly.
1728     if (BlockInfo) {
1729       setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1730       return;
1731     }
1732 
1733     // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1734     // handle the case where 'this' is passed indirectly as part of an inalloca
1735     // struct.
1736     if (const CXXMethodDecl *MD =
1737             dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1738       if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1739         llvm::Value *This = Arg.isIndirect()
1740                                 ? Builder.CreateLoad(Arg.getIndirectAddress())
1741                                 : Arg.getDirectValue();
1742         This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1743             *this, CurGD, This);
1744         if (Arg.isIndirect())
1745           Builder.CreateStore(This, Arg.getIndirectAddress());
1746         else
1747           Arg = ParamValue::forDirect(This);
1748       }
1749     }
1750   }
1751 
1752   Address DeclPtr = Address::invalid();
1753   bool DoStore = false;
1754   bool IsScalar = hasScalarEvaluationKind(Ty);
1755   // If we already have a pointer to the argument, reuse the input pointer.
1756   if (Arg.isIndirect()) {
1757     DeclPtr = Arg.getIndirectAddress();
1758     // If we have a prettier pointer type at this point, bitcast to that.
1759     unsigned AS = DeclPtr.getType()->getAddressSpace();
1760     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1761     if (DeclPtr.getType() != IRTy)
1762       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1763 
1764     // Push a destructor cleanup for this parameter if the ABI requires it.
1765     // Don't push a cleanup in a thunk for a method that will also emit a
1766     // cleanup.
1767     if (!IsScalar && !CurFuncIsThunk &&
1768         getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1769       const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1770       if (RD && RD->hasNonTrivialDestructor())
1771         pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1772     }
1773   } else {
1774     // Otherwise, create a temporary to hold the value.
1775     DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1776                             D.getName() + ".addr");
1777     DoStore = true;
1778   }
1779 
1780   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1781 
1782   LValue lv = MakeAddrLValue(DeclPtr, Ty);
1783   if (IsScalar) {
1784     Qualifiers qs = Ty.getQualifiers();
1785     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1786       // We honor __attribute__((ns_consumed)) for types with lifetime.
1787       // For __strong, it's handled by just skipping the initial retain;
1788       // otherwise we have to balance out the initial +1 with an extra
1789       // cleanup to do the release at the end of the function.
1790       bool isConsumed = D.hasAttr<NSConsumedAttr>();
1791 
1792       // 'self' is always formally __strong, but if this is not an
1793       // init method then we don't want to retain it.
1794       if (D.isARCPseudoStrong()) {
1795         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1796         assert(&D == method->getSelfDecl());
1797         assert(lt == Qualifiers::OCL_Strong);
1798         assert(qs.hasConst());
1799         assert(method->getMethodFamily() != OMF_init);
1800         (void) method;
1801         lt = Qualifiers::OCL_ExplicitNone;
1802       }
1803 
1804       if (lt == Qualifiers::OCL_Strong) {
1805         if (!isConsumed) {
1806           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1807             // use objc_storeStrong(&dest, value) for retaining the
1808             // object. But first, store a null into 'dest' because
1809             // objc_storeStrong attempts to release its old value.
1810             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1811             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1812             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1813             DoStore = false;
1814           }
1815           else
1816           // Don't use objc_retainBlock for block pointers, because we
1817           // don't want to Block_copy something just because we got it
1818           // as a parameter.
1819             ArgVal = EmitARCRetainNonBlock(ArgVal);
1820         }
1821       } else {
1822         // Push the cleanup for a consumed parameter.
1823         if (isConsumed) {
1824           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1825                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1826           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1827                                                    precise);
1828         }
1829 
1830         if (lt == Qualifiers::OCL_Weak) {
1831           EmitARCInitWeak(DeclPtr, ArgVal);
1832           DoStore = false; // The weak init is a store, no need to do two.
1833         }
1834       }
1835 
1836       // Enter the cleanup scope.
1837       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1838     }
1839   }
1840 
1841   // Store the initial value into the alloca.
1842   if (DoStore)
1843     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1844 
1845   setAddrOfLocalVar(&D, DeclPtr);
1846 
1847   // Emit debug info for param declaration.
1848   if (CGDebugInfo *DI = getDebugInfo()) {
1849     if (CGM.getCodeGenOpts().getDebugInfo() >=
1850         codegenoptions::LimitedDebugInfo) {
1851       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1852     }
1853   }
1854 
1855   if (D.hasAttr<AnnotateAttr>())
1856     EmitVarAnnotations(&D, DeclPtr.getPointer());
1857 }
1858 
1859 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1860                                             CodeGenFunction *CGF) {
1861   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1862     return;
1863   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1864 }
1865