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