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