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