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