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 /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
889 /// markers.
890 static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
891                                       const LangOptions &LangOpts) {
892   // Asan uses markers for use-after-scope checks.
893   if (CGOpts.SanitizeAddressUseAfterScope)
894     return true;
895 
896   // Disable lifetime markers in msan builds.
897   // FIXME: Remove this when msan works with lifetime markers.
898   if (LangOpts.Sanitize.has(SanitizerKind::Memory))
899     return false;
900 
901   // For now, only in optimized builds.
902   return CGOpts.OptimizationLevel != 0;
903 }
904 
905 /// Emit a lifetime.begin marker if some criteria are satisfied.
906 /// \return a pointer to the temporary size Value if a marker was emitted, null
907 /// otherwise
908 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
909                                                 llvm::Value *Addr) {
910   if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
911     return nullptr;
912 
913   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
914   Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
915   llvm::CallInst *C =
916       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
917   C->setDoesNotThrow();
918   return SizeV;
919 }
920 
921 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
922   Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
923   llvm::CallInst *C =
924       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
925   C->setDoesNotThrow();
926 }
927 
928 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
929 /// local variable.  Does not emit initialization or destruction.
930 CodeGenFunction::AutoVarEmission
931 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
932   QualType Ty = D.getType();
933 
934   AutoVarEmission emission(D);
935 
936   bool isByRef = D.hasAttr<BlocksAttr>();
937   emission.IsByRef = isByRef;
938 
939   CharUnits alignment = getContext().getDeclAlign(&D);
940 
941   // If the type is variably-modified, emit all the VLA sizes for it.
942   if (Ty->isVariablyModifiedType())
943     EmitVariablyModifiedType(Ty);
944 
945   Address address = Address::invalid();
946   if (Ty->isConstantSizeType()) {
947     bool NRVO = getLangOpts().ElideConstructors &&
948       D.isNRVOVariable();
949 
950     // If this value is an array or struct with a statically determinable
951     // constant initializer, there are optimizations we can do.
952     //
953     // TODO: We should constant-evaluate the initializer of any variable,
954     // as long as it is initialized by a constant expression. Currently,
955     // isConstantInitializer produces wrong answers for structs with
956     // reference or bitfield members, and a few other cases, and checking
957     // for POD-ness protects us from some of these.
958     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
959         (D.isConstexpr() ||
960          ((Ty.isPODType(getContext()) ||
961            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
962           D.getInit()->isConstantInitializer(getContext(), false)))) {
963 
964       // If the variable's a const type, and it's neither an NRVO
965       // candidate nor a __block variable and has no mutable members,
966       // emit it as a global instead.
967       if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
968           CGM.isTypeConstant(Ty, true)) {
969         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
970 
971         // Signal this condition to later callbacks.
972         emission.Addr = Address::invalid();
973         assert(emission.wasEmittedAsGlobal());
974         return emission;
975       }
976 
977       // Otherwise, tell the initialization code that we're in this case.
978       emission.IsConstantAggregate = true;
979     }
980 
981     // A normal fixed sized variable becomes an alloca in the entry block,
982     // unless it's an NRVO variable.
983 
984     if (NRVO) {
985       // The named return value optimization: allocate this variable in the
986       // return slot, so that we can elide the copy when returning this
987       // variable (C++0x [class.copy]p34).
988       address = ReturnValue;
989 
990       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
991         if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
992           // Create a flag that is used to indicate when the NRVO was applied
993           // to this variable. Set it to zero to indicate that NRVO was not
994           // applied.
995           llvm::Value *Zero = Builder.getFalse();
996           Address NRVOFlag =
997             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
998           EnsureInsertPoint();
999           Builder.CreateStore(Zero, NRVOFlag);
1000 
1001           // Record the NRVO flag for this variable.
1002           NRVOFlags[&D] = NRVOFlag.getPointer();
1003           emission.NRVOFlag = NRVOFlag.getPointer();
1004         }
1005       }
1006     } else {
1007       CharUnits allocaAlignment;
1008       llvm::Type *allocaTy;
1009       if (isByRef) {
1010         auto &byrefInfo = getBlockByrefInfo(&D);
1011         allocaTy = byrefInfo.Type;
1012         allocaAlignment = byrefInfo.ByrefAlignment;
1013       } else {
1014         allocaTy = ConvertTypeForMem(Ty);
1015         allocaAlignment = alignment;
1016       }
1017 
1018       // Create the alloca.  Note that we set the name separately from
1019       // building the instruction so that it's there even in no-asserts
1020       // builds.
1021       address = CreateTempAlloca(allocaTy, allocaAlignment);
1022       address.getPointer()->setName(D.getName());
1023 
1024       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1025       // the catch parameter starts in the catchpad instruction, and we can't
1026       // insert code in those basic blocks.
1027       bool IsMSCatchParam =
1028           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1029 
1030       // Emit a lifetime intrinsic if meaningful.  There's no point
1031       // in doing this if we don't have a valid insertion point (?).
1032       if (HaveInsertPoint() && !IsMSCatchParam) {
1033         uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1034         emission.SizeForLifetimeMarkers =
1035           EmitLifetimeStart(size, address.getPointer());
1036       } else {
1037         assert(!emission.useLifetimeMarkers());
1038       }
1039     }
1040   } else {
1041     EnsureInsertPoint();
1042 
1043     if (!DidCallStackSave) {
1044       // Save the stack.
1045       Address Stack =
1046         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1047 
1048       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1049       llvm::Value *V = Builder.CreateCall(F);
1050       Builder.CreateStore(V, Stack);
1051 
1052       DidCallStackSave = true;
1053 
1054       // Push a cleanup block and restore the stack there.
1055       // FIXME: in general circumstances, this should be an EH cleanup.
1056       pushStackRestore(NormalCleanup, Stack);
1057     }
1058 
1059     llvm::Value *elementCount;
1060     QualType elementType;
1061     std::tie(elementCount, elementType) = getVLASize(Ty);
1062 
1063     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1064 
1065     // Allocate memory for the array.
1066     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1067     vla->setAlignment(alignment.getQuantity());
1068 
1069     address = Address(vla, alignment);
1070   }
1071 
1072   setAddrOfLocalVar(&D, address);
1073   emission.Addr = address;
1074 
1075   // Emit debug info for local var declaration.
1076   if (HaveInsertPoint())
1077     if (CGDebugInfo *DI = getDebugInfo()) {
1078       if (CGM.getCodeGenOpts().getDebugInfo() >=
1079           codegenoptions::LimitedDebugInfo) {
1080         DI->setLocation(D.getLocation());
1081         DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1082       }
1083     }
1084 
1085   if (D.hasAttr<AnnotateAttr>())
1086     EmitVarAnnotations(&D, address.getPointer());
1087 
1088   return emission;
1089 }
1090 
1091 /// Determines whether the given __block variable is potentially
1092 /// captured by the given expression.
1093 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1094   // Skip the most common kinds of expressions that make
1095   // hierarchy-walking expensive.
1096   e = e->IgnoreParenCasts();
1097 
1098   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1099     const BlockDecl *block = be->getBlockDecl();
1100     for (const auto &I : block->captures()) {
1101       if (I.getVariable() == &var)
1102         return true;
1103     }
1104 
1105     // No need to walk into the subexpressions.
1106     return false;
1107   }
1108 
1109   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1110     const CompoundStmt *CS = SE->getSubStmt();
1111     for (const auto *BI : CS->body())
1112       if (const auto *E = dyn_cast<Expr>(BI)) {
1113         if (isCapturedBy(var, E))
1114             return true;
1115       }
1116       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1117           // special case declarations
1118           for (const auto *I : DS->decls()) {
1119               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1120                 const Expr *Init = VD->getInit();
1121                 if (Init && isCapturedBy(var, Init))
1122                   return true;
1123               }
1124           }
1125       }
1126       else
1127         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1128         // Later, provide code to poke into statements for capture analysis.
1129         return true;
1130     return false;
1131   }
1132 
1133   for (const Stmt *SubStmt : e->children())
1134     if (isCapturedBy(var, cast<Expr>(SubStmt)))
1135       return true;
1136 
1137   return false;
1138 }
1139 
1140 /// \brief Determine whether the given initializer is trivial in the sense
1141 /// that it requires no code to be generated.
1142 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1143   if (!Init)
1144     return true;
1145 
1146   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1147     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1148       if (Constructor->isTrivial() &&
1149           Constructor->isDefaultConstructor() &&
1150           !Construct->requiresZeroInitialization())
1151         return true;
1152 
1153   return false;
1154 }
1155 
1156 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1157   assert(emission.Variable && "emission was not valid!");
1158 
1159   // If this was emitted as a global constant, we're done.
1160   if (emission.wasEmittedAsGlobal()) return;
1161 
1162   const VarDecl &D = *emission.Variable;
1163   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1164   QualType type = D.getType();
1165 
1166   // If this local has an initializer, emit it now.
1167   const Expr *Init = D.getInit();
1168 
1169   // If we are at an unreachable point, we don't need to emit the initializer
1170   // unless it contains a label.
1171   if (!HaveInsertPoint()) {
1172     if (!Init || !ContainsLabel(Init)) return;
1173     EnsureInsertPoint();
1174   }
1175 
1176   // Initialize the structure of a __block variable.
1177   if (emission.IsByRef)
1178     emitByrefStructureInit(emission);
1179 
1180   if (isTrivialInitializer(Init))
1181     return;
1182 
1183   // Check whether this is a byref variable that's potentially
1184   // captured and moved by its own initializer.  If so, we'll need to
1185   // emit the initializer first, then copy into the variable.
1186   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1187 
1188   Address Loc =
1189     capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1190 
1191   llvm::Constant *constant = nullptr;
1192   if (emission.IsConstantAggregate || D.isConstexpr()) {
1193     assert(!capturedByInit && "constant init contains a capturing block?");
1194     constant = CGM.EmitConstantInit(D, this);
1195   }
1196 
1197   if (!constant) {
1198     LValue lv = MakeAddrLValue(Loc, type);
1199     lv.setNonGC(true);
1200     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1201   }
1202 
1203   if (!emission.IsConstantAggregate) {
1204     // For simple scalar/complex initialization, store the value directly.
1205     LValue lv = MakeAddrLValue(Loc, type);
1206     lv.setNonGC(true);
1207     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1208   }
1209 
1210   // If this is a simple aggregate initialization, we can optimize it
1211   // in various ways.
1212   bool isVolatile = type.isVolatileQualified();
1213 
1214   llvm::Value *SizeVal =
1215     llvm::ConstantInt::get(IntPtrTy,
1216                            getContext().getTypeSizeInChars(type).getQuantity());
1217 
1218   llvm::Type *BP = Int8PtrTy;
1219   if (Loc.getType() != BP)
1220     Loc = Builder.CreateBitCast(Loc, BP);
1221 
1222   // If the initializer is all or mostly zeros, codegen with memset then do
1223   // a few stores afterward.
1224   if (shouldUseMemSetPlusStoresToInitialize(constant,
1225                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1226     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1227                          isVolatile);
1228     // Zero and undef don't require a stores.
1229     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1230       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1231       emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1232                                    isVolatile, Builder);
1233     }
1234   } else {
1235     // Otherwise, create a temporary global with the initializer then
1236     // memcpy from the global to the alloca.
1237     std::string Name = getStaticDeclName(CGM, D);
1238     llvm::GlobalVariable *GV =
1239       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1240                                llvm::GlobalValue::PrivateLinkage,
1241                                constant, Name);
1242     GV->setAlignment(Loc.getAlignment().getQuantity());
1243     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1244 
1245     Address SrcPtr = Address(GV, Loc.getAlignment());
1246     if (SrcPtr.getType() != BP)
1247       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1248 
1249     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1250   }
1251 }
1252 
1253 /// Emit an expression as an initializer for a variable at the given
1254 /// location.  The expression is not necessarily the normal
1255 /// initializer for the variable, and the address is not necessarily
1256 /// its normal location.
1257 ///
1258 /// \param init the initializing expression
1259 /// \param var the variable to act as if we're initializing
1260 /// \param loc the address to initialize; its type is a pointer
1261 ///   to the LLVM mapping of the variable's type
1262 /// \param alignment the alignment of the address
1263 /// \param capturedByInit true if the variable is a __block variable
1264 ///   whose address is potentially changed by the initializer
1265 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1266                                      LValue lvalue, bool capturedByInit) {
1267   QualType type = D->getType();
1268 
1269   if (type->isReferenceType()) {
1270     RValue rvalue = EmitReferenceBindingToExpr(init);
1271     if (capturedByInit)
1272       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1273     EmitStoreThroughLValue(rvalue, lvalue, true);
1274     return;
1275   }
1276   switch (getEvaluationKind(type)) {
1277   case TEK_Scalar:
1278     EmitScalarInit(init, D, lvalue, capturedByInit);
1279     return;
1280   case TEK_Complex: {
1281     ComplexPairTy complex = EmitComplexExpr(init);
1282     if (capturedByInit)
1283       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1284     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1285     return;
1286   }
1287   case TEK_Aggregate:
1288     if (type->isAtomicType()) {
1289       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1290     } else {
1291       // TODO: how can we delay here if D is captured by its initializer?
1292       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1293                                               AggValueSlot::IsDestructed,
1294                                          AggValueSlot::DoesNotNeedGCBarriers,
1295                                               AggValueSlot::IsNotAliased));
1296     }
1297     return;
1298   }
1299   llvm_unreachable("bad evaluation kind");
1300 }
1301 
1302 /// Enter a destroy cleanup for the given local variable.
1303 void CodeGenFunction::emitAutoVarTypeCleanup(
1304                             const CodeGenFunction::AutoVarEmission &emission,
1305                             QualType::DestructionKind dtorKind) {
1306   assert(dtorKind != QualType::DK_none);
1307 
1308   // Note that for __block variables, we want to destroy the
1309   // original stack object, not the possibly forwarded object.
1310   Address addr = emission.getObjectAddress(*this);
1311 
1312   const VarDecl *var = emission.Variable;
1313   QualType type = var->getType();
1314 
1315   CleanupKind cleanupKind = NormalAndEHCleanup;
1316   CodeGenFunction::Destroyer *destroyer = nullptr;
1317 
1318   switch (dtorKind) {
1319   case QualType::DK_none:
1320     llvm_unreachable("no cleanup for trivially-destructible variable");
1321 
1322   case QualType::DK_cxx_destructor:
1323     // If there's an NRVO flag on the emission, we need a different
1324     // cleanup.
1325     if (emission.NRVOFlag) {
1326       assert(!type->isArrayType());
1327       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1328       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1329                                                dtor, emission.NRVOFlag);
1330       return;
1331     }
1332     break;
1333 
1334   case QualType::DK_objc_strong_lifetime:
1335     // Suppress cleanups for pseudo-strong variables.
1336     if (var->isARCPseudoStrong()) return;
1337 
1338     // Otherwise, consider whether to use an EH cleanup or not.
1339     cleanupKind = getARCCleanupKind();
1340 
1341     // Use the imprecise destroyer by default.
1342     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1343       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1344     break;
1345 
1346   case QualType::DK_objc_weak_lifetime:
1347     break;
1348   }
1349 
1350   // If we haven't chosen a more specific destroyer, use the default.
1351   if (!destroyer) destroyer = getDestroyer(dtorKind);
1352 
1353   // Use an EH cleanup in array destructors iff the destructor itself
1354   // is being pushed as an EH cleanup.
1355   bool useEHCleanup = (cleanupKind & EHCleanup);
1356   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1357                                      useEHCleanup);
1358 }
1359 
1360 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1361   assert(emission.Variable && "emission was not valid!");
1362 
1363   // If this was emitted as a global constant, we're done.
1364   if (emission.wasEmittedAsGlobal()) return;
1365 
1366   // If we don't have an insertion point, we're done.  Sema prevents
1367   // us from jumping into any of these scopes anyway.
1368   if (!HaveInsertPoint()) return;
1369 
1370   const VarDecl &D = *emission.Variable;
1371 
1372   // Make sure we call @llvm.lifetime.end.  This needs to happen
1373   // *last*, so the cleanup needs to be pushed *first*.
1374   if (emission.useLifetimeMarkers())
1375     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1376                                          emission.getAllocatedAddress(),
1377                                          emission.getSizeForLifetimeMarkers());
1378 
1379   // Check the type for a cleanup.
1380   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1381     emitAutoVarTypeCleanup(emission, dtorKind);
1382 
1383   // In GC mode, honor objc_precise_lifetime.
1384   if (getLangOpts().getGC() != LangOptions::NonGC &&
1385       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1386     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1387   }
1388 
1389   // Handle the cleanup attribute.
1390   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1391     const FunctionDecl *FD = CA->getFunctionDecl();
1392 
1393     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1394     assert(F && "Could not find function!");
1395 
1396     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1397     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1398   }
1399 
1400   // If this is a block variable, call _Block_object_destroy
1401   // (on the unforwarded address).
1402   if (emission.IsByRef)
1403     enterByrefCleanup(emission);
1404 }
1405 
1406 CodeGenFunction::Destroyer *
1407 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1408   switch (kind) {
1409   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1410   case QualType::DK_cxx_destructor:
1411     return destroyCXXObject;
1412   case QualType::DK_objc_strong_lifetime:
1413     return destroyARCStrongPrecise;
1414   case QualType::DK_objc_weak_lifetime:
1415     return destroyARCWeak;
1416   }
1417   llvm_unreachable("Unknown DestructionKind");
1418 }
1419 
1420 /// pushEHDestroy - Push the standard destructor for the given type as
1421 /// an EH-only cleanup.
1422 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1423                                     Address addr, QualType type) {
1424   assert(dtorKind && "cannot push destructor for trivial type");
1425   assert(needsEHCleanup(dtorKind));
1426 
1427   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1428 }
1429 
1430 /// pushDestroy - Push the standard destructor for the given type as
1431 /// at least a normal cleanup.
1432 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1433                                   Address addr, QualType type) {
1434   assert(dtorKind && "cannot push destructor for trivial type");
1435 
1436   CleanupKind cleanupKind = getCleanupKind(dtorKind);
1437   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1438               cleanupKind & EHCleanup);
1439 }
1440 
1441 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1442                                   QualType type, Destroyer *destroyer,
1443                                   bool useEHCleanupForArray) {
1444   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1445                                      destroyer, useEHCleanupForArray);
1446 }
1447 
1448 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1449   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1450 }
1451 
1452 void CodeGenFunction::pushLifetimeExtendedDestroy(
1453     CleanupKind cleanupKind, Address addr, QualType type,
1454     Destroyer *destroyer, bool useEHCleanupForArray) {
1455   assert(!isInConditionalBranch() &&
1456          "performing lifetime extension from within conditional");
1457 
1458   // Push an EH-only cleanup for the object now.
1459   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1460   // around in case a temporary's destructor throws an exception.
1461   if (cleanupKind & EHCleanup)
1462     EHStack.pushCleanup<DestroyObject>(
1463         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1464         destroyer, useEHCleanupForArray);
1465 
1466   // Remember that we need to push a full cleanup for the object at the
1467   // end of the full-expression.
1468   pushCleanupAfterFullExpr<DestroyObject>(
1469       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1470 }
1471 
1472 /// emitDestroy - Immediately perform the destruction of the given
1473 /// object.
1474 ///
1475 /// \param addr - the address of the object; a type*
1476 /// \param type - the type of the object; if an array type, all
1477 ///   objects are destroyed in reverse order
1478 /// \param destroyer - the function to call to destroy individual
1479 ///   elements
1480 /// \param useEHCleanupForArray - whether an EH cleanup should be
1481 ///   used when destroying array elements, in case one of the
1482 ///   destructions throws an exception
1483 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1484                                   Destroyer *destroyer,
1485                                   bool useEHCleanupForArray) {
1486   const ArrayType *arrayType = getContext().getAsArrayType(type);
1487   if (!arrayType)
1488     return destroyer(*this, addr, type);
1489 
1490   llvm::Value *length = emitArrayLength(arrayType, type, addr);
1491 
1492   CharUnits elementAlign =
1493     addr.getAlignment()
1494         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1495 
1496   // Normally we have to check whether the array is zero-length.
1497   bool checkZeroLength = true;
1498 
1499   // But if the array length is constant, we can suppress that.
1500   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1501     // ...and if it's constant zero, we can just skip the entire thing.
1502     if (constLength->isZero()) return;
1503     checkZeroLength = false;
1504   }
1505 
1506   llvm::Value *begin = addr.getPointer();
1507   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1508   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1509                    checkZeroLength, useEHCleanupForArray);
1510 }
1511 
1512 /// emitArrayDestroy - Destroys all the elements of the given array,
1513 /// beginning from last to first.  The array cannot be zero-length.
1514 ///
1515 /// \param begin - a type* denoting the first element of the array
1516 /// \param end - a type* denoting one past the end of the array
1517 /// \param elementType - the element type of the array
1518 /// \param destroyer - the function to call to destroy elements
1519 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1520 ///   the remaining elements in case the destruction of a single
1521 ///   element throws
1522 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1523                                        llvm::Value *end,
1524                                        QualType elementType,
1525                                        CharUnits elementAlign,
1526                                        Destroyer *destroyer,
1527                                        bool checkZeroLength,
1528                                        bool useEHCleanup) {
1529   assert(!elementType->isArrayType());
1530 
1531   // The basic structure here is a do-while loop, because we don't
1532   // need to check for the zero-element case.
1533   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1534   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1535 
1536   if (checkZeroLength) {
1537     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1538                                                 "arraydestroy.isempty");
1539     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1540   }
1541 
1542   // Enter the loop body, making that address the current address.
1543   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1544   EmitBlock(bodyBB);
1545   llvm::PHINode *elementPast =
1546     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1547   elementPast->addIncoming(end, entryBB);
1548 
1549   // Shift the address back by one element.
1550   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1551   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1552                                                    "arraydestroy.element");
1553 
1554   if (useEHCleanup)
1555     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1556                                    destroyer);
1557 
1558   // Perform the actual destruction there.
1559   destroyer(*this, Address(element, elementAlign), elementType);
1560 
1561   if (useEHCleanup)
1562     PopCleanupBlock();
1563 
1564   // Check whether we've reached the end.
1565   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1566   Builder.CreateCondBr(done, doneBB, bodyBB);
1567   elementPast->addIncoming(element, Builder.GetInsertBlock());
1568 
1569   // Done.
1570   EmitBlock(doneBB);
1571 }
1572 
1573 /// Perform partial array destruction as if in an EH cleanup.  Unlike
1574 /// emitArrayDestroy, the element type here may still be an array type.
1575 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1576                                     llvm::Value *begin, llvm::Value *end,
1577                                     QualType type, CharUnits elementAlign,
1578                                     CodeGenFunction::Destroyer *destroyer) {
1579   // If the element type is itself an array, drill down.
1580   unsigned arrayDepth = 0;
1581   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1582     // VLAs don't require a GEP index to walk into.
1583     if (!isa<VariableArrayType>(arrayType))
1584       arrayDepth++;
1585     type = arrayType->getElementType();
1586   }
1587 
1588   if (arrayDepth) {
1589     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1590 
1591     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1592     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1593     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1594   }
1595 
1596   // Destroy the array.  We don't ever need an EH cleanup because we
1597   // assume that we're in an EH cleanup ourselves, so a throwing
1598   // destructor causes an immediate terminate.
1599   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1600                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1601 }
1602 
1603 namespace {
1604   /// RegularPartialArrayDestroy - a cleanup which performs a partial
1605   /// array destroy where the end pointer is regularly determined and
1606   /// does not need to be loaded from a local.
1607   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1608     llvm::Value *ArrayBegin;
1609     llvm::Value *ArrayEnd;
1610     QualType ElementType;
1611     CodeGenFunction::Destroyer *Destroyer;
1612     CharUnits ElementAlign;
1613   public:
1614     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1615                                QualType elementType, CharUnits elementAlign,
1616                                CodeGenFunction::Destroyer *destroyer)
1617       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1618         ElementType(elementType), Destroyer(destroyer),
1619         ElementAlign(elementAlign) {}
1620 
1621     void Emit(CodeGenFunction &CGF, Flags flags) override {
1622       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1623                               ElementType, ElementAlign, Destroyer);
1624     }
1625   };
1626 
1627   /// IrregularPartialArrayDestroy - a cleanup which performs a
1628   /// partial array destroy where the end pointer is irregularly
1629   /// determined and must be loaded from a local.
1630   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1631     llvm::Value *ArrayBegin;
1632     Address ArrayEndPointer;
1633     QualType ElementType;
1634     CodeGenFunction::Destroyer *Destroyer;
1635     CharUnits ElementAlign;
1636   public:
1637     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1638                                  Address arrayEndPointer,
1639                                  QualType elementType,
1640                                  CharUnits elementAlign,
1641                                  CodeGenFunction::Destroyer *destroyer)
1642       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1643         ElementType(elementType), Destroyer(destroyer),
1644         ElementAlign(elementAlign) {}
1645 
1646     void Emit(CodeGenFunction &CGF, Flags flags) override {
1647       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1648       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1649                               ElementType, ElementAlign, Destroyer);
1650     }
1651   };
1652 } // end anonymous namespace
1653 
1654 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1655 /// already-constructed elements of the given array.  The cleanup
1656 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1657 ///
1658 /// \param elementType - the immediate element type of the array;
1659 ///   possibly still an array type
1660 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1661                                                        Address arrayEndPointer,
1662                                                        QualType elementType,
1663                                                        CharUnits elementAlign,
1664                                                        Destroyer *destroyer) {
1665   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1666                                                     arrayBegin, arrayEndPointer,
1667                                                     elementType, elementAlign,
1668                                                     destroyer);
1669 }
1670 
1671 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1672 /// already-constructed elements of the given array.  The cleanup
1673 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1674 ///
1675 /// \param elementType - the immediate element type of the array;
1676 ///   possibly still an array type
1677 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1678                                                      llvm::Value *arrayEnd,
1679                                                      QualType elementType,
1680                                                      CharUnits elementAlign,
1681                                                      Destroyer *destroyer) {
1682   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1683                                                   arrayBegin, arrayEnd,
1684                                                   elementType, elementAlign,
1685                                                   destroyer);
1686 }
1687 
1688 /// Lazily declare the @llvm.lifetime.start intrinsic.
1689 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1690   if (LifetimeStartFn) return LifetimeStartFn;
1691   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1692                                             llvm::Intrinsic::lifetime_start);
1693   return LifetimeStartFn;
1694 }
1695 
1696 /// Lazily declare the @llvm.lifetime.end intrinsic.
1697 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1698   if (LifetimeEndFn) return LifetimeEndFn;
1699   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1700                                               llvm::Intrinsic::lifetime_end);
1701   return LifetimeEndFn;
1702 }
1703 
1704 namespace {
1705   /// A cleanup to perform a release of an object at the end of a
1706   /// function.  This is used to balance out the incoming +1 of a
1707   /// ns_consumed argument when we can't reasonably do that just by
1708   /// not doing the initial retain for a __block argument.
1709   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1710     ConsumeARCParameter(llvm::Value *param,
1711                         ARCPreciseLifetime_t precise)
1712       : Param(param), Precise(precise) {}
1713 
1714     llvm::Value *Param;
1715     ARCPreciseLifetime_t Precise;
1716 
1717     void Emit(CodeGenFunction &CGF, Flags flags) override {
1718       CGF.EmitARCRelease(Param, Precise);
1719     }
1720   };
1721 } // end anonymous namespace
1722 
1723 /// Emit an alloca (or GlobalValue depending on target)
1724 /// for the specified parameter and set up LocalDeclMap.
1725 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1726                                    unsigned ArgNo) {
1727   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1728   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1729          "Invalid argument to EmitParmDecl");
1730 
1731   Arg.getAnyValue()->setName(D.getName());
1732 
1733   QualType Ty = D.getType();
1734 
1735   // Use better IR generation for certain implicit parameters.
1736   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1737     // The only implicit argument a block has is its literal.
1738     // We assume this is always passed directly.
1739     if (BlockInfo) {
1740       setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1741       return;
1742     }
1743 
1744     // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1745     // handle the case where 'this' is passed indirectly as part of an inalloca
1746     // struct.
1747     if (const CXXMethodDecl *MD =
1748             dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1749       if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1750         llvm::Value *This = Arg.isIndirect()
1751                                 ? Builder.CreateLoad(Arg.getIndirectAddress())
1752                                 : Arg.getDirectValue();
1753         This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1754             *this, CurGD, This);
1755         if (Arg.isIndirect())
1756           Builder.CreateStore(This, Arg.getIndirectAddress());
1757         else
1758           Arg = ParamValue::forDirect(This);
1759       }
1760     }
1761   }
1762 
1763   Address DeclPtr = Address::invalid();
1764   bool DoStore = false;
1765   bool IsScalar = hasScalarEvaluationKind(Ty);
1766   // If we already have a pointer to the argument, reuse the input pointer.
1767   if (Arg.isIndirect()) {
1768     DeclPtr = Arg.getIndirectAddress();
1769     // If we have a prettier pointer type at this point, bitcast to that.
1770     unsigned AS = DeclPtr.getType()->getAddressSpace();
1771     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1772     if (DeclPtr.getType() != IRTy)
1773       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1774 
1775     // Push a destructor cleanup for this parameter if the ABI requires it.
1776     // Don't push a cleanup in a thunk for a method that will also emit a
1777     // cleanup.
1778     if (!IsScalar && !CurFuncIsThunk &&
1779         getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1780       const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1781       if (RD && RD->hasNonTrivialDestructor())
1782         pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1783     }
1784   } else {
1785     // Otherwise, create a temporary to hold the value.
1786     DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1787                             D.getName() + ".addr");
1788     DoStore = true;
1789   }
1790 
1791   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1792 
1793   LValue lv = MakeAddrLValue(DeclPtr, Ty);
1794   if (IsScalar) {
1795     Qualifiers qs = Ty.getQualifiers();
1796     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1797       // We honor __attribute__((ns_consumed)) for types with lifetime.
1798       // For __strong, it's handled by just skipping the initial retain;
1799       // otherwise we have to balance out the initial +1 with an extra
1800       // cleanup to do the release at the end of the function.
1801       bool isConsumed = D.hasAttr<NSConsumedAttr>();
1802 
1803       // 'self' is always formally __strong, but if this is not an
1804       // init method then we don't want to retain it.
1805       if (D.isARCPseudoStrong()) {
1806         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1807         assert(&D == method->getSelfDecl());
1808         assert(lt == Qualifiers::OCL_Strong);
1809         assert(qs.hasConst());
1810         assert(method->getMethodFamily() != OMF_init);
1811         (void) method;
1812         lt = Qualifiers::OCL_ExplicitNone;
1813       }
1814 
1815       if (lt == Qualifiers::OCL_Strong) {
1816         if (!isConsumed) {
1817           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1818             // use objc_storeStrong(&dest, value) for retaining the
1819             // object. But first, store a null into 'dest' because
1820             // objc_storeStrong attempts to release its old value.
1821             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1822             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1823             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1824             DoStore = false;
1825           }
1826           else
1827           // Don't use objc_retainBlock for block pointers, because we
1828           // don't want to Block_copy something just because we got it
1829           // as a parameter.
1830             ArgVal = EmitARCRetainNonBlock(ArgVal);
1831         }
1832       } else {
1833         // Push the cleanup for a consumed parameter.
1834         if (isConsumed) {
1835           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1836                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1837           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1838                                                    precise);
1839         }
1840 
1841         if (lt == Qualifiers::OCL_Weak) {
1842           EmitARCInitWeak(DeclPtr, ArgVal);
1843           DoStore = false; // The weak init is a store, no need to do two.
1844         }
1845       }
1846 
1847       // Enter the cleanup scope.
1848       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1849     }
1850   }
1851 
1852   // Store the initial value into the alloca.
1853   if (DoStore)
1854     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1855 
1856   setAddrOfLocalVar(&D, DeclPtr);
1857 
1858   // Emit debug info for param declaration.
1859   if (CGDebugInfo *DI = getDebugInfo()) {
1860     if (CGM.getCodeGenOpts().getDebugInfo() >=
1861         codegenoptions::LimitedDebugInfo) {
1862       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1863     }
1864   }
1865 
1866   if (D.hasAttr<AnnotateAttr>())
1867     EmitVarAnnotations(&D, DeclPtr.getPointer());
1868 }
1869 
1870 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1871                                             CodeGenFunction *CGF) {
1872   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1873     return;
1874   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1875 }
1876