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