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