xref: /src/contrib/llvm-project/clang/lib/CodeGen/CGDecl.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1ec2b103cSEd Schouten //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2ec2b103cSEd Schouten //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ec2b103cSEd Schouten //
7ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
8ec2b103cSEd Schouten //
9ec2b103cSEd Schouten // This contains code to emit Decl nodes as LLVM code.
10ec2b103cSEd Schouten //
11ec2b103cSEd Schouten //===----------------------------------------------------------------------===//
12ec2b103cSEd Schouten 
1345b53394SDimitry Andric #include "CGBlocks.h"
14bab175ecSDimitry Andric #include "CGCXXABI.h"
155e20cdd8SDimitry Andric #include "CGCleanup.h"
16809500fcSDimitry Andric #include "CGDebugInfo.h"
1736981b17SDimitry Andric #include "CGOpenCLRuntime.h"
182b6b257fSDimitry Andric #include "CGOpenMPRuntime.h"
19aa803409SDimitry Andric #include "CodeGenFunction.h"
20809500fcSDimitry Andric #include "CodeGenModule.h"
21461a67faSDimitry Andric #include "ConstantEmitter.h"
22ac9a064cSDimitry Andric #include "EHScopeStack.h"
2322989816SDimitry Andric #include "PatternInit.h"
24aa803409SDimitry Andric #include "TargetInfo.h"
25ec2b103cSEd Schouten #include "clang/AST/ASTContext.h"
26706b4fc4SDimitry Andric #include "clang/AST/Attr.h"
27abe15e55SRoman Divacky #include "clang/AST/CharUnits.h"
28ec2b103cSEd Schouten #include "clang/AST/Decl.h"
29ec2b103cSEd Schouten #include "clang/AST/DeclObjC.h"
302b6b257fSDimitry Andric #include "clang/AST/DeclOpenMP.h"
31676fbe81SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
32ec2b103cSEd Schouten #include "clang/Basic/SourceManager.h"
33ec2b103cSEd Schouten #include "clang/Basic/TargetInfo.h"
34bfef3995SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h"
35cfca06d7SDimitry Andric #include "clang/Sema/Sema.h"
36ac9a064cSDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
37676fbe81SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
38809500fcSDimitry Andric #include "llvm/IR/DataLayout.h"
39809500fcSDimitry Andric #include "llvm/IR/GlobalVariable.h"
40ac9a064cSDimitry Andric #include "llvm/IR/Instructions.h"
41809500fcSDimitry Andric #include "llvm/IR/Intrinsics.h"
42809500fcSDimitry Andric #include "llvm/IR/Type.h"
43e3b55780SDimitry Andric #include <optional>
442b6b257fSDimitry Andric 
45ec2b103cSEd Schouten using namespace clang;
46ec2b103cSEd Schouten using namespace CodeGen;
47ec2b103cSEd Schouten 
48cfca06d7SDimitry Andric static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
49cfca06d7SDimitry Andric               "Clang max alignment greater than what LLVM supports?");
50cfca06d7SDimitry Andric 
EmitDecl(const Decl & D)51ec2b103cSEd Schouten void CodeGenFunction::EmitDecl(const Decl &D) {
52ec2b103cSEd Schouten   switch (D.getKind()) {
5345b53394SDimitry Andric   case Decl::BuiltinTemplate:
540883ccd9SRoman Divacky   case Decl::TranslationUnit:
555e20cdd8SDimitry Andric   case Decl::ExternCContext:
560883ccd9SRoman Divacky   case Decl::Namespace:
570883ccd9SRoman Divacky   case Decl::UnresolvedUsingTypename:
580883ccd9SRoman Divacky   case Decl::ClassTemplateSpecialization:
590883ccd9SRoman Divacky   case Decl::ClassTemplatePartialSpecialization:
60bfef3995SDimitry Andric   case Decl::VarTemplateSpecialization:
61bfef3995SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
620883ccd9SRoman Divacky   case Decl::TemplateTypeParm:
630883ccd9SRoman Divacky   case Decl::UnresolvedUsingValue:
640883ccd9SRoman Divacky   case Decl::NonTypeTemplateParm:
657442d6faSDimitry Andric   case Decl::CXXDeductionGuide:
660883ccd9SRoman Divacky   case Decl::CXXMethod:
670883ccd9SRoman Divacky   case Decl::CXXConstructor:
680883ccd9SRoman Divacky   case Decl::CXXDestructor:
690883ccd9SRoman Divacky   case Decl::CXXConversion:
700883ccd9SRoman Divacky   case Decl::Field:
716a037251SDimitry Andric   case Decl::MSProperty:
72bca07a45SDimitry Andric   case Decl::IndirectField:
730883ccd9SRoman Divacky   case Decl::ObjCIvar:
740883ccd9SRoman Divacky   case Decl::ObjCAtDefsField:
75ec2b103cSEd Schouten   case Decl::ParmVar:
760883ccd9SRoman Divacky   case Decl::ImplicitParam:
770883ccd9SRoman Divacky   case Decl::ClassTemplate:
78bfef3995SDimitry Andric   case Decl::VarTemplate:
790883ccd9SRoman Divacky   case Decl::FunctionTemplate:
8029cafa66SDimitry Andric   case Decl::TypeAliasTemplate:
810883ccd9SRoman Divacky   case Decl::TemplateTemplateParm:
820883ccd9SRoman Divacky   case Decl::ObjCMethod:
830883ccd9SRoman Divacky   case Decl::ObjCCategory:
840883ccd9SRoman Divacky   case Decl::ObjCProtocol:
850883ccd9SRoman Divacky   case Decl::ObjCInterface:
860883ccd9SRoman Divacky   case Decl::ObjCCategoryImpl:
870883ccd9SRoman Divacky   case Decl::ObjCImplementation:
880883ccd9SRoman Divacky   case Decl::ObjCProperty:
890883ccd9SRoman Divacky   case Decl::ObjCCompatibleAlias:
902b6b257fSDimitry Andric   case Decl::PragmaComment:
912b6b257fSDimitry Andric   case Decl::PragmaDetectMismatch:
924ba67500SRoman Divacky   case Decl::AccessSpec:
930883ccd9SRoman Divacky   case Decl::LinkageSpec:
94bab175ecSDimitry Andric   case Decl::Export:
950883ccd9SRoman Divacky   case Decl::ObjCPropertyImpl:
960883ccd9SRoman Divacky   case Decl::FileScopeAsm:
97e3b55780SDimitry Andric   case Decl::TopLevelStmt:
980883ccd9SRoman Divacky   case Decl::Friend:
990883ccd9SRoman Divacky   case Decl::FriendTemplate:
1000883ccd9SRoman Divacky   case Decl::Block:
1016a037251SDimitry Andric   case Decl::Captured:
102bfef3995SDimitry Andric   case Decl::UsingShadow:
1032b6b257fSDimitry Andric   case Decl::ConstructorUsingShadow:
10451ece4aaSDimitry Andric   case Decl::ObjCTypeParam:
105bab175ecSDimitry Andric   case Decl::Binding:
106344a3780SDimitry Andric   case Decl::UnresolvedUsingIfExists:
107e3b55780SDimitry Andric   case Decl::HLSLBuffer:
10836981b17SDimitry Andric     llvm_unreachable("Declaration should not be in declstmts!");
109ec2b103cSEd Schouten   case Decl::Record:    // struct/union/class X;
110ec2b103cSEd Schouten   case Decl::CXXRecord: // struct/union/class X; [C++]
111b60736ecSDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
112b60736ecSDimitry Andric       if (cast<RecordDecl>(D).getDefinition())
113b60736ecSDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
114b60736ecSDimitry Andric     return;
115b60736ecSDimitry Andric   case Decl::Enum:      // enum X;
116b60736ecSDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
117b60736ecSDimitry Andric       if (cast<EnumDecl>(D).getDefinition())
118b60736ecSDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
119b60736ecSDimitry Andric     return;
120b60736ecSDimitry Andric   case Decl::Function:     // void X();
121b60736ecSDimitry Andric   case Decl::EnumConstant: // enum ? { X = ? }
12234d02d0bSRoman Divacky   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
123bca07a45SDimitry Andric   case Decl::Label:        // __label__ x;
124dbe13110SDimitry Andric   case Decl::Import:
125cfca06d7SDimitry Andric   case Decl::MSGuid:    // __declspec(uuid("..."))
126145449b1SDimitry Andric   case Decl::UnnamedGlobalConstant:
127b60736ecSDimitry Andric   case Decl::TemplateParamObject:
128809500fcSDimitry Andric   case Decl::OMPThreadPrivate:
12922989816SDimitry Andric   case Decl::OMPAllocate:
1302b6b257fSDimitry Andric   case Decl::OMPCapturedExpr:
131676fbe81SDimitry Andric   case Decl::OMPRequires:
132809500fcSDimitry Andric   case Decl::Empty:
13322989816SDimitry Andric   case Decl::Concept:
134e3b55780SDimitry Andric   case Decl::ImplicitConceptSpecialization:
135706b4fc4SDimitry Andric   case Decl::LifetimeExtendedTemporary:
136cfca06d7SDimitry Andric   case Decl::RequiresExprBody:
137ec2b103cSEd Schouten     // None of these decls require codegen support.
138ec2b103cSEd Schouten     return;
139ec2b103cSEd Schouten 
140bfef3995SDimitry Andric   case Decl::NamespaceAlias:
141bfef3995SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
142bfef3995SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
143bfef3995SDimitry Andric     return;
144bfef3995SDimitry Andric   case Decl::Using:          // using X; [C++]
145bfef3995SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
146bfef3995SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(D));
147bfef3995SDimitry Andric     return;
148344a3780SDimitry Andric   case Decl::UsingEnum: // using enum X; [C++]
149344a3780SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
150344a3780SDimitry Andric       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
151344a3780SDimitry Andric     return;
152bab175ecSDimitry Andric   case Decl::UsingPack:
153bab175ecSDimitry Andric     for (auto *Using : cast<UsingPackDecl>(D).expansions())
154bab175ecSDimitry Andric       EmitDecl(*Using);
155bab175ecSDimitry Andric     return;
1566a037251SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
1576a037251SDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
1586a037251SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
1596a037251SDimitry Andric     return;
160bab175ecSDimitry Andric   case Decl::Var:
161bab175ecSDimitry Andric   case Decl::Decomposition: {
162ec2b103cSEd Schouten     const VarDecl &VD = cast<VarDecl>(D);
163bca07a45SDimitry Andric     assert(VD.isLocalVarDecl() &&
164ec2b103cSEd Schouten            "Should not see file-scope variables inside a function!");
165bab175ecSDimitry Andric     EmitVarDecl(VD);
166bab175ecSDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
167bab175ecSDimitry Andric       for (auto *B : DD->bindings())
168bab175ecSDimitry Andric         if (auto *HD = B->getHoldingVar())
169bab175ecSDimitry Andric           EmitVarDecl(*HD);
170bab175ecSDimitry Andric     return;
171ec2b103cSEd Schouten   }
172ec2b103cSEd Schouten 
1732b6b257fSDimitry Andric   case Decl::OMPDeclareReduction:
1742b6b257fSDimitry Andric     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
1752b6b257fSDimitry Andric 
17622989816SDimitry Andric   case Decl::OMPDeclareMapper:
17722989816SDimitry Andric     return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
17822989816SDimitry Andric 
17901af97d3SDimitry Andric   case Decl::Typedef:      // typedef int X;
18001af97d3SDimitry Andric   case Decl::TypeAlias: {  // using X = int; [C++0x]
181b60736ecSDimitry Andric     QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
182b60736ecSDimitry Andric     if (CGDebugInfo *DI = getDebugInfo())
183b60736ecSDimitry Andric       DI->EmitAndRetainType(Ty);
184ec2b103cSEd Schouten     if (Ty->isVariablyModifiedType())
185180abc3dSDimitry Andric       EmitVariablyModifiedType(Ty);
18622989816SDimitry Andric     return;
187ec2b103cSEd Schouten   }
188ec2b103cSEd Schouten   }
189ec2b103cSEd Schouten }
190ec2b103cSEd Schouten 
191bca07a45SDimitry Andric /// EmitVarDecl - This method handles emission of any variable declaration
192ec2b103cSEd Schouten /// inside a function, including static vars etc.
EmitVarDecl(const VarDecl & D)193bca07a45SDimitry Andric void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
1942410013dSDimitry Andric   if (D.hasExternalStorage())
1952410013dSDimitry Andric     // Don't emit it now, allow it to be emitted lazily on its first use.
1962410013dSDimitry Andric     return;
1972410013dSDimitry Andric 
1982410013dSDimitry Andric   // Some function-scope variable does not have static storage but still
1992410013dSDimitry Andric   // needs to be emitted like a static variable, e.g. a function-scope
2002410013dSDimitry Andric   // variable in constant address space in OpenCL.
2012410013dSDimitry Andric   if (D.getStorageDuration() != SD_Automatic) {
202461a67faSDimitry Andric     // Static sampler variables translated to function calls.
203461a67faSDimitry Andric     if (D.getType()->isSamplerT())
204461a67faSDimitry Andric       return;
205461a67faSDimitry Andric 
206ecb7e5c8SRoman Divacky     llvm::GlobalValue::LinkageTypes Linkage =
207b1c73532SDimitry Andric         CGM.getLLVMLinkageVarDefinition(&D);
208bfef3995SDimitry Andric 
209bfef3995SDimitry Andric     // FIXME: We need to force the emission/use of a guard variable for
210bfef3995SDimitry Andric     // some variables even if we can constant-evaluate them because
211bfef3995SDimitry Andric     // we can't guarantee every translation unit will constant-evaluate them.
212ecb7e5c8SRoman Divacky 
213bca07a45SDimitry Andric     return EmitStaticVarDecl(D, Linkage);
214ecb7e5c8SRoman Divacky   }
215bfef3995SDimitry Andric 
21645b53394SDimitry Andric   if (D.getType().getAddressSpace() == LangAS::opencl_local)
217bfef3995SDimitry Andric     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
218bfef3995SDimitry Andric 
219bfef3995SDimitry Andric   assert(D.hasLocalStorage());
220bfef3995SDimitry Andric   return EmitAutoVarDecl(D);
221ec2b103cSEd Schouten }
222ec2b103cSEd Schouten 
getStaticDeclName(CodeGenModule & CGM,const VarDecl & D)22306d4ba38SDimitry Andric static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
22406d4ba38SDimitry Andric   if (CGM.getLangOpts().CPlusPlus)
2259f4dbff6SDimitry Andric     return CGM.getMangledName(&D).str();
2269f4dbff6SDimitry Andric 
22706d4ba38SDimitry Andric   // If this isn't C++, we don't need a mangled name, just a pretty one.
22806d4ba38SDimitry Andric   assert(!D.isExternallyVisible() && "name shouldn't matter");
22906d4ba38SDimitry Andric   std::string ContextName;
23006d4ba38SDimitry Andric   const DeclContext *DC = D.getDeclContext();
2315e20cdd8SDimitry Andric   if (auto *CD = dyn_cast<CapturedDecl>(DC))
2325e20cdd8SDimitry Andric     DC = cast<DeclContext>(CD->getNonClosureContext());
23306d4ba38SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
234cfca06d7SDimitry Andric     ContextName = std::string(CGM.getMangledName(FD));
23506d4ba38SDimitry Andric   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
236cfca06d7SDimitry Andric     ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
23706d4ba38SDimitry Andric   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
23806d4ba38SDimitry Andric     ContextName = OMD->getSelector().getAsString();
23934d02d0bSRoman Divacky   else
24036981b17SDimitry Andric     llvm_unreachable("Unknown context for static var decl");
24134d02d0bSRoman Divacky 
24206d4ba38SDimitry Andric   ContextName += "." + D.getNameAsString();
24306d4ba38SDimitry Andric   return ContextName;
24434d02d0bSRoman Divacky }
24534d02d0bSRoman Divacky 
getOrCreateStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)24606d4ba38SDimitry Andric llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
24706d4ba38SDimitry Andric     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
24806d4ba38SDimitry Andric   // In general, we don't always emit static var decls once before we reference
24906d4ba38SDimitry Andric   // them. It is possible to reference them before emitting the function that
25006d4ba38SDimitry Andric   // contains them, and it is possible to emit the containing function multiple
25106d4ba38SDimitry Andric   // times.
25206d4ba38SDimitry Andric   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
25306d4ba38SDimitry Andric     return ExistingGV;
25406d4ba38SDimitry Andric 
255ec2b103cSEd Schouten   QualType Ty = D.getType();
256ec2b103cSEd Schouten   assert(Ty->isConstantSizeType() && "VLAs can't be static");
257ec2b103cSEd Schouten 
258dbe13110SDimitry Andric   // Use the label if the variable is renamed with the asm-label extension.
259dbe13110SDimitry Andric   std::string Name;
260dbe13110SDimitry Andric   if (D.hasAttr<AsmLabelAttr>())
261cfca06d7SDimitry Andric     Name = std::string(getMangledName(&D));
262dbe13110SDimitry Andric   else
26306d4ba38SDimitry Andric     Name = getStaticDeclName(*this, D);
264ec2b103cSEd Schouten 
26506d4ba38SDimitry Andric   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
266461a67faSDimitry Andric   LangAS AS = GetGlobalVarAddressSpace(&D);
2678746d127SDimitry Andric   unsigned TargetAS = getContext().getTargetAddressSpace(AS);
26806d4ba38SDimitry Andric 
26948675466SDimitry Andric   // OpenCL variables in local address space and CUDA shared
27048675466SDimitry Andric   // variables cannot have an initializer.
27106d4ba38SDimitry Andric   llvm::Constant *Init = nullptr;
27248675466SDimitry Andric   if (Ty.getAddressSpace() == LangAS::opencl_local ||
273cfca06d7SDimitry Andric       D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
27406d4ba38SDimitry Andric     Init = llvm::UndefValue::get(LTy);
27548675466SDimitry Andric   else
27648675466SDimitry Andric     Init = EmitNullConstant(Ty);
27706d4ba38SDimitry Andric 
2788746d127SDimitry Andric   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2798746d127SDimitry Andric       getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
2808746d127SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
281519fc96cSDimitry Andric   GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
28206d4ba38SDimitry Andric 
2835e20cdd8SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
2845e20cdd8SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2855e20cdd8SDimitry Andric 
2866a037251SDimitry Andric   if (D.getTLSKind())
28706d4ba38SDimitry Andric     setTLSMode(GV, D);
28856d91b49SDimitry Andric 
28948675466SDimitry Andric   setGVProperties(GV, &D);
290ac9a064cSDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(cast<Decl>(&D), GV, *this);
2919f4dbff6SDimitry Andric 
2929f4dbff6SDimitry Andric   // Make sure the result is of the correct type.
293461a67faSDimitry Andric   LangAS ExpectedAS = Ty.getAddressSpace();
29406d4ba38SDimitry Andric   llvm::Constant *Addr = GV;
2958746d127SDimitry Andric   if (AS != ExpectedAS) {
2968746d127SDimitry Andric     Addr = getTargetCodeGenInfo().performAddrSpaceCast(
2978746d127SDimitry Andric         *this, GV, AS, ExpectedAS,
2987fa27ce4SDimitry Andric         llvm::PointerType::get(getLLVMContext(),
2997fa27ce4SDimitry Andric                                getContext().getTargetAddressSpace(ExpectedAS)));
3009f4dbff6SDimitry Andric   }
3019f4dbff6SDimitry Andric 
30206d4ba38SDimitry Andric   setStaticLocalDeclAddress(&D, Addr);
30306d4ba38SDimitry Andric 
30406d4ba38SDimitry Andric   // Ensure that the static local gets initialized by making sure the parent
30506d4ba38SDimitry Andric   // function gets emitted eventually.
30606d4ba38SDimitry Andric   const Decl *DC = cast<Decl>(D.getDeclContext());
30706d4ba38SDimitry Andric 
30806d4ba38SDimitry Andric   // We can't name blocks or captured statements directly, so try to emit their
30906d4ba38SDimitry Andric   // parents.
31006d4ba38SDimitry Andric   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
31106d4ba38SDimitry Andric     DC = DC->getNonClosureContext();
31206d4ba38SDimitry Andric     // FIXME: Ensure that global blocks get emitted.
31306d4ba38SDimitry Andric     if (!DC)
31406d4ba38SDimitry Andric       return Addr;
31506d4ba38SDimitry Andric   }
31606d4ba38SDimitry Andric 
31706d4ba38SDimitry Andric   GlobalDecl GD;
31806d4ba38SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
31906d4ba38SDimitry Andric     GD = GlobalDecl(CD, Ctor_Base);
32006d4ba38SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
32106d4ba38SDimitry Andric     GD = GlobalDecl(DD, Dtor_Base);
32206d4ba38SDimitry Andric   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
32306d4ba38SDimitry Andric     GD = GlobalDecl(FD);
32406d4ba38SDimitry Andric   else {
32506d4ba38SDimitry Andric     // Don't do anything for Obj-C method decls or global closures. We should
32606d4ba38SDimitry Andric     // never defer them.
32706d4ba38SDimitry Andric     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
32806d4ba38SDimitry Andric   }
32948675466SDimitry Andric   if (GD.getDecl()) {
33048675466SDimitry Andric     // Disable emission of the parent function for the OpenMP device codegen.
33148675466SDimitry Andric     CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
33206d4ba38SDimitry Andric     (void)GetAddrOfGlobal(GD);
33348675466SDimitry Andric   }
33406d4ba38SDimitry Andric 
33506d4ba38SDimitry Andric   return Addr;
336ec2b103cSEd Schouten }
337ec2b103cSEd Schouten 
338bca07a45SDimitry Andric /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
33934d02d0bSRoman Divacky /// global variable that has already been created for it.  If the initializer
34034d02d0bSRoman Divacky /// has a different type than GV does, this may free GV and return a different
34134d02d0bSRoman Divacky /// one.  Otherwise it just returns GV.
34234d02d0bSRoman Divacky llvm::GlobalVariable *
AddInitializerToStaticVarDecl(const VarDecl & D,llvm::GlobalVariable * GV)343bca07a45SDimitry Andric CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
34434d02d0bSRoman Divacky                                                llvm::GlobalVariable *GV) {
345461a67faSDimitry Andric   ConstantEmitter emitter(*this);
346461a67faSDimitry Andric   llvm::Constant *Init = emitter.tryEmitForInitializer(D);
347ec2b103cSEd Schouten 
348ec2b103cSEd Schouten   // If constant emission failed, then this should be a C++ static
349ec2b103cSEd Schouten   // initializer.
350ec2b103cSEd Schouten   if (!Init) {
35113cc256eSDimitry Andric     if (!getLangOpts().CPlusPlus)
352ec2b103cSEd Schouten       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
353145449b1SDimitry Andric     else if (D.hasFlexibleArrayInit(getContext()))
354145449b1SDimitry Andric       CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
355d2e0a8ddSDimitry Andric     else if (HaveInsertPoint()) {
356ecb7e5c8SRoman Divacky       // Since we have a static initializer, this global variable can't
357ecb7e5c8SRoman Divacky       // be constant.
358ecb7e5c8SRoman Divacky       GV->setConstant(false);
359ecb7e5c8SRoman Divacky 
360dbe13110SDimitry Andric       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
361ecb7e5c8SRoman Divacky     }
36234d02d0bSRoman Divacky     return GV;
36334d02d0bSRoman Divacky   }
36434d02d0bSRoman Divacky 
365145449b1SDimitry Andric #ifndef NDEBUG
366145449b1SDimitry Andric   CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
367145449b1SDimitry Andric                       D.getFlexibleArrayInitChars(getContext());
368145449b1SDimitry Andric   CharUnits CstSize = CharUnits::fromQuantity(
369145449b1SDimitry Andric       CGM.getDataLayout().getTypeAllocSize(Init->getType()));
370145449b1SDimitry Andric   assert(VarSize == CstSize && "Emitted constant has unexpected size");
371145449b1SDimitry Andric #endif
372145449b1SDimitry Andric 
373ec2b103cSEd Schouten   // The initializer may differ in type from the global. Rewrite
374ec2b103cSEd Schouten   // the global to match the initializer.  (We have to do this
375ec2b103cSEd Schouten   // because some types, like unions, can't be completely represented
376ec2b103cSEd Schouten   // in the LLVM type system.)
377cfca06d7SDimitry Andric   if (GV->getValueType() != Init->getType()) {
378ec2b103cSEd Schouten     llvm::GlobalVariable *OldGV = GV;
379ec2b103cSEd Schouten 
380b60736ecSDimitry Andric     GV = new llvm::GlobalVariable(
381b60736ecSDimitry Andric         CGM.getModule(), Init->getType(), OldGV->isConstant(),
382ec2b103cSEd Schouten         OldGV->getLinkage(), Init, "",
383b60736ecSDimitry Andric         /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
384b60736ecSDimitry Andric         OldGV->getType()->getPointerAddressSpace());
385bca07a45SDimitry Andric     GV->setVisibility(OldGV->getVisibility());
38648675466SDimitry Andric     GV->setDSOLocal(OldGV->isDSOLocal());
38745b53394SDimitry Andric     GV->setComdat(OldGV->getComdat());
388ec2b103cSEd Schouten 
389ec2b103cSEd Schouten     // Steal the name of the old global
390ec2b103cSEd Schouten     GV->takeName(OldGV);
391ec2b103cSEd Schouten 
392ec2b103cSEd Schouten     // Replace all uses of the old global with the new global
393b1c73532SDimitry Andric     OldGV->replaceAllUsesWith(GV);
394ec2b103cSEd Schouten 
395ec2b103cSEd Schouten     // Erase the old global, since it is no longer used.
396ec2b103cSEd Schouten     OldGV->eraseFromParent();
397ec2b103cSEd Schouten   }
398ec2b103cSEd Schouten 
3997fa27ce4SDimitry Andric   bool NeedsDtor =
4007fa27ce4SDimitry Andric       D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4017fa27ce4SDimitry Andric 
402b1c73532SDimitry Andric   GV->setConstant(
403b1c73532SDimitry Andric       D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
404ec2b103cSEd Schouten   GV->setInitializer(Init);
405dbe13110SDimitry Andric 
406461a67faSDimitry Andric   emitter.finalize(GV);
407461a67faSDimitry Andric 
4087fa27ce4SDimitry Andric   if (NeedsDtor && HaveInsertPoint()) {
409dbe13110SDimitry Andric     // We have a constant initializer, but a nontrivial destructor. We still
410dbe13110SDimitry Andric     // need to perform a guarded "initialization" in order to register the
411dbe13110SDimitry Andric     // destructor.
412dbe13110SDimitry Andric     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
413dbe13110SDimitry Andric   }
414dbe13110SDimitry Andric 
41534d02d0bSRoman Divacky   return GV;
416ec2b103cSEd Schouten }
41734d02d0bSRoman Divacky 
EmitStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)418bca07a45SDimitry Andric void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
419ecb7e5c8SRoman Divacky                                       llvm::GlobalValue::LinkageTypes Linkage) {
420dbe13110SDimitry Andric   // Check to see if we already have a global variable for this
421dbe13110SDimitry Andric   // declaration.  This can happen when double-emitting function
422dbe13110SDimitry Andric   // bodies, e.g. with complete and base constructors.
42306d4ba38SDimitry Andric   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
42445b53394SDimitry Andric   CharUnits alignment = getContext().getDeclAlign(&D);
42534d02d0bSRoman Divacky 
42634d02d0bSRoman Divacky   // Store into LocalDeclMap before generating initializer to handle
42734d02d0bSRoman Divacky   // circular references.
42877fc4c14SDimitry Andric   llvm::Type *elemTy = ConvertTypeForMem(D.getType());
42977fc4c14SDimitry Andric   setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
43034d02d0bSRoman Divacky 
431be17651fSRoman Divacky   // We can't have a VLA here, but we can have a pointer to a VLA,
432be17651fSRoman Divacky   // even though that doesn't really make any sense.
43334d02d0bSRoman Divacky   // Make sure to evaluate VLA bounds now so that we have them for later.
43434d02d0bSRoman Divacky   if (D.getType()->isVariablyModifiedType())
435180abc3dSDimitry Andric     EmitVariablyModifiedType(D.getType());
43634d02d0bSRoman Divacky 
437dbe13110SDimitry Andric   // Save the type in case adding the initializer forces a type change.
438dbe13110SDimitry Andric   llvm::Type *expectedType = addr->getType();
439bca07a45SDimitry Andric 
4409f4dbff6SDimitry Andric   llvm::GlobalVariable *var =
4419f4dbff6SDimitry Andric     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
4422b6b257fSDimitry Andric 
4432b6b257fSDimitry Andric   // CUDA's local and local static __shared__ variables should not
4442b6b257fSDimitry Andric   // have any non-empty initializers. This is ensured by Sema.
4452b6b257fSDimitry Andric   // Whatever initializer such variable may have when it gets here is
4462b6b257fSDimitry Andric   // a no-op and should not be emitted.
4472b6b257fSDimitry Andric   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4482b6b257fSDimitry Andric                          D.hasAttr<CUDASharedAttr>();
44934d02d0bSRoman Divacky   // If this value has an initializer, emit it.
4502b6b257fSDimitry Andric   if (D.getInit() && !isCudaSharedVar)
451dbe13110SDimitry Andric     var = AddInitializerToStaticVarDecl(D, var);
452ec2b103cSEd Schouten 
453519fc96cSDimitry Andric   var->setAlignment(alignment.getAsAlign());
4544a37f65fSRoman Divacky 
45536981b17SDimitry Andric   if (D.hasAttr<AnnotateAttr>())
456dbe13110SDimitry Andric     CGM.AddGlobalAnnotations(&D, var);
457ec2b103cSEd Schouten 
4581b08b196SDimitry Andric   if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
4591b08b196SDimitry Andric     var->addAttribute("bss-section", SA->getName());
4601b08b196SDimitry Andric   if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
4611b08b196SDimitry Andric     var->addAttribute("data-section", SA->getName());
4621b08b196SDimitry Andric   if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
4631b08b196SDimitry Andric     var->addAttribute("rodata-section", SA->getName());
464519fc96cSDimitry Andric   if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
465519fc96cSDimitry Andric     var->addAttribute("relro-section", SA->getName());
4661b08b196SDimitry Andric 
4675362a71cSEd Schouten   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
468dbe13110SDimitry Andric     var->setSection(SA->getName());
469ec2b103cSEd Schouten 
470344a3780SDimitry Andric   if (D.hasAttr<RetainAttr>())
4719f4dbff6SDimitry Andric     CGM.addUsedGlobal(var);
472344a3780SDimitry Andric   else if (D.hasAttr<UsedAttr>())
473344a3780SDimitry Andric     CGM.addUsedOrCompilerUsedGlobal(var);
474ec2b103cSEd Schouten 
4757fa27ce4SDimitry Andric   if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
4767fa27ce4SDimitry Andric     CGM.addUsedOrCompilerUsedGlobal(var);
4777fa27ce4SDimitry Andric 
478ec2b103cSEd Schouten   // We may have to cast the constant because of the initializer
479ec2b103cSEd Schouten   // mismatch above.
480ec2b103cSEd Schouten   //
481ec2b103cSEd Schouten   // FIXME: It is really dangerous to store this in the map; if anyone
482ec2b103cSEd Schouten   // RAUW's the GV uses of this constant will be invalid.
4839f4dbff6SDimitry Andric   llvm::Constant *castedAddr =
4849f4dbff6SDimitry Andric     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
48577fc4c14SDimitry Andric   LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
486dbe13110SDimitry Andric   CGM.setStaticLocalDeclAddress(&D, castedAddr);
487ec2b103cSEd Schouten 
488145449b1SDimitry Andric   CGM.getSanitizerMetadata()->reportGlobal(var, D);
4899f4dbff6SDimitry Andric 
490ec2b103cSEd Schouten   // Emit global variable debug descriptor for static vars.
491ec2b103cSEd Schouten   CGDebugInfo *DI = getDebugInfo();
492706b4fc4SDimitry Andric   if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
493ec2b103cSEd Schouten     DI->setLocation(D.getLocation());
494dbe13110SDimitry Andric     DI->EmitGlobalVariable(var, &D);
495ec2b103cSEd Schouten   }
496ec2b103cSEd Schouten }
497ec2b103cSEd Schouten 
4984e58654bSRoman Divacky namespace {
49945b53394SDimitry Andric   struct DestroyObject final : EHScopeStack::Cleanup {
DestroyObject__anon7fada2950111::DestroyObject50045b53394SDimitry Andric     DestroyObject(Address addr, QualType type,
501180abc3dSDimitry Andric                   CodeGenFunction::Destroyer *destroyer,
502180abc3dSDimitry Andric                   bool useEHCleanupForArray)
503dbe13110SDimitry Andric       : addr(addr), type(type), destroyer(destroyer),
504180abc3dSDimitry Andric         useEHCleanupForArray(useEHCleanupForArray) {}
5054e58654bSRoman Divacky 
50645b53394SDimitry Andric     Address addr;
507180abc3dSDimitry Andric     QualType type;
508dbe13110SDimitry Andric     CodeGenFunction::Destroyer *destroyer;
509180abc3dSDimitry Andric     bool useEHCleanupForArray;
5104e58654bSRoman Divacky 
Emit__anon7fada2950111::DestroyObject5119f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
512180abc3dSDimitry Andric       // Don't use an EH cleanup recursively from an EH cleanup.
513180abc3dSDimitry Andric       bool useEHCleanupForArray =
514180abc3dSDimitry Andric         flags.isForNormalCleanup() && this->useEHCleanupForArray;
515180abc3dSDimitry Andric 
516180abc3dSDimitry Andric       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
5174e58654bSRoman Divacky     }
5184e58654bSRoman Divacky   };
5194e58654bSRoman Divacky 
52048675466SDimitry Andric   template <class Derived>
52148675466SDimitry Andric   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
DestroyNRVOVariable__anon7fada2950111::DestroyNRVOVariable52222989816SDimitry Andric     DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
52322989816SDimitry Andric         : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
5244e58654bSRoman Divacky 
5254e58654bSRoman Divacky     llvm::Value *NRVOFlag;
52645b53394SDimitry Andric     Address Loc;
52722989816SDimitry Andric     QualType Ty;
5284e58654bSRoman Divacky 
Emit__anon7fada2950111::DestroyNRVOVariable5299f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
5304e58654bSRoman Divacky       // Along the exceptions path we always execute the dtor.
531180abc3dSDimitry Andric       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
5324e58654bSRoman Divacky 
5339f4dbff6SDimitry Andric       llvm::BasicBlock *SkipDtorBB = nullptr;
5344e58654bSRoman Divacky       if (NRVO) {
5354e58654bSRoman Divacky         // If we exited via NRVO, we skip the destructor call.
5364e58654bSRoman Divacky         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
5374e58654bSRoman Divacky         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
53845b53394SDimitry Andric         llvm::Value *DidNRVO =
53945b53394SDimitry Andric           CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
5404e58654bSRoman Divacky         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
5414e58654bSRoman Divacky         CGF.EmitBlock(RunDtorBB);
5424e58654bSRoman Divacky       }
5434e58654bSRoman Divacky 
54448675466SDimitry Andric       static_cast<Derived *>(this)->emitDestructorCall(CGF);
5454e58654bSRoman Divacky 
5464e58654bSRoman Divacky       if (NRVO) CGF.EmitBlock(SkipDtorBB);
5474e58654bSRoman Divacky     }
54848675466SDimitry Andric 
54948675466SDimitry Andric     virtual ~DestroyNRVOVariable() = default;
55048675466SDimitry Andric   };
55148675466SDimitry Andric 
55248675466SDimitry Andric   struct DestroyNRVOVariableCXX final
55348675466SDimitry Andric       : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
DestroyNRVOVariableCXX__anon7fada2950111::DestroyNRVOVariableCXX55422989816SDimitry Andric     DestroyNRVOVariableCXX(Address addr, QualType type,
55522989816SDimitry Andric                            const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
55622989816SDimitry Andric         : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
55748675466SDimitry Andric           Dtor(Dtor) {}
55848675466SDimitry Andric 
55948675466SDimitry Andric     const CXXDestructorDecl *Dtor;
56048675466SDimitry Andric 
emitDestructorCall__anon7fada2950111::DestroyNRVOVariableCXX56148675466SDimitry Andric     void emitDestructorCall(CodeGenFunction &CGF) {
56248675466SDimitry Andric       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
56348675466SDimitry Andric                                 /*ForVirtualBase=*/false,
56422989816SDimitry Andric                                 /*Delegating=*/false, Loc, Ty);
56548675466SDimitry Andric     }
56648675466SDimitry Andric   };
56748675466SDimitry Andric 
56848675466SDimitry Andric   struct DestroyNRVOVariableC final
56948675466SDimitry Andric       : DestroyNRVOVariable<DestroyNRVOVariableC> {
DestroyNRVOVariableC__anon7fada2950111::DestroyNRVOVariableC57048675466SDimitry Andric     DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
57122989816SDimitry Andric         : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
57248675466SDimitry Andric 
emitDestructorCall__anon7fada2950111::DestroyNRVOVariableC57348675466SDimitry Andric     void emitDestructorCall(CodeGenFunction &CGF) {
57448675466SDimitry Andric       CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
57548675466SDimitry Andric     }
5764e58654bSRoman Divacky   };
5774e58654bSRoman Divacky 
57845b53394SDimitry Andric   struct CallStackRestore final : EHScopeStack::Cleanup {
57945b53394SDimitry Andric     Address Stack;
CallStackRestore__anon7fada2950111::CallStackRestore58045b53394SDimitry Andric     CallStackRestore(Address Stack) : Stack(Stack) {}
isRedundantBeforeReturn__anon7fada2950111::CallStackRestore581344a3780SDimitry Andric     bool isRedundantBeforeReturn() override { return true; }
Emit__anon7fada2950111::CallStackRestore5829f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
58336981b17SDimitry Andric       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
584b1c73532SDimitry Andric       CGF.Builder.CreateStackRestore(V);
5853d1dcd9bSDimitry Andric     }
5863d1dcd9bSDimitry Andric   };
5873d1dcd9bSDimitry Andric 
5887fa27ce4SDimitry Andric   struct KmpcAllocFree final : EHScopeStack::Cleanup {
5897fa27ce4SDimitry Andric     std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
KmpcAllocFree__anon7fada2950111::KmpcAllocFree5907fa27ce4SDimitry Andric     KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
5917fa27ce4SDimitry Andric         : AddrSizePair(AddrSizePair) {}
Emit__anon7fada2950111::KmpcAllocFree5927fa27ce4SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
5937fa27ce4SDimitry Andric       auto &RT = CGF.CGM.getOpenMPRuntime();
5947fa27ce4SDimitry Andric       RT.getKmpcFreeShared(CGF, AddrSizePair);
5957fa27ce4SDimitry Andric     }
5967fa27ce4SDimitry Andric   };
5977fa27ce4SDimitry Andric 
59845b53394SDimitry Andric   struct ExtendGCLifetime final : EHScopeStack::Cleanup {
599180abc3dSDimitry Andric     const VarDecl &Var;
ExtendGCLifetime__anon7fada2950111::ExtendGCLifetime600180abc3dSDimitry Andric     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
601180abc3dSDimitry Andric 
Emit__anon7fada2950111::ExtendGCLifetime6029f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
603180abc3dSDimitry Andric       // Compute the address of the local variable, in case it's a
604180abc3dSDimitry Andric       // byref or something.
605676fbe81SDimitry Andric       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
606dbe13110SDimitry Andric                       Var.getType(), VK_LValue, SourceLocation());
607bfef3995SDimitry Andric       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
608bfef3995SDimitry Andric                                                 SourceLocation());
609180abc3dSDimitry Andric       CGF.EmitExtendGCLifetime(value);
610180abc3dSDimitry Andric     }
611180abc3dSDimitry Andric   };
612180abc3dSDimitry Andric 
61345b53394SDimitry Andric   struct CallCleanupFunction final : EHScopeStack::Cleanup {
6143d1dcd9bSDimitry Andric     llvm::Constant *CleanupFn;
6153d1dcd9bSDimitry Andric     const CGFunctionInfo &FnInfo;
6163d1dcd9bSDimitry Andric     const VarDecl &Var;
6173d1dcd9bSDimitry Andric 
CallCleanupFunction__anon7fada2950111::CallCleanupFunction6183d1dcd9bSDimitry Andric     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
619c3b054d2SDimitry Andric                         const VarDecl *Var)
620c3b054d2SDimitry Andric       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
6213d1dcd9bSDimitry Andric 
Emit__anon7fada2950111::CallCleanupFunction6229f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
623676fbe81SDimitry Andric       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
624dbe13110SDimitry Andric                       Var.getType(), VK_LValue, SourceLocation());
625c3b054d2SDimitry Andric       // Compute the address of the local variable, in case it's a byref
626c3b054d2SDimitry Andric       // or something.
627706b4fc4SDimitry Andric       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
628c3b054d2SDimitry Andric 
6293d1dcd9bSDimitry Andric       // In some cases, the type of the function argument will be different from
6303d1dcd9bSDimitry Andric       // the type of the pointer. An example of this is
6313d1dcd9bSDimitry Andric       // void f(void* arg);
6323d1dcd9bSDimitry Andric       // __attribute__((cleanup(f))) void *g;
6333d1dcd9bSDimitry Andric       //
6343d1dcd9bSDimitry Andric       // To fix this we insert a bitcast here.
6353d1dcd9bSDimitry Andric       QualType ArgTy = FnInfo.arg_begin()->type;
6363d1dcd9bSDimitry Andric       llvm::Value *Arg =
6373d1dcd9bSDimitry Andric         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
6383d1dcd9bSDimitry Andric 
6393d1dcd9bSDimitry Andric       CallArgList Args;
64001af97d3SDimitry Andric       Args.add(RValue::get(Arg),
64101af97d3SDimitry Andric                CGF.getContext().getPointerType(Var.getType()));
642bab175ecSDimitry Andric       auto Callee = CGCallee::forDirect(CleanupFn);
643bab175ecSDimitry Andric       CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
6443d1dcd9bSDimitry Andric     }
6453d1dcd9bSDimitry Andric   };
6462b6b257fSDimitry Andric } // end anonymous namespace
6473d1dcd9bSDimitry Andric 
648180abc3dSDimitry Andric /// EmitAutoVarWithLifetime - Does the setup required for an automatic
649180abc3dSDimitry Andric /// variable with lifetime.
EmitAutoVarWithLifetime(CodeGenFunction & CGF,const VarDecl & var,Address addr,Qualifiers::ObjCLifetime lifetime)650180abc3dSDimitry Andric static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
65145b53394SDimitry Andric                                     Address addr,
652180abc3dSDimitry Andric                                     Qualifiers::ObjCLifetime lifetime) {
653180abc3dSDimitry Andric   switch (lifetime) {
654180abc3dSDimitry Andric   case Qualifiers::OCL_None:
655180abc3dSDimitry Andric     llvm_unreachable("present but none");
656180abc3dSDimitry Andric 
657180abc3dSDimitry Andric   case Qualifiers::OCL_ExplicitNone:
658180abc3dSDimitry Andric     // nothing to do
659180abc3dSDimitry Andric     break;
660180abc3dSDimitry Andric 
661180abc3dSDimitry Andric   case Qualifiers::OCL_Strong: {
662dbe13110SDimitry Andric     CodeGenFunction::Destroyer *destroyer =
663180abc3dSDimitry Andric       (var.hasAttr<ObjCPreciseLifetimeAttr>()
664180abc3dSDimitry Andric        ? CodeGenFunction::destroyARCStrongPrecise
665180abc3dSDimitry Andric        : CodeGenFunction::destroyARCStrongImprecise);
666180abc3dSDimitry Andric 
667180abc3dSDimitry Andric     CleanupKind cleanupKind = CGF.getARCCleanupKind();
668180abc3dSDimitry Andric     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
669180abc3dSDimitry Andric                     cleanupKind & EHCleanup);
670180abc3dSDimitry Andric     break;
671180abc3dSDimitry Andric   }
672180abc3dSDimitry Andric   case Qualifiers::OCL_Autoreleasing:
673180abc3dSDimitry Andric     // nothing to do
674180abc3dSDimitry Andric     break;
675180abc3dSDimitry Andric 
676180abc3dSDimitry Andric   case Qualifiers::OCL_Weak:
677180abc3dSDimitry Andric     // __weak objects always get EH cleanups; otherwise, exceptions
678180abc3dSDimitry Andric     // could cause really nasty crashes instead of mere leaks.
679180abc3dSDimitry Andric     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
680180abc3dSDimitry Andric                     CodeGenFunction::destroyARCWeak,
681180abc3dSDimitry Andric                     /*useEHCleanup*/ true);
682180abc3dSDimitry Andric     break;
683180abc3dSDimitry Andric   }
684180abc3dSDimitry Andric }
685180abc3dSDimitry Andric 
isAccessedBy(const VarDecl & var,const Stmt * s)686180abc3dSDimitry Andric static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
687180abc3dSDimitry Andric   if (const Expr *e = dyn_cast<Expr>(s)) {
688180abc3dSDimitry Andric     // Skip the most common kinds of expressions that make
689180abc3dSDimitry Andric     // hierarchy-walking expensive.
690180abc3dSDimitry Andric     s = e = e->IgnoreParenCasts();
691180abc3dSDimitry Andric 
692180abc3dSDimitry Andric     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
693180abc3dSDimitry Andric       return (ref->getDecl() == &var);
69456d91b49SDimitry Andric     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
69556d91b49SDimitry Andric       const BlockDecl *block = be->getBlockDecl();
6969f4dbff6SDimitry Andric       for (const auto &I : block->captures()) {
6979f4dbff6SDimitry Andric         if (I.getVariable() == &var)
69856d91b49SDimitry Andric           return true;
69956d91b49SDimitry Andric       }
70056d91b49SDimitry Andric     }
701180abc3dSDimitry Andric   }
702180abc3dSDimitry Andric 
703c192b3dcSDimitry Andric   for (const Stmt *SubStmt : s->children())
704c192b3dcSDimitry Andric     // SubStmt might be null; as in missing decl or conditional of an if-stmt.
705c192b3dcSDimitry Andric     if (SubStmt && isAccessedBy(var, SubStmt))
706180abc3dSDimitry Andric       return true;
707180abc3dSDimitry Andric 
708180abc3dSDimitry Andric   return false;
709180abc3dSDimitry Andric }
710180abc3dSDimitry Andric 
isAccessedBy(const ValueDecl * decl,const Expr * e)711180abc3dSDimitry Andric static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
712180abc3dSDimitry Andric   if (!decl) return false;
713180abc3dSDimitry Andric   if (!isa<VarDecl>(decl)) return false;
714180abc3dSDimitry Andric   const VarDecl *var = cast<VarDecl>(decl);
715180abc3dSDimitry Andric   return isAccessedBy(*var, e);
716180abc3dSDimitry Andric }
717180abc3dSDimitry Andric 
tryEmitARCCopyWeakInit(CodeGenFunction & CGF,const LValue & destLV,const Expr * init)71845b53394SDimitry Andric static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
71945b53394SDimitry Andric                                    const LValue &destLV, const Expr *init) {
72045b53394SDimitry Andric   bool needsCast = false;
72145b53394SDimitry Andric 
72245b53394SDimitry Andric   while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
72345b53394SDimitry Andric     switch (castExpr->getCastKind()) {
72445b53394SDimitry Andric     // Look through casts that don't require representation changes.
72545b53394SDimitry Andric     case CK_NoOp:
72645b53394SDimitry Andric     case CK_BitCast:
72745b53394SDimitry Andric     case CK_BlockPointerToObjCPointerCast:
72845b53394SDimitry Andric       needsCast = true;
72945b53394SDimitry Andric       break;
73045b53394SDimitry Andric 
73145b53394SDimitry Andric     // If we find an l-value to r-value cast from a __weak variable,
73245b53394SDimitry Andric     // emit this operation as a copy or move.
73345b53394SDimitry Andric     case CK_LValueToRValue: {
73445b53394SDimitry Andric       const Expr *srcExpr = castExpr->getSubExpr();
73545b53394SDimitry Andric       if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
73645b53394SDimitry Andric         return false;
73745b53394SDimitry Andric 
73845b53394SDimitry Andric       // Emit the source l-value.
73945b53394SDimitry Andric       LValue srcLV = CGF.EmitLValue(srcExpr);
74045b53394SDimitry Andric 
74145b53394SDimitry Andric       // Handle a formal type change to avoid asserting.
742ac9a064cSDimitry Andric       auto srcAddr = srcLV.getAddress();
74345b53394SDimitry Andric       if (needsCast) {
744ac9a064cSDimitry Andric         srcAddr = srcAddr.withElementType(destLV.getAddress().getElementType());
74545b53394SDimitry Andric       }
74645b53394SDimitry Andric 
74745b53394SDimitry Andric       // If it was an l-value, use objc_copyWeak.
748344a3780SDimitry Andric       if (srcExpr->isLValue()) {
749ac9a064cSDimitry Andric         CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
75045b53394SDimitry Andric       } else {
751344a3780SDimitry Andric         assert(srcExpr->isXValue());
752ac9a064cSDimitry Andric         CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
75345b53394SDimitry Andric       }
75445b53394SDimitry Andric       return true;
75545b53394SDimitry Andric     }
75645b53394SDimitry Andric 
75745b53394SDimitry Andric     // Stop at anything else.
75845b53394SDimitry Andric     default:
75945b53394SDimitry Andric       return false;
76045b53394SDimitry Andric     }
76145b53394SDimitry Andric 
76245b53394SDimitry Andric     init = castExpr->getSubExpr();
76345b53394SDimitry Andric   }
76445b53394SDimitry Andric   return false;
76545b53394SDimitry Andric }
76645b53394SDimitry Andric 
drillIntoBlockVariable(CodeGenFunction & CGF,LValue & lvalue,const VarDecl * var)767180abc3dSDimitry Andric static void drillIntoBlockVariable(CodeGenFunction &CGF,
768180abc3dSDimitry Andric                                    LValue &lvalue,
769180abc3dSDimitry Andric                                    const VarDecl *var) {
770ac9a064cSDimitry Andric   lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
771180abc3dSDimitry Andric }
772180abc3dSDimitry Andric 
EmitNullabilityCheck(LValue LHS,llvm::Value * RHS,SourceLocation Loc)7737442d6faSDimitry Andric void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
7747442d6faSDimitry Andric                                            SourceLocation Loc) {
7757442d6faSDimitry Andric   if (!SanOpts.has(SanitizerKind::NullabilityAssign))
7767442d6faSDimitry Andric     return;
7777442d6faSDimitry Andric 
778e3b55780SDimitry Andric   auto Nullability = LHS.getType()->getNullability();
7797442d6faSDimitry Andric   if (!Nullability || *Nullability != NullabilityKind::NonNull)
7807442d6faSDimitry Andric     return;
7817442d6faSDimitry Andric 
7827442d6faSDimitry Andric   // Check if the right hand side of the assignment is nonnull, if the left
7837442d6faSDimitry Andric   // hand side must be nonnull.
7847442d6faSDimitry Andric   SanitizerScope SanScope(this);
7857442d6faSDimitry Andric   llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
7867442d6faSDimitry Andric   llvm::Constant *StaticData[] = {
7877442d6faSDimitry Andric       EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
7887442d6faSDimitry Andric       llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
7897442d6faSDimitry Andric       llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
7907442d6faSDimitry Andric   EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
7917442d6faSDimitry Andric             SanitizerHandler::TypeMismatch, StaticData, RHS);
7927442d6faSDimitry Andric }
7937442d6faSDimitry Andric 
EmitScalarInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)79406d4ba38SDimitry Andric void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
79506d4ba38SDimitry Andric                                      LValue lvalue, bool capturedByInit) {
796180abc3dSDimitry Andric   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
797180abc3dSDimitry Andric   if (!lifetime) {
798180abc3dSDimitry Andric     llvm::Value *value = EmitScalarExpr(init);
799180abc3dSDimitry Andric     if (capturedByInit)
800180abc3dSDimitry Andric       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
8017442d6faSDimitry Andric     EmitNullabilityCheck(lvalue, value, init->getExprLoc());
802dbe13110SDimitry Andric     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
803180abc3dSDimitry Andric     return;
804180abc3dSDimitry Andric   }
805180abc3dSDimitry Andric 
8069f4dbff6SDimitry Andric   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
8079f4dbff6SDimitry Andric     init = DIE->getExpr();
8089f4dbff6SDimitry Andric 
809180abc3dSDimitry Andric   // If we're emitting a value with lifetime, we have to do the
810180abc3dSDimitry Andric   // initialization *before* we leave the cleanup scopes.
811344a3780SDimitry Andric   if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
812dbe13110SDimitry Andric     CodeGenFunction::RunCleanupsScope Scope(*this);
813344a3780SDimitry Andric     return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
814344a3780SDimitry Andric   }
815180abc3dSDimitry Andric 
816180abc3dSDimitry Andric   // We have to maintain the illusion that the variable is
817180abc3dSDimitry Andric   // zero-initialized.  If the variable might be accessed in its
818180abc3dSDimitry Andric   // initializer, zero-initialize before running the initializer, then
819180abc3dSDimitry Andric   // actually perform the initialization with an assign.
820180abc3dSDimitry Andric   bool accessedByInit = false;
821180abc3dSDimitry Andric   if (lifetime != Qualifiers::OCL_ExplicitNone)
82236981b17SDimitry Andric     accessedByInit = (capturedByInit || isAccessedBy(D, init));
823180abc3dSDimitry Andric   if (accessedByInit) {
824180abc3dSDimitry Andric     LValue tempLV = lvalue;
825180abc3dSDimitry Andric     // Drill down to the __block object if necessary.
826180abc3dSDimitry Andric     if (capturedByInit) {
827180abc3dSDimitry Andric       // We can use a simple GEP for this because it can't have been
828180abc3dSDimitry Andric       // moved yet.
829ac9a064cSDimitry Andric       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
83045b53394SDimitry Andric                                               cast<VarDecl>(D),
83145b53394SDimitry Andric                                               /*follow*/ false));
832180abc3dSDimitry Andric     }
833180abc3dSDimitry Andric 
834ac9a064cSDimitry Andric     auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
835bab175ecSDimitry Andric     llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
836180abc3dSDimitry Andric 
837180abc3dSDimitry Andric     // If __weak, we want to use a barrier under certain conditions.
838180abc3dSDimitry Andric     if (lifetime == Qualifiers::OCL_Weak)
839ac9a064cSDimitry Andric       EmitARCInitWeak(tempLV.getAddress(), zero);
840180abc3dSDimitry Andric 
841180abc3dSDimitry Andric     // Otherwise just do a simple store.
842180abc3dSDimitry Andric     else
843dbe13110SDimitry Andric       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
844180abc3dSDimitry Andric   }
845180abc3dSDimitry Andric 
846180abc3dSDimitry Andric   // Emit the initializer.
8479f4dbff6SDimitry Andric   llvm::Value *value = nullptr;
848180abc3dSDimitry Andric 
849180abc3dSDimitry Andric   switch (lifetime) {
850180abc3dSDimitry Andric   case Qualifiers::OCL_None:
851180abc3dSDimitry Andric     llvm_unreachable("present but none");
852180abc3dSDimitry Andric 
853180abc3dSDimitry Andric   case Qualifiers::OCL_Strong: {
854676fbe81SDimitry Andric     if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
855180abc3dSDimitry Andric       value = EmitARCRetainScalarExpr(init);
856180abc3dSDimitry Andric       break;
857180abc3dSDimitry Andric     }
858676fbe81SDimitry Andric     // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
859676fbe81SDimitry Andric     // that we omit the retain, and causes non-autoreleased return values to be
860676fbe81SDimitry Andric     // immediately released.
861e3b55780SDimitry Andric     [[fallthrough]];
862676fbe81SDimitry Andric   }
863676fbe81SDimitry Andric 
864676fbe81SDimitry Andric   case Qualifiers::OCL_ExplicitNone:
865676fbe81SDimitry Andric     value = EmitARCUnsafeUnretainedScalarExpr(init);
866676fbe81SDimitry Andric     break;
867180abc3dSDimitry Andric 
868180abc3dSDimitry Andric   case Qualifiers::OCL_Weak: {
86945b53394SDimitry Andric     // If it's not accessed by the initializer, try to emit the
87045b53394SDimitry Andric     // initialization with a copy or move.
87145b53394SDimitry Andric     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
87245b53394SDimitry Andric       return;
87345b53394SDimitry Andric     }
87445b53394SDimitry Andric 
875180abc3dSDimitry Andric     // No way to optimize a producing initializer into this.  It's not
876180abc3dSDimitry Andric     // worth optimizing for, because the value will immediately
877180abc3dSDimitry Andric     // disappear in the common case.
878180abc3dSDimitry Andric     value = EmitScalarExpr(init);
879180abc3dSDimitry Andric 
880180abc3dSDimitry Andric     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
881180abc3dSDimitry Andric     if (accessedByInit)
882ac9a064cSDimitry Andric       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
883180abc3dSDimitry Andric     else
884ac9a064cSDimitry Andric       EmitARCInitWeak(lvalue.getAddress(), value);
885180abc3dSDimitry Andric     return;
886180abc3dSDimitry Andric   }
887180abc3dSDimitry Andric 
888180abc3dSDimitry Andric   case Qualifiers::OCL_Autoreleasing:
889180abc3dSDimitry Andric     value = EmitARCRetainAutoreleaseScalarExpr(init);
890180abc3dSDimitry Andric     break;
891180abc3dSDimitry Andric   }
892180abc3dSDimitry Andric 
893180abc3dSDimitry Andric   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
894180abc3dSDimitry Andric 
8957442d6faSDimitry Andric   EmitNullabilityCheck(lvalue, value, init->getExprLoc());
8967442d6faSDimitry Andric 
897180abc3dSDimitry Andric   // If the variable might have been accessed by its initializer, we
898180abc3dSDimitry Andric   // might have to initialize with a barrier.  We have to do this for
899180abc3dSDimitry Andric   // both __weak and __strong, but __weak got filtered out above.
900180abc3dSDimitry Andric   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
901bfef3995SDimitry Andric     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
902dbe13110SDimitry Andric     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
903809500fcSDimitry Andric     EmitARCRelease(oldValue, ARCImpreciseLifetime);
904180abc3dSDimitry Andric     return;
905180abc3dSDimitry Andric   }
906180abc3dSDimitry Andric 
907dbe13110SDimitry Andric   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
908180abc3dSDimitry Andric }
909180abc3dSDimitry Andric 
91048675466SDimitry Andric /// Decide whether we can emit the non-zero parts of the specified initializer
91148675466SDimitry Andric /// with equal or fewer than NumStores scalar stores.
canEmitInitWithFewStoresAfterBZero(llvm::Constant * Init,unsigned & NumStores)91248675466SDimitry Andric static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
913bca07a45SDimitry Andric                                                unsigned &NumStores) {
914bca07a45SDimitry Andric   // Zero and Undef never requires any extra stores.
915bca07a45SDimitry Andric   if (isa<llvm::ConstantAggregateZero>(Init) ||
916bca07a45SDimitry Andric       isa<llvm::ConstantPointerNull>(Init) ||
917bca07a45SDimitry Andric       isa<llvm::UndefValue>(Init))
918bca07a45SDimitry Andric     return true;
919bca07a45SDimitry Andric   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
920bca07a45SDimitry Andric       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
921bca07a45SDimitry Andric       isa<llvm::ConstantExpr>(Init))
922bca07a45SDimitry Andric     return Init->isNullValue() || NumStores--;
923bca07a45SDimitry Andric 
924bca07a45SDimitry Andric   // See if we can emit each element.
925bca07a45SDimitry Andric   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
926bca07a45SDimitry Andric     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
927bca07a45SDimitry Andric       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
92848675466SDimitry Andric       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
929bca07a45SDimitry Andric         return false;
930bca07a45SDimitry Andric     }
931bca07a45SDimitry Andric     return true;
932bca07a45SDimitry Andric   }
933bca07a45SDimitry Andric 
934dbe13110SDimitry Andric   if (llvm::ConstantDataSequential *CDS =
935dbe13110SDimitry Andric         dyn_cast<llvm::ConstantDataSequential>(Init)) {
936dbe13110SDimitry Andric     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
937dbe13110SDimitry Andric       llvm::Constant *Elt = CDS->getElementAsConstant(i);
93848675466SDimitry Andric       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
939dbe13110SDimitry Andric         return false;
940dbe13110SDimitry Andric     }
941dbe13110SDimitry Andric     return true;
942dbe13110SDimitry Andric   }
943dbe13110SDimitry Andric 
944bca07a45SDimitry Andric   // Anything else is hard and scary.
945bca07a45SDimitry Andric   return false;
946bca07a45SDimitry Andric }
947bca07a45SDimitry Andric 
94848675466SDimitry Andric /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
94948675466SDimitry Andric /// the scalar stores that would be required.
emitStoresForInitAfterBZero(CodeGenModule & CGM,llvm::Constant * Init,Address Loc,bool isVolatile,CGBuilderTy & Builder,bool IsAutoInit)95048675466SDimitry Andric static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
95148675466SDimitry Andric                                         llvm::Constant *Init, Address Loc,
952b60736ecSDimitry Andric                                         bool isVolatile, CGBuilderTy &Builder,
953b60736ecSDimitry Andric                                         bool IsAutoInit) {
95413cc256eSDimitry Andric   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
95548675466SDimitry Andric          "called emitStoresForInitAfterBZero for zero or undef value.");
956bca07a45SDimitry Andric 
957bca07a45SDimitry Andric   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
958bca07a45SDimitry Andric       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
959bca07a45SDimitry Andric       isa<llvm::ConstantExpr>(Init)) {
960b60736ecSDimitry Andric     auto *I = Builder.CreateStore(Init, Loc, isVolatile);
961b60736ecSDimitry Andric     if (IsAutoInit)
962b60736ecSDimitry Andric       I->addAnnotationMetadata("auto-init");
963bca07a45SDimitry Andric     return;
964bca07a45SDimitry Andric   }
965bca07a45SDimitry Andric 
966dbe13110SDimitry Andric   if (llvm::ConstantDataSequential *CDS =
967dbe13110SDimitry Andric           dyn_cast<llvm::ConstantDataSequential>(Init)) {
968dbe13110SDimitry Andric     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
969dbe13110SDimitry Andric       llvm::Constant *Elt = CDS->getElementAsConstant(i);
970dbe13110SDimitry Andric 
97113cc256eSDimitry Andric       // If necessary, get a pointer to the element and emit it.
97213cc256eSDimitry Andric       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
97348675466SDimitry Andric         emitStoresForInitAfterBZero(
97422989816SDimitry Andric             CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
975b60736ecSDimitry Andric             Builder, IsAutoInit);
976dbe13110SDimitry Andric     }
977dbe13110SDimitry Andric     return;
978dbe13110SDimitry Andric   }
979dbe13110SDimitry Andric 
980bca07a45SDimitry Andric   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
981bca07a45SDimitry Andric          "Unknown value type!");
982bca07a45SDimitry Andric 
983bca07a45SDimitry Andric   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
984bca07a45SDimitry Andric     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
98513cc256eSDimitry Andric 
98613cc256eSDimitry Andric     // If necessary, get a pointer to the element and emit it.
98713cc256eSDimitry Andric     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
98822989816SDimitry Andric       emitStoresForInitAfterBZero(CGM, Elt,
98922989816SDimitry Andric                                   Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
990b60736ecSDimitry Andric                                   isVolatile, Builder, IsAutoInit);
991bca07a45SDimitry Andric   }
992bca07a45SDimitry Andric }
993bca07a45SDimitry Andric 
99448675466SDimitry Andric /// Decide whether we should use bzero plus some stores to initialize a local
99548675466SDimitry Andric /// variable instead of using a memcpy from a constant global.  It is beneficial
99648675466SDimitry Andric /// to use bzero if the global is all zeros, or mostly zeros and large.
shouldUseBZeroPlusStoresToInitialize(llvm::Constant * Init,uint64_t GlobalSize)99748675466SDimitry Andric static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
998bca07a45SDimitry Andric                                                  uint64_t GlobalSize) {
99948675466SDimitry Andric   // If a global is all zeros, always use a bzero.
1000bca07a45SDimitry Andric   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
1001bca07a45SDimitry Andric 
1002bca07a45SDimitry Andric   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
1003bca07a45SDimitry Andric   // do it if it will require 6 or fewer scalar stores.
1004bca07a45SDimitry Andric   // TODO: Should budget depends on the size?  Avoiding a large global warrants
1005bca07a45SDimitry Andric   // plopping in more stores.
1006bca07a45SDimitry Andric   unsigned StoreBudget = 6;
1007bca07a45SDimitry Andric   uint64_t SizeLimit = 32;
1008bca07a45SDimitry Andric 
1009bca07a45SDimitry Andric   return GlobalSize > SizeLimit &&
101048675466SDimitry Andric          canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
101148675466SDimitry Andric }
101248675466SDimitry Andric 
101348675466SDimitry Andric /// Decide whether we should use memset to initialize a local variable instead
101448675466SDimitry Andric /// of using a memcpy from a constant global. Assumes we've already decided to
101548675466SDimitry Andric /// not user bzero.
101648675466SDimitry Andric /// FIXME We could be more clever, as we are for bzero above, and generate
101748675466SDimitry Andric ///       memset followed by stores. It's unclear that's worth the effort.
shouldUseMemSetToInitialize(llvm::Constant * Init,uint64_t GlobalSize,const llvm::DataLayout & DL)1018676fbe81SDimitry Andric static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
101922989816SDimitry Andric                                                 uint64_t GlobalSize,
102022989816SDimitry Andric                                                 const llvm::DataLayout &DL) {
102148675466SDimitry Andric   uint64_t SizeLimit = 32;
102248675466SDimitry Andric   if (GlobalSize <= SizeLimit)
1023676fbe81SDimitry Andric     return nullptr;
102422989816SDimitry Andric   return llvm::isBytewiseValue(Init, DL);
1025676fbe81SDimitry Andric }
1026676fbe81SDimitry Andric 
102722989816SDimitry Andric /// Decide whether we want to split a constant structure or array store into a
102822989816SDimitry Andric /// sequence of its fields' stores. This may cost us code size and compilation
102922989816SDimitry Andric /// speed, but plays better with store optimizations.
shouldSplitConstantStore(CodeGenModule & CGM,uint64_t GlobalByteSize)103022989816SDimitry Andric static bool shouldSplitConstantStore(CodeGenModule &CGM,
103122989816SDimitry Andric                                      uint64_t GlobalByteSize) {
103222989816SDimitry Andric   // Don't break things that occupy more than one cacheline.
103322989816SDimitry Andric   uint64_t ByteSizeLimit = 64;
103422989816SDimitry Andric   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
103522989816SDimitry Andric     return false;
103622989816SDimitry Andric   if (GlobalByteSize <= ByteSizeLimit)
103722989816SDimitry Andric     return true;
103822989816SDimitry Andric   return false;
1039676fbe81SDimitry Andric }
1040676fbe81SDimitry Andric 
104122989816SDimitry Andric enum class IsPattern { No, Yes };
104222989816SDimitry Andric 
104322989816SDimitry Andric /// Generate a constant filled with either a pattern or zeroes.
patternOrZeroFor(CodeGenModule & CGM,IsPattern isPattern,llvm::Type * Ty)104422989816SDimitry Andric static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
104522989816SDimitry Andric                                         llvm::Type *Ty) {
104622989816SDimitry Andric   if (isPattern == IsPattern::Yes)
104722989816SDimitry Andric     return initializationPatternFor(CGM, Ty);
104822989816SDimitry Andric   else
104922989816SDimitry Andric     return llvm::Constant::getNullValue(Ty);
1050676fbe81SDimitry Andric }
1051676fbe81SDimitry Andric 
105222989816SDimitry Andric static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
105322989816SDimitry Andric                                         llvm::Constant *constant);
105422989816SDimitry Andric 
105522989816SDimitry Andric /// Helper function for constWithPadding() to deal with padding in structures.
constStructWithPadding(CodeGenModule & CGM,IsPattern isPattern,llvm::StructType * STy,llvm::Constant * constant)105622989816SDimitry Andric static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
105722989816SDimitry Andric                                               IsPattern isPattern,
105822989816SDimitry Andric                                               llvm::StructType *STy,
105922989816SDimitry Andric                                               llvm::Constant *constant) {
106022989816SDimitry Andric   const llvm::DataLayout &DL = CGM.getDataLayout();
106122989816SDimitry Andric   const llvm::StructLayout *Layout = DL.getStructLayout(STy);
106222989816SDimitry Andric   llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
106322989816SDimitry Andric   unsigned SizeSoFar = 0;
106422989816SDimitry Andric   SmallVector<llvm::Constant *, 8> Values;
106522989816SDimitry Andric   bool NestedIntact = true;
106622989816SDimitry Andric   for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
106722989816SDimitry Andric     unsigned CurOff = Layout->getElementOffset(i);
106822989816SDimitry Andric     if (SizeSoFar < CurOff) {
106922989816SDimitry Andric       assert(!STy->isPacked());
107022989816SDimitry Andric       auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
107122989816SDimitry Andric       Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
107222989816SDimitry Andric     }
107322989816SDimitry Andric     llvm::Constant *CurOp;
107422989816SDimitry Andric     if (constant->isZeroValue())
107522989816SDimitry Andric       CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
107622989816SDimitry Andric     else
107722989816SDimitry Andric       CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
107822989816SDimitry Andric     auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
107922989816SDimitry Andric     if (CurOp != NewOp)
108022989816SDimitry Andric       NestedIntact = false;
108122989816SDimitry Andric     Values.push_back(NewOp);
108222989816SDimitry Andric     SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
108322989816SDimitry Andric   }
108422989816SDimitry Andric   unsigned TotalSize = Layout->getSizeInBytes();
108522989816SDimitry Andric   if (SizeSoFar < TotalSize) {
108622989816SDimitry Andric     auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
108722989816SDimitry Andric     Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
108822989816SDimitry Andric   }
108922989816SDimitry Andric   if (NestedIntact && Values.size() == STy->getNumElements())
109022989816SDimitry Andric     return constant;
109122989816SDimitry Andric   return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
109222989816SDimitry Andric }
109322989816SDimitry Andric 
109422989816SDimitry Andric /// Replace all padding bytes in a given constant with either a pattern byte or
109522989816SDimitry Andric /// 0x00.
constWithPadding(CodeGenModule & CGM,IsPattern isPattern,llvm::Constant * constant)109622989816SDimitry Andric static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
109722989816SDimitry Andric                                         llvm::Constant *constant) {
109822989816SDimitry Andric   llvm::Type *OrigTy = constant->getType();
109922989816SDimitry Andric   if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
110022989816SDimitry Andric     return constStructWithPadding(CGM, isPattern, STy, constant);
1101cfca06d7SDimitry Andric   if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
110222989816SDimitry Andric     llvm::SmallVector<llvm::Constant *, 8> Values;
1103cfca06d7SDimitry Andric     uint64_t Size = ArrayTy->getNumElements();
110422989816SDimitry Andric     if (!Size)
110522989816SDimitry Andric       return constant;
1106cfca06d7SDimitry Andric     llvm::Type *ElemTy = ArrayTy->getElementType();
1107cfca06d7SDimitry Andric     bool ZeroInitializer = constant->isNullValue();
110822989816SDimitry Andric     llvm::Constant *OpValue, *PaddedOp;
110922989816SDimitry Andric     if (ZeroInitializer) {
111022989816SDimitry Andric       OpValue = llvm::Constant::getNullValue(ElemTy);
111122989816SDimitry Andric       PaddedOp = constWithPadding(CGM, isPattern, OpValue);
111222989816SDimitry Andric     }
111322989816SDimitry Andric     for (unsigned Op = 0; Op != Size; ++Op) {
111422989816SDimitry Andric       if (!ZeroInitializer) {
111522989816SDimitry Andric         OpValue = constant->getAggregateElement(Op);
111622989816SDimitry Andric         PaddedOp = constWithPadding(CGM, isPattern, OpValue);
111722989816SDimitry Andric       }
111822989816SDimitry Andric       Values.push_back(PaddedOp);
111922989816SDimitry Andric     }
112022989816SDimitry Andric     auto *NewElemTy = Values[0]->getType();
112122989816SDimitry Andric     if (NewElemTy == ElemTy)
112222989816SDimitry Andric       return constant;
1123cfca06d7SDimitry Andric     auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1124cfca06d7SDimitry Andric     return llvm::ConstantArray::get(NewArrayTy, Values);
112522989816SDimitry Andric   }
1126cfca06d7SDimitry Andric   // FIXME: Add handling for tail padding in vectors. Vectors don't
1127cfca06d7SDimitry Andric   // have padding between or inside elements, but the total amount of
1128cfca06d7SDimitry Andric   // data can be less than the allocated size.
112922989816SDimitry Andric   return constant;
113022989816SDimitry Andric }
113122989816SDimitry Andric 
createUnnamedGlobalFrom(const VarDecl & D,llvm::Constant * Constant,CharUnits Align)113222989816SDimitry Andric Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1133676fbe81SDimitry Andric                                                llvm::Constant *Constant,
1134676fbe81SDimitry Andric                                                CharUnits Align) {
1135676fbe81SDimitry Andric   auto FunctionName = [&](const DeclContext *DC) -> std::string {
1136676fbe81SDimitry Andric     if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1137676fbe81SDimitry Andric       if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1138676fbe81SDimitry Andric         return CC->getNameAsString();
1139676fbe81SDimitry Andric       if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1140676fbe81SDimitry Andric         return CD->getNameAsString();
1141cfca06d7SDimitry Andric       return std::string(getMangledName(FD));
1142676fbe81SDimitry Andric     } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1143676fbe81SDimitry Andric       return OM->getNameAsString();
1144676fbe81SDimitry Andric     } else if (isa<BlockDecl>(DC)) {
1145676fbe81SDimitry Andric       return "<block>";
1146676fbe81SDimitry Andric     } else if (isa<CapturedDecl>(DC)) {
1147676fbe81SDimitry Andric       return "<captured>";
1148676fbe81SDimitry Andric     } else {
114922989816SDimitry Andric       llvm_unreachable("expected a function or method");
1150676fbe81SDimitry Andric     }
1151676fbe81SDimitry Andric   };
1152676fbe81SDimitry Andric 
115322989816SDimitry Andric   // Form a simple per-variable cache of these values in case we find we
115422989816SDimitry Andric   // want to reuse them.
115522989816SDimitry Andric   llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
115622989816SDimitry Andric   if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1157676fbe81SDimitry Andric     auto *Ty = Constant->getType();
1158676fbe81SDimitry Andric     bool isConstant = true;
1159676fbe81SDimitry Andric     llvm::GlobalVariable *InsertBefore = nullptr;
116022989816SDimitry Andric     unsigned AS =
1161344a3780SDimitry Andric         getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
116222989816SDimitry Andric     std::string Name;
116322989816SDimitry Andric     if (D.hasGlobalStorage())
116422989816SDimitry Andric       Name = getMangledName(&D).str() + ".const";
116522989816SDimitry Andric     else if (const DeclContext *DC = D.getParentFunctionOrMethod())
116622989816SDimitry Andric       Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
116722989816SDimitry Andric     else
116822989816SDimitry Andric       llvm_unreachable("local variable has no parent function or method");
1169676fbe81SDimitry Andric     llvm::GlobalVariable *GV = new llvm::GlobalVariable(
117022989816SDimitry Andric         getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
117122989816SDimitry Andric         Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1172519fc96cSDimitry Andric     GV->setAlignment(Align.getAsAlign());
1173676fbe81SDimitry Andric     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
117422989816SDimitry Andric     CacheEntry = GV;
1175c0981da4SDimitry Andric   } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1176519fc96cSDimitry Andric     CacheEntry->setAlignment(Align.getAsAlign());
117722989816SDimitry Andric   }
1178676fbe81SDimitry Andric 
117977fc4c14SDimitry Andric   return Address(CacheEntry, CacheEntry->getValueType(), Align);
118022989816SDimitry Andric }
118122989816SDimitry Andric 
createUnnamedGlobalForMemcpyFrom(CodeGenModule & CGM,const VarDecl & D,CGBuilderTy & Builder,llvm::Constant * Constant,CharUnits Align)118222989816SDimitry Andric static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
118322989816SDimitry Andric                                                 const VarDecl &D,
118422989816SDimitry Andric                                                 CGBuilderTy &Builder,
118522989816SDimitry Andric                                                 llvm::Constant *Constant,
118622989816SDimitry Andric                                                 CharUnits Align) {
118722989816SDimitry Andric   Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
11887fa27ce4SDimitry Andric   return SrcPtr.withElementType(CGM.Int8Ty);
1189676fbe81SDimitry Andric }
1190676fbe81SDimitry Andric 
emitStoresForConstant(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder,llvm::Constant * constant,bool IsAutoInit)1191676fbe81SDimitry Andric static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1192676fbe81SDimitry Andric                                   Address Loc, bool isVolatile,
1193676fbe81SDimitry Andric                                   CGBuilderTy &Builder,
1194b60736ecSDimitry Andric                                   llvm::Constant *constant, bool IsAutoInit) {
1195676fbe81SDimitry Andric   auto *Ty = constant->getType();
119622989816SDimitry Andric   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
119722989816SDimitry Andric   if (!ConstantSize)
119822989816SDimitry Andric     return;
119922989816SDimitry Andric 
120022989816SDimitry Andric   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
120122989816SDimitry Andric                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
120222989816SDimitry Andric   if (canDoSingleStore) {
1203b60736ecSDimitry Andric     auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1204b60736ecSDimitry Andric     if (IsAutoInit)
1205b60736ecSDimitry Andric       I->addAnnotationMetadata("auto-init");
1206676fbe81SDimitry Andric     return;
1207676fbe81SDimitry Andric   }
1208676fbe81SDimitry Andric 
120922989816SDimitry Andric   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1210676fbe81SDimitry Andric 
1211676fbe81SDimitry Andric   // If the initializer is all or mostly the same, codegen with bzero / memset
1212676fbe81SDimitry Andric   // then do a few stores afterward.
1213676fbe81SDimitry Andric   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1214b60736ecSDimitry Andric     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1215b60736ecSDimitry Andric                                    SizeVal, isVolatile);
1216b60736ecSDimitry Andric     if (IsAutoInit)
1217b60736ecSDimitry Andric       I->addAnnotationMetadata("auto-init");
1218676fbe81SDimitry Andric 
1219676fbe81SDimitry Andric     bool valueAlreadyCorrect =
1220676fbe81SDimitry Andric         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1221676fbe81SDimitry Andric     if (!valueAlreadyCorrect) {
12227fa27ce4SDimitry Andric       Loc = Loc.withElementType(Ty);
1223b60736ecSDimitry Andric       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1224b60736ecSDimitry Andric                                   IsAutoInit);
1225676fbe81SDimitry Andric     }
1226676fbe81SDimitry Andric     return;
1227676fbe81SDimitry Andric   }
1228676fbe81SDimitry Andric 
122922989816SDimitry Andric   // If the initializer is a repeated byte pattern, use memset.
123022989816SDimitry Andric   llvm::Value *Pattern =
123122989816SDimitry Andric       shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1232676fbe81SDimitry Andric   if (Pattern) {
1233676fbe81SDimitry Andric     uint64_t Value = 0x00;
1234676fbe81SDimitry Andric     if (!isa<llvm::UndefValue>(Pattern)) {
1235676fbe81SDimitry Andric       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1236676fbe81SDimitry Andric       assert(AP.getBitWidth() <= 8);
1237676fbe81SDimitry Andric       Value = AP.getLimitedValue();
1238676fbe81SDimitry Andric     }
1239b60736ecSDimitry Andric     auto *I = Builder.CreateMemSet(
1240b60736ecSDimitry Andric         Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1241b60736ecSDimitry Andric     if (IsAutoInit)
1242b60736ecSDimitry Andric       I->addAnnotationMetadata("auto-init");
1243676fbe81SDimitry Andric     return;
1244676fbe81SDimitry Andric   }
1245676fbe81SDimitry Andric 
1246ac9a064cSDimitry Andric   // If the initializer is small or trivialAutoVarInit is set, use a handful of
1247ac9a064cSDimitry Andric   // stores.
1248ac9a064cSDimitry Andric   bool IsTrivialAutoVarInitPattern =
1249ac9a064cSDimitry Andric       CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
1250ac9a064cSDimitry Andric       LangOptions::TrivialAutoVarInitKind::Pattern;
125122989816SDimitry Andric   if (shouldSplitConstantStore(CGM, ConstantSize)) {
125222989816SDimitry Andric     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1253ac9a064cSDimitry Andric       if (STy == Loc.getElementType() ||
1254ac9a064cSDimitry Andric           (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
1255b1c73532SDimitry Andric         const llvm::StructLayout *Layout =
1256b1c73532SDimitry Andric             CGM.getDataLayout().getStructLayout(STy);
125722989816SDimitry Andric         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1258ac9a064cSDimitry Andric           CharUnits CurOff =
1259ac9a064cSDimitry Andric               CharUnits::fromQuantity(Layout->getElementOffset(i));
1260b1c73532SDimitry Andric           Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1261b1c73532SDimitry Andric               Loc.withElementType(CGM.Int8Ty), CurOff);
1262b1c73532SDimitry Andric           emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1263b1c73532SDimitry Andric                                 constant->getAggregateElement(i), IsAutoInit);
126422989816SDimitry Andric         }
126522989816SDimitry Andric         return;
1266ac9a064cSDimitry Andric       }
126722989816SDimitry Andric     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1268ac9a064cSDimitry Andric       if (ATy == Loc.getElementType() ||
1269ac9a064cSDimitry Andric           (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
127022989816SDimitry Andric         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1271b1c73532SDimitry Andric           Address EltPtr = Builder.CreateConstGEP(
1272b1c73532SDimitry Andric               Loc.withElementType(ATy->getElementType()), i);
1273b1c73532SDimitry Andric           emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1274b1c73532SDimitry Andric                                 constant->getAggregateElement(i), IsAutoInit);
127522989816SDimitry Andric         }
127622989816SDimitry Andric         return;
127722989816SDimitry Andric       }
127822989816SDimitry Andric     }
1279ac9a064cSDimitry Andric   }
128022989816SDimitry Andric 
128122989816SDimitry Andric   // Copy from a global.
1282b60736ecSDimitry Andric   auto *I =
128322989816SDimitry Andric       Builder.CreateMemCpy(Loc,
128422989816SDimitry Andric                            createUnnamedGlobalForMemcpyFrom(
128522989816SDimitry Andric                                CGM, D, Builder, constant, Loc.getAlignment()),
1286676fbe81SDimitry Andric                            SizeVal, isVolatile);
1287b60736ecSDimitry Andric   if (IsAutoInit)
1288b60736ecSDimitry Andric     I->addAnnotationMetadata("auto-init");
1289676fbe81SDimitry Andric }
1290676fbe81SDimitry Andric 
emitStoresForZeroInit(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder)1291676fbe81SDimitry Andric static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1292676fbe81SDimitry Andric                                   Address Loc, bool isVolatile,
1293676fbe81SDimitry Andric                                   CGBuilderTy &Builder) {
1294676fbe81SDimitry Andric   llvm::Type *ElTy = Loc.getElementType();
129522989816SDimitry Andric   llvm::Constant *constant =
129622989816SDimitry Andric       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1297b60736ecSDimitry Andric   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1298b60736ecSDimitry Andric                         /*IsAutoInit=*/true);
1299676fbe81SDimitry Andric }
1300676fbe81SDimitry Andric 
emitStoresForPatternInit(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder)1301676fbe81SDimitry Andric static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1302676fbe81SDimitry Andric                                      Address Loc, bool isVolatile,
1303676fbe81SDimitry Andric                                      CGBuilderTy &Builder) {
1304676fbe81SDimitry Andric   llvm::Type *ElTy = Loc.getElementType();
130522989816SDimitry Andric   llvm::Constant *constant = constWithPadding(
130622989816SDimitry Andric       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1307676fbe81SDimitry Andric   assert(!isa<llvm::UndefValue>(constant));
1308b60736ecSDimitry Andric   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1309b60736ecSDimitry Andric                         /*IsAutoInit=*/true);
1310676fbe81SDimitry Andric }
1311676fbe81SDimitry Andric 
containsUndef(llvm::Constant * constant)1312676fbe81SDimitry Andric static bool containsUndef(llvm::Constant *constant) {
1313676fbe81SDimitry Andric   auto *Ty = constant->getType();
1314676fbe81SDimitry Andric   if (isa<llvm::UndefValue>(constant))
1315676fbe81SDimitry Andric     return true;
1316676fbe81SDimitry Andric   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1317676fbe81SDimitry Andric     for (llvm::Use &Op : constant->operands())
1318676fbe81SDimitry Andric       if (containsUndef(cast<llvm::Constant>(Op)))
1319676fbe81SDimitry Andric         return true;
1320676fbe81SDimitry Andric   return false;
1321676fbe81SDimitry Andric }
1322676fbe81SDimitry Andric 
replaceUndef(CodeGenModule & CGM,IsPattern isPattern,llvm::Constant * constant)132322989816SDimitry Andric static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
132422989816SDimitry Andric                                     llvm::Constant *constant) {
1325676fbe81SDimitry Andric   auto *Ty = constant->getType();
1326676fbe81SDimitry Andric   if (isa<llvm::UndefValue>(constant))
132722989816SDimitry Andric     return patternOrZeroFor(CGM, isPattern, Ty);
1328676fbe81SDimitry Andric   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1329676fbe81SDimitry Andric     return constant;
1330676fbe81SDimitry Andric   if (!containsUndef(constant))
1331676fbe81SDimitry Andric     return constant;
1332676fbe81SDimitry Andric   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1333676fbe81SDimitry Andric   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1334676fbe81SDimitry Andric     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
133522989816SDimitry Andric     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1336676fbe81SDimitry Andric   }
1337676fbe81SDimitry Andric   if (Ty->isStructTy())
1338676fbe81SDimitry Andric     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1339676fbe81SDimitry Andric   if (Ty->isArrayTy())
1340676fbe81SDimitry Andric     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1341676fbe81SDimitry Andric   assert(Ty->isVectorTy());
1342676fbe81SDimitry Andric   return llvm::ConstantVector::get(Values);
1343bca07a45SDimitry Andric }
1344bca07a45SDimitry Andric 
1345bca07a45SDimitry Andric /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1346ec2b103cSEd Schouten /// variable declaration with auto, register, or no storage class specifier.
1347ec2b103cSEd Schouten /// These turn into simple stack objects, or GlobalValues depending on target.
EmitAutoVarDecl(const VarDecl & D)1348c3b054d2SDimitry Andric void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1349c3b054d2SDimitry Andric   AutoVarEmission emission = EmitAutoVarAlloca(D);
1350c3b054d2SDimitry Andric   EmitAutoVarInit(emission);
1351c3b054d2SDimitry Andric   EmitAutoVarCleanups(emission);
1352c3b054d2SDimitry Andric }
1353ec2b103cSEd Schouten 
13545e20cdd8SDimitry Andric /// Emit a lifetime.begin marker if some criteria are satisfied.
13555e20cdd8SDimitry Andric /// \return a pointer to the temporary size Value if a marker was emitted, null
13565e20cdd8SDimitry Andric /// otherwise
EmitLifetimeStart(llvm::TypeSize Size,llvm::Value * Addr)1357344a3780SDimitry Andric llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
13585e20cdd8SDimitry Andric                                                 llvm::Value *Addr) {
1359bab175ecSDimitry Andric   if (!ShouldEmitLifetimeMarkers)
13605e20cdd8SDimitry Andric     return nullptr;
13615e20cdd8SDimitry Andric 
136248675466SDimitry Andric   assert(Addr->getType()->getPointerAddressSpace() ==
136348675466SDimitry Andric              CGM.getDataLayout().getAllocaAddrSpace() &&
136448675466SDimitry Andric          "Pointer should be in alloca address space");
1365344a3780SDimitry Andric   llvm::Value *SizeV = llvm::ConstantInt::get(
1366344a3780SDimitry Andric       Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
13672e645aa5SDimitry Andric   llvm::CallInst *C =
13682e645aa5SDimitry Andric       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
13695e20cdd8SDimitry Andric   C->setDoesNotThrow();
13705e20cdd8SDimitry Andric   return SizeV;
13715e20cdd8SDimitry Andric }
13725e20cdd8SDimitry Andric 
EmitLifetimeEnd(llvm::Value * Size,llvm::Value * Addr)13735e20cdd8SDimitry Andric void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
137448675466SDimitry Andric   assert(Addr->getType()->getPointerAddressSpace() ==
137548675466SDimitry Andric              CGM.getDataLayout().getAllocaAddrSpace() &&
137648675466SDimitry Andric          "Pointer should be in alloca address space");
13772e645aa5SDimitry Andric   llvm::CallInst *C =
13782e645aa5SDimitry Andric       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
13795e20cdd8SDimitry Andric   C->setDoesNotThrow();
13805e20cdd8SDimitry Andric }
13815e20cdd8SDimitry Andric 
EmitAndRegisterVariableArrayDimensions(CGDebugInfo * DI,const VarDecl & D,bool EmitDebugInfo)138248675466SDimitry Andric void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
138348675466SDimitry Andric     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
138448675466SDimitry Andric   // For each dimension stores its QualType and corresponding
138548675466SDimitry Andric   // size-expression Value.
138648675466SDimitry Andric   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1387ac9a064cSDimitry Andric   SmallVector<const IdentifierInfo *, 4> VLAExprNames;
138848675466SDimitry Andric 
138948675466SDimitry Andric   // Break down the array into individual dimensions.
139048675466SDimitry Andric   QualType Type1D = D.getType();
139148675466SDimitry Andric   while (getContext().getAsVariableArrayType(Type1D)) {
139248675466SDimitry Andric     auto VlaSize = getVLAElements1D(Type1D);
139348675466SDimitry Andric     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
139448675466SDimitry Andric       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
139548675466SDimitry Andric     else {
1396676fbe81SDimitry Andric       // Generate a locally unique name for the size expression.
1397676fbe81SDimitry Andric       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1398676fbe81SDimitry Andric       SmallString<12> Buffer;
1399676fbe81SDimitry Andric       StringRef NameRef = Name.toStringRef(Buffer);
1400676fbe81SDimitry Andric       auto &Ident = getContext().Idents.getOwn(NameRef);
1401676fbe81SDimitry Andric       VLAExprNames.push_back(&Ident);
1402676fbe81SDimitry Andric       auto SizeExprAddr =
1403676fbe81SDimitry Andric           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
140448675466SDimitry Andric       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
140548675466SDimitry Andric       Dimensions.emplace_back(SizeExprAddr.getPointer(),
140648675466SDimitry Andric                               Type1D.getUnqualifiedType());
140748675466SDimitry Andric     }
140848675466SDimitry Andric     Type1D = VlaSize.Type;
140948675466SDimitry Andric   }
141048675466SDimitry Andric 
141148675466SDimitry Andric   if (!EmitDebugInfo)
141248675466SDimitry Andric     return;
141348675466SDimitry Andric 
141448675466SDimitry Andric   // Register each dimension's size-expression with a DILocalVariable,
141548675466SDimitry Andric   // so that it can be used by CGDebugInfo when instantiating a DISubrange
141648675466SDimitry Andric   // to describe this array.
1417676fbe81SDimitry Andric   unsigned NameIdx = 0;
141848675466SDimitry Andric   for (auto &VlaSize : Dimensions) {
141948675466SDimitry Andric     llvm::Metadata *MD;
142048675466SDimitry Andric     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
142148675466SDimitry Andric       MD = llvm::ConstantAsMetadata::get(C);
142248675466SDimitry Andric     else {
142348675466SDimitry Andric       // Create an artificial VarDecl to generate debug info for.
1424ac9a064cSDimitry Andric       const IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
142548675466SDimitry Andric       auto QT = getContext().getIntTypeForBitwidth(
14266f8fc217SDimitry Andric           SizeTy->getScalarSizeInBits(), false);
142748675466SDimitry Andric       auto *ArtificialDecl = VarDecl::Create(
142848675466SDimitry Andric           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1429676fbe81SDimitry Andric           D.getLocation(), D.getLocation(), NameIdent, QT,
143048675466SDimitry Andric           getContext().CreateTypeSourceInfo(QT), SC_Auto);
143148675466SDimitry Andric       ArtificialDecl->setImplicit();
143248675466SDimitry Andric 
143348675466SDimitry Andric       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
143448675466SDimitry Andric                                          Builder);
143548675466SDimitry Andric     }
143648675466SDimitry Andric     assert(MD && "No Size expression debug node created");
143748675466SDimitry Andric     DI->registerVLASizeExpression(VlaSize.Type, MD);
143848675466SDimitry Andric   }
143948675466SDimitry Andric }
144048675466SDimitry Andric 
1441c3b054d2SDimitry Andric /// EmitAutoVarAlloca - Emit the alloca and debug information for a
14429f4dbff6SDimitry Andric /// local variable.  Does not emit initialization or destruction.
1443c3b054d2SDimitry Andric CodeGenFunction::AutoVarEmission
EmitAutoVarAlloca(const VarDecl & D)1444c3b054d2SDimitry Andric CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1445c3b054d2SDimitry Andric   QualType Ty = D.getType();
1446461a67faSDimitry Andric   assert(
1447461a67faSDimitry Andric       Ty.getAddressSpace() == LangAS::Default ||
1448461a67faSDimitry Andric       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1449c3b054d2SDimitry Andric 
1450c3b054d2SDimitry Andric   AutoVarEmission emission(D);
1451c3b054d2SDimitry Andric 
1452676fbe81SDimitry Andric   bool isEscapingByRef = D.isEscapingByref();
1453676fbe81SDimitry Andric   emission.IsEscapingByRef = isEscapingByRef;
1454c3b054d2SDimitry Andric 
1455c3b054d2SDimitry Andric   CharUnits alignment = getContext().getDeclAlign(&D);
1456c3b054d2SDimitry Andric 
1457180abc3dSDimitry Andric   // If the type is variably-modified, emit all the VLA sizes for it.
1458180abc3dSDimitry Andric   if (Ty->isVariablyModifiedType())
1459180abc3dSDimitry Andric     EmitVariablyModifiedType(Ty);
1460180abc3dSDimitry Andric 
146148675466SDimitry Andric   auto *DI = getDebugInfo();
1462706b4fc4SDimitry Andric   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
146348675466SDimitry Andric 
146445b53394SDimitry Andric   Address address = Address::invalid();
1465ac9a064cSDimitry Andric   RawAddress AllocaAddr = RawAddress::invalid();
1466cfca06d7SDimitry Andric   Address OpenMPLocalAddr = Address::invalid();
1467cfca06d7SDimitry Andric   if (CGM.getLangOpts().OpenMPIRBuilder)
1468cfca06d7SDimitry Andric     OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1469cfca06d7SDimitry Andric   else
1470cfca06d7SDimitry Andric     OpenMPLocalAddr =
147122989816SDimitry Andric         getLangOpts().OpenMP
147222989816SDimitry Andric             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
147322989816SDimitry Andric             : Address::invalid();
1474cfca06d7SDimitry Andric 
147522989816SDimitry Andric   bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1476c3b054d2SDimitry Andric 
147722989816SDimitry Andric   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
147822989816SDimitry Andric     address = OpenMPLocalAddr;
1479c0981da4SDimitry Andric     AllocaAddr = OpenMPLocalAddr;
148022989816SDimitry Andric   } else if (Ty->isConstantSizeType()) {
1481bfef3995SDimitry Andric     // If this value is an array or struct with a statically determinable
1482bfef3995SDimitry Andric     // constant initializer, there are optimizations we can do.
1483dbe13110SDimitry Andric     //
1484dbe13110SDimitry Andric     // TODO: We should constant-evaluate the initializer of any variable,
1485dbe13110SDimitry Andric     // as long as it is initialized by a constant expression. Currently,
1486dbe13110SDimitry Andric     // isConstantInitializer produces wrong answers for structs with
1487dbe13110SDimitry Andric     // reference or bitfield members, and a few other cases, and checking
1488dbe13110SDimitry Andric     // for POD-ness protects us from some of these.
1489bfef3995SDimitry Andric     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1490bfef3995SDimitry Andric         (D.isConstexpr() ||
1491bfef3995SDimitry Andric          ((Ty.isPODType(getContext()) ||
1492180abc3dSDimitry Andric            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1493bfef3995SDimitry Andric           D.getInit()->isConstantInitializer(getContext(), false)))) {
1494c3b054d2SDimitry Andric 
1495c3b054d2SDimitry Andric       // If the variable's a const type, and it's neither an NRVO
1496dbe13110SDimitry Andric       // candidate nor a __block variable and has no mutable members,
1497dbe13110SDimitry Andric       // emit it as a global instead.
1498bab175ecSDimitry Andric       // Exception is if a variable is located in non-constant address space
1499bab175ecSDimitry Andric       // in OpenCL.
15007fa27ce4SDimitry Andric       bool NeedsDtor =
15017fa27ce4SDimitry Andric           D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
1502bab175ecSDimitry Andric       if ((!getLangOpts().OpenCL ||
1503bab175ecSDimitry Andric            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1504676fbe81SDimitry Andric           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1505b1c73532SDimitry Andric            !isEscapingByRef &&
1506b1c73532SDimitry Andric            Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {
150701af97d3SDimitry Andric         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1508c3b054d2SDimitry Andric 
150945b53394SDimitry Andric         // Signal this condition to later callbacks.
151045b53394SDimitry Andric         emission.Addr = Address::invalid();
1511c3b054d2SDimitry Andric         assert(emission.wasEmittedAsGlobal());
1512c3b054d2SDimitry Andric         return emission;
151351fb8b01SRoman Divacky       }
151434d02d0bSRoman Divacky 
1515c3b054d2SDimitry Andric       // Otherwise, tell the initialization code that we're in this case.
1516c3b054d2SDimitry Andric       emission.IsConstantAggregate = true;
151751fb8b01SRoman Divacky     }
151851fb8b01SRoman Divacky 
1519d7279c4cSRoman Divacky     // A normal fixed sized variable becomes an alloca in the entry block,
152048675466SDimitry Andric     // unless:
152148675466SDimitry Andric     // - it's an NRVO variable.
152248675466SDimitry Andric     // - we are compiling OpenMP and it's an OpenMP local variable.
152322989816SDimitry Andric     if (NRVO) {
1524d7279c4cSRoman Divacky       // The named return value optimization: allocate this variable in the
1525d7279c4cSRoman Divacky       // return slot, so that we can elide the copy when returning this
1526d7279c4cSRoman Divacky       // variable (C++0x [class.copy]p34).
152745b53394SDimitry Andric       address = ReturnValue;
1528ac9a064cSDimitry Andric       AllocaAddr =
1529ac9a064cSDimitry Andric           RawAddress(ReturnValue.emitRawPointer(*this),
1530ac9a064cSDimitry Andric                      ReturnValue.getElementType(), ReturnValue.getAlignment());
1531ac9a064cSDimitry Andric       ;
1532d7279c4cSRoman Divacky 
1533d7279c4cSRoman Divacky       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
153448675466SDimitry Andric         const auto *RD = RecordTy->getDecl();
153548675466SDimitry Andric         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
153648675466SDimitry Andric         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
153748675466SDimitry Andric             RD->isNonTrivialToPrimitiveDestroy()) {
1538d7279c4cSRoman Divacky           // Create a flag that is used to indicate when the NRVO was applied
1539d7279c4cSRoman Divacky           // to this variable. Set it to zero to indicate that NRVO was not
1540d7279c4cSRoman Divacky           // applied.
1541bca07a45SDimitry Andric           llvm::Value *Zero = Builder.getFalse();
1542ac9a064cSDimitry Andric           RawAddress NRVOFlag =
1543b1c73532SDimitry Andric               CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1544bca07a45SDimitry Andric           EnsureInsertPoint();
1545d7279c4cSRoman Divacky           Builder.CreateStore(Zero, NRVOFlag);
1546d7279c4cSRoman Divacky 
1547d7279c4cSRoman Divacky           // Record the NRVO flag for this variable.
154845b53394SDimitry Andric           NRVOFlags[&D] = NRVOFlag.getPointer();
154945b53394SDimitry Andric           emission.NRVOFlag = NRVOFlag.getPointer();
1550d7279c4cSRoman Divacky         }
1551d7279c4cSRoman Divacky       }
1552d7279c4cSRoman Divacky     } else {
155345b53394SDimitry Andric       CharUnits allocaAlignment;
155445b53394SDimitry Andric       llvm::Type *allocaTy;
1555676fbe81SDimitry Andric       if (isEscapingByRef) {
155645b53394SDimitry Andric         auto &byrefInfo = getBlockByrefInfo(&D);
155745b53394SDimitry Andric         allocaTy = byrefInfo.Type;
155845b53394SDimitry Andric         allocaAlignment = byrefInfo.ByrefAlignment;
155945b53394SDimitry Andric       } else {
156045b53394SDimitry Andric         allocaTy = ConvertTypeForMem(Ty);
156145b53394SDimitry Andric         allocaAlignment = alignment;
156245b53394SDimitry Andric       }
1563d7279c4cSRoman Divacky 
156445b53394SDimitry Andric       // Create the alloca.  Note that we set the name separately from
156545b53394SDimitry Andric       // building the instruction so that it's there even in no-asserts
156645b53394SDimitry Andric       // builds.
156748675466SDimitry Andric       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
156848675466SDimitry Andric                                  /*ArraySize=*/nullptr, &AllocaAddr);
1569ec2b103cSEd Schouten 
157045b53394SDimitry Andric       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
157145b53394SDimitry Andric       // the catch parameter starts in the catchpad instruction, and we can't
157245b53394SDimitry Andric       // insert code in those basic blocks.
157345b53394SDimitry Andric       bool IsMSCatchParam =
157445b53394SDimitry Andric           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1575809500fcSDimitry Andric 
1576bab175ecSDimitry Andric       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1577bab175ecSDimitry Andric       // if we don't have a valid insertion point (?).
157845b53394SDimitry Andric       if (HaveInsertPoint() && !IsMSCatchParam) {
15797442d6faSDimitry Andric         // If there's a jump into the lifetime of this variable, its lifetime
15807442d6faSDimitry Andric         // gets broken up into several regions in IR, which requires more work
15817442d6faSDimitry Andric         // to handle correctly. For now, just omit the intrinsics; this is a
15827442d6faSDimitry Andric         // rare case, and it's better to just be conservatively correct.
15837442d6faSDimitry Andric         // PR28267.
15847442d6faSDimitry Andric         //
15857442d6faSDimitry Andric         // We have to do this in all language modes if there's a jump past the
15867442d6faSDimitry Andric         // declaration. We also have to do it in C if there's a jump to an
15877442d6faSDimitry Andric         // earlier point in the current block because non-VLA lifetimes begin as
15887442d6faSDimitry Andric         // soon as the containing block is entered, not when its variables
15897442d6faSDimitry Andric         // actually come into scope; suppressing the lifetime annotations
15907442d6faSDimitry Andric         // completely in this case is unnecessarily pessimistic, but again, this
15917442d6faSDimitry Andric         // is rare.
15927442d6faSDimitry Andric         if (!Bypasses.IsBypassed(&D) &&
15937442d6faSDimitry Andric             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1594344a3780SDimitry Andric           llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
159545b53394SDimitry Andric           emission.SizeForLifetimeMarkers =
1596344a3780SDimitry Andric               EmitLifetimeStart(Size, AllocaAddr.getPointer());
1597bab175ecSDimitry Andric         }
1598ec2b103cSEd Schouten       } else {
1599809500fcSDimitry Andric         assert(!emission.useLifetimeMarkers());
1600809500fcSDimitry Andric       }
1601ec2b103cSEd Schouten     }
1602ec2b103cSEd Schouten   } else {
16034c8b2481SRoman Divacky     EnsureInsertPoint();
16044c8b2481SRoman Divacky 
16057fa27ce4SDimitry Andric     // Delayed globalization for variable length declarations. This ensures that
16067fa27ce4SDimitry Andric     // the expression representing the length has been emitted and can be used
16077fa27ce4SDimitry Andric     // by the definition of the VLA. Since this is an escaped declaration, in
16087fa27ce4SDimitry Andric     // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
16097fa27ce4SDimitry Andric     // deallocation call to __kmpc_free_shared() is emitted later.
16107fa27ce4SDimitry Andric     bool VarAllocated = false;
16117fa27ce4SDimitry Andric     if (getLangOpts().OpenMPIsTargetDevice) {
16127fa27ce4SDimitry Andric       auto &RT = CGM.getOpenMPRuntime();
16137fa27ce4SDimitry Andric       if (RT.isDelayedVariableLengthDecl(*this, &D)) {
16147fa27ce4SDimitry Andric         // Emit call to __kmpc_alloc_shared() instead of the alloca.
16157fa27ce4SDimitry Andric         std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
16167fa27ce4SDimitry Andric             RT.getKmpcAllocShared(*this, &D);
16177fa27ce4SDimitry Andric 
16187fa27ce4SDimitry Andric         // Save the address of the allocation:
16197fa27ce4SDimitry Andric         LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),
16207fa27ce4SDimitry Andric                                      CGM.getContext().getDeclAlign(&D),
16217fa27ce4SDimitry Andric                                      AlignmentSource::Decl);
1622ac9a064cSDimitry Andric         address = Base.getAddress();
16237fa27ce4SDimitry Andric 
16247fa27ce4SDimitry Andric         // Push a cleanup block to emit the call to __kmpc_free_shared in the
16257fa27ce4SDimitry Andric         // appropriate location at the end of the scope of the
16267fa27ce4SDimitry Andric         // __kmpc_alloc_shared functions:
16277fa27ce4SDimitry Andric         pushKmpcAllocFree(NormalCleanup, AddrSizePair);
16287fa27ce4SDimitry Andric 
16297fa27ce4SDimitry Andric         // Mark variable as allocated:
16307fa27ce4SDimitry Andric         VarAllocated = true;
16317fa27ce4SDimitry Andric       }
16327fa27ce4SDimitry Andric     }
16337fa27ce4SDimitry Andric 
16347fa27ce4SDimitry Andric     if (!VarAllocated) {
1635ec2b103cSEd Schouten       if (!DidCallStackSave) {
1636ec2b103cSEd Schouten         // Save the stack.
163745b53394SDimitry Andric         Address Stack =
1638b1c73532SDimitry Andric             CreateDefaultAlignTempAlloca(AllocaInt8PtrTy, "saved_stack");
1639ec2b103cSEd Schouten 
1640b1c73532SDimitry Andric         llvm::Value *V = Builder.CreateStackSave();
1641b1c73532SDimitry Andric         assert(V->getType() == AllocaInt8PtrTy);
1642ec2b103cSEd Schouten         Builder.CreateStore(V, Stack);
1643ec2b103cSEd Schouten 
1644ec2b103cSEd Schouten         DidCallStackSave = true;
1645ec2b103cSEd Schouten 
1646ec2b103cSEd Schouten         // Push a cleanup block and restore the stack there.
1647bca07a45SDimitry Andric         // FIXME: in general circumstances, this should be an EH cleanup.
16489f4dbff6SDimitry Andric         pushStackRestore(NormalCleanup, Stack);
1649ec2b103cSEd Schouten       }
1650ec2b103cSEd Schouten 
165148675466SDimitry Andric       auto VlaSize = getVLASize(Ty);
165248675466SDimitry Andric       llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1653ec2b103cSEd Schouten 
1654ec2b103cSEd Schouten       // Allocate memory for the array.
165548675466SDimitry Andric       address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
165648675466SDimitry Andric                                  &AllocaAddr);
16577fa27ce4SDimitry Andric     }
165848675466SDimitry Andric 
165948675466SDimitry Andric     // If we have debug info enabled, properly describe the VLA dimensions for
166048675466SDimitry Andric     // this type by registering the vla size expression for each of the
166148675466SDimitry Andric     // dimensions.
166248675466SDimitry Andric     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1663ec2b103cSEd Schouten   }
1664ec2b103cSEd Schouten 
166545b53394SDimitry Andric   setAddrOfLocalVar(&D, address);
166645b53394SDimitry Andric   emission.Addr = address;
166748675466SDimitry Andric   emission.AllocaAddr = AllocaAddr;
1668ec2b103cSEd Schouten 
1669ec2b103cSEd Schouten   // Emit debug info for local var declaration.
167048675466SDimitry Andric   if (EmitDebugInfo && HaveInsertPoint()) {
167122989816SDimitry Andric     Address DebugAddr = address;
167222989816SDimitry Andric     bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1673ec2b103cSEd Schouten     DI->setLocation(D.getLocation());
167422989816SDimitry Andric 
167522989816SDimitry Andric     // If NRVO, use a pointer to the return address.
1676c0981da4SDimitry Andric     if (UsePointerValue) {
167722989816SDimitry Andric       DebugAddr = ReturnValuePointer;
1678c0981da4SDimitry Andric       AllocaAddr = ReturnValuePointer;
1679c0981da4SDimitry Andric     }
1680c0981da4SDimitry Andric     (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
168122989816SDimitry Andric                                         UsePointerValue);
168256d91b49SDimitry Andric   }
1683ec2b103cSEd Schouten 
168422989816SDimitry Andric   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1685ac9a064cSDimitry Andric     EmitVarAnnotations(&D, address.emitRawPointer(*this));
168636981b17SDimitry Andric 
16877442d6faSDimitry Andric   // Make sure we call @llvm.lifetime.end.
16887442d6faSDimitry Andric   if (emission.useLifetimeMarkers())
16897442d6faSDimitry Andric     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
169048675466SDimitry Andric                                          emission.getOriginalAllocatedAddress(),
16917442d6faSDimitry Andric                                          emission.getSizeForLifetimeMarkers());
16927442d6faSDimitry Andric 
1693c3b054d2SDimitry Andric   return emission;
1694c3b054d2SDimitry Andric }
1695c3b054d2SDimitry Andric 
169648675466SDimitry Andric static bool isCapturedBy(const VarDecl &, const Expr *);
169748675466SDimitry Andric 
169848675466SDimitry Andric /// Determines whether the given __block variable is potentially
169948675466SDimitry Andric /// captured by the given statement.
isCapturedBy(const VarDecl & Var,const Stmt * S)170048675466SDimitry Andric static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
170148675466SDimitry Andric   if (const Expr *E = dyn_cast<Expr>(S))
170248675466SDimitry Andric     return isCapturedBy(Var, E);
170348675466SDimitry Andric   for (const Stmt *SubStmt : S->children())
170448675466SDimitry Andric     if (isCapturedBy(Var, SubStmt))
170548675466SDimitry Andric       return true;
170648675466SDimitry Andric   return false;
170748675466SDimitry Andric }
170848675466SDimitry Andric 
1709c3b054d2SDimitry Andric /// Determines whether the given __block variable is potentially
1710c3b054d2SDimitry Andric /// captured by the given expression.
isCapturedBy(const VarDecl & Var,const Expr * E)171148675466SDimitry Andric static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1712c3b054d2SDimitry Andric   // Skip the most common kinds of expressions that make
1713c3b054d2SDimitry Andric   // hierarchy-walking expensive.
171448675466SDimitry Andric   E = E->IgnoreParenCasts();
1715c3b054d2SDimitry Andric 
171648675466SDimitry Andric   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
171748675466SDimitry Andric     const BlockDecl *Block = BE->getBlockDecl();
171848675466SDimitry Andric     for (const auto &I : Block->captures()) {
171948675466SDimitry Andric       if (I.getVariable() == &Var)
1720c3b054d2SDimitry Andric         return true;
1721c3b054d2SDimitry Andric     }
1722c3b054d2SDimitry Andric 
1723c3b054d2SDimitry Andric     // No need to walk into the subexpressions.
1724c3b054d2SDimitry Andric     return false;
1725c3b054d2SDimitry Andric   }
1726c3b054d2SDimitry Andric 
172748675466SDimitry Andric   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
172836981b17SDimitry Andric     const CompoundStmt *CS = SE->getSubStmt();
17299f4dbff6SDimitry Andric     for (const auto *BI : CS->body())
173048675466SDimitry Andric       if (const auto *BIE = dyn_cast<Expr>(BI)) {
173148675466SDimitry Andric         if (isCapturedBy(Var, BIE))
173236981b17SDimitry Andric           return true;
173336981b17SDimitry Andric       }
17349f4dbff6SDimitry Andric       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
173536981b17SDimitry Andric           // special case declarations
17369f4dbff6SDimitry Andric           for (const auto *I : DS->decls()) {
17379f4dbff6SDimitry Andric               if (const auto *VD = dyn_cast<VarDecl>((I))) {
17389f4dbff6SDimitry Andric                 const Expr *Init = VD->getInit();
173948675466SDimitry Andric                 if (Init && isCapturedBy(Var, Init))
174036981b17SDimitry Andric                   return true;
174136981b17SDimitry Andric               }
174236981b17SDimitry Andric           }
174336981b17SDimitry Andric       }
174436981b17SDimitry Andric       else
174536981b17SDimitry Andric         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
174636981b17SDimitry Andric         // Later, provide code to poke into statements for capture analysis.
174736981b17SDimitry Andric         return true;
174836981b17SDimitry Andric     return false;
174936981b17SDimitry Andric   }
175036981b17SDimitry Andric 
175148675466SDimitry Andric   for (const Stmt *SubStmt : E->children())
175248675466SDimitry Andric     if (isCapturedBy(Var, SubStmt))
1753c3b054d2SDimitry Andric       return true;
1754c3b054d2SDimitry Andric 
1755c3b054d2SDimitry Andric   return false;
1756c3b054d2SDimitry Andric }
1757c3b054d2SDimitry Andric 
175848675466SDimitry Andric /// Determine whether the given initializer is trivial in the sense
1759180abc3dSDimitry Andric /// that it requires no code to be generated.
isTrivialInitializer(const Expr * Init)176006d4ba38SDimitry Andric bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1761180abc3dSDimitry Andric   if (!Init)
1762180abc3dSDimitry Andric     return true;
1763180abc3dSDimitry Andric 
1764180abc3dSDimitry Andric   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1765180abc3dSDimitry Andric     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1766180abc3dSDimitry Andric       if (Constructor->isTrivial() &&
1767180abc3dSDimitry Andric           Constructor->isDefaultConstructor() &&
1768180abc3dSDimitry Andric           !Construct->requiresZeroInitialization())
1769180abc3dSDimitry Andric         return true;
1770180abc3dSDimitry Andric 
1771180abc3dSDimitry Andric   return false;
1772180abc3dSDimitry Andric }
17732b6b257fSDimitry Andric 
emitZeroOrPatternForAutoVarInit(QualType type,const VarDecl & D,Address Loc)177422989816SDimitry Andric void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
177522989816SDimitry Andric                                                       const VarDecl &D,
177622989816SDimitry Andric                                                       Address Loc) {
177722989816SDimitry Andric   auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
17784df029ccSDimitry Andric   auto trivialAutoVarInitMaxSize =
17794df029ccSDimitry Andric       getContext().getLangOpts().TrivialAutoVarInitMaxSize;
178022989816SDimitry Andric   CharUnits Size = getContext().getTypeSizeInChars(type);
178122989816SDimitry Andric   bool isVolatile = type.isVolatileQualified();
178222989816SDimitry Andric   if (!Size.isZero()) {
17834df029ccSDimitry Andric     // We skip auto-init variables by their alloc size. Take this as an example:
17844df029ccSDimitry Andric     // "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.
17854df029ccSDimitry Andric     // All Foo type variables will be skipped. Ideally, we only skip the buff
17864df029ccSDimitry Andric     // array and still auto-init X in this example.
17874df029ccSDimitry Andric     // TODO: Improve the size filtering to by member size.
17884df029ccSDimitry Andric     auto allocSize = CGM.getDataLayout().getTypeAllocSize(Loc.getElementType());
178922989816SDimitry Andric     switch (trivialAutoVarInit) {
179022989816SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
179122989816SDimitry Andric       llvm_unreachable("Uninitialized handled by caller");
179222989816SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Zero:
1793cfca06d7SDimitry Andric       if (CGM.stopAutoInit())
1794cfca06d7SDimitry Andric         return;
17954df029ccSDimitry Andric       if (trivialAutoVarInitMaxSize > 0 &&
17964df029ccSDimitry Andric           allocSize > trivialAutoVarInitMaxSize)
17974df029ccSDimitry Andric         return;
179822989816SDimitry Andric       emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
179922989816SDimitry Andric       break;
180022989816SDimitry Andric     case LangOptions::TrivialAutoVarInitKind::Pattern:
1801cfca06d7SDimitry Andric       if (CGM.stopAutoInit())
1802cfca06d7SDimitry Andric         return;
18034df029ccSDimitry Andric       if (trivialAutoVarInitMaxSize > 0 &&
18044df029ccSDimitry Andric           allocSize > trivialAutoVarInitMaxSize)
18054df029ccSDimitry Andric         return;
180622989816SDimitry Andric       emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
180722989816SDimitry Andric       break;
180822989816SDimitry Andric     }
180922989816SDimitry Andric     return;
181022989816SDimitry Andric   }
181122989816SDimitry Andric 
181222989816SDimitry Andric   // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
181322989816SDimitry Andric   // them, so emit a memcpy with the VLA size to initialize each element.
181422989816SDimitry Andric   // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
181522989816SDimitry Andric   // will catch that code, but there exists code which generates zero-sized
181622989816SDimitry Andric   // VLAs. Be nice and initialize whatever they requested.
181722989816SDimitry Andric   const auto *VlaType = getContext().getAsVariableArrayType(type);
181822989816SDimitry Andric   if (!VlaType)
181922989816SDimitry Andric     return;
182022989816SDimitry Andric   auto VlaSize = getVLASize(VlaType);
182122989816SDimitry Andric   auto SizeVal = VlaSize.NumElts;
182222989816SDimitry Andric   CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
182322989816SDimitry Andric   switch (trivialAutoVarInit) {
182422989816SDimitry Andric   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
182522989816SDimitry Andric     llvm_unreachable("Uninitialized handled by caller");
182622989816SDimitry Andric 
1827b60736ecSDimitry Andric   case LangOptions::TrivialAutoVarInitKind::Zero: {
1828cfca06d7SDimitry Andric     if (CGM.stopAutoInit())
1829cfca06d7SDimitry Andric       return;
183022989816SDimitry Andric     if (!EltSize.isOne())
183122989816SDimitry Andric       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1832b60736ecSDimitry Andric     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1833b60736ecSDimitry Andric                                    SizeVal, isVolatile);
1834b60736ecSDimitry Andric     I->addAnnotationMetadata("auto-init");
183522989816SDimitry Andric     break;
1836b60736ecSDimitry Andric   }
183722989816SDimitry Andric 
183822989816SDimitry Andric   case LangOptions::TrivialAutoVarInitKind::Pattern: {
1839cfca06d7SDimitry Andric     if (CGM.stopAutoInit())
1840cfca06d7SDimitry Andric       return;
184122989816SDimitry Andric     llvm::Type *ElTy = Loc.getElementType();
184222989816SDimitry Andric     llvm::Constant *Constant = constWithPadding(
184322989816SDimitry Andric         CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
184422989816SDimitry Andric     CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
184522989816SDimitry Andric     llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
184622989816SDimitry Andric     llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
184722989816SDimitry Andric     llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
184822989816SDimitry Andric     llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
184922989816SDimitry Andric         SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
185022989816SDimitry Andric         "vla.iszerosized");
185122989816SDimitry Andric     Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
185222989816SDimitry Andric     EmitBlock(SetupBB);
185322989816SDimitry Andric     if (!EltSize.isOne())
185422989816SDimitry Andric       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
185522989816SDimitry Andric     llvm::Value *BaseSizeInChars =
185622989816SDimitry Andric         llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
18577fa27ce4SDimitry Andric     Address Begin = Loc.withElementType(Int8Ty);
1858ac9a064cSDimitry Andric     llvm::Value *End = Builder.CreateInBoundsGEP(Begin.getElementType(),
1859ac9a064cSDimitry Andric                                                  Begin.emitRawPointer(*this),
1860ac9a064cSDimitry Andric                                                  SizeVal, "vla.end");
186122989816SDimitry Andric     llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
186222989816SDimitry Andric     EmitBlock(LoopBB);
186322989816SDimitry Andric     llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1864ac9a064cSDimitry Andric     Cur->addIncoming(Begin.emitRawPointer(*this), OriginBB);
186522989816SDimitry Andric     CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1866b60736ecSDimitry Andric     auto *I =
1867145449b1SDimitry Andric         Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
186822989816SDimitry Andric                              createUnnamedGlobalForMemcpyFrom(
186922989816SDimitry Andric                                  CGM, D, Builder, Constant, ConstantAlign),
187022989816SDimitry Andric                              BaseSizeInChars, isVolatile);
1871b60736ecSDimitry Andric     I->addAnnotationMetadata("auto-init");
187222989816SDimitry Andric     llvm::Value *Next =
187322989816SDimitry Andric         Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
187422989816SDimitry Andric     llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
187522989816SDimitry Andric     Builder.CreateCondBr(Done, ContBB, LoopBB);
187622989816SDimitry Andric     Cur->addIncoming(Next, LoopBB);
187722989816SDimitry Andric     EmitBlock(ContBB);
187822989816SDimitry Andric   } break;
187922989816SDimitry Andric   }
188022989816SDimitry Andric }
188122989816SDimitry Andric 
EmitAutoVarInit(const AutoVarEmission & emission)1882c3b054d2SDimitry Andric void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1883c3b054d2SDimitry Andric   assert(emission.Variable && "emission was not valid!");
1884c3b054d2SDimitry Andric 
1885c3b054d2SDimitry Andric   // If this was emitted as a global constant, we're done.
1886c3b054d2SDimitry Andric   if (emission.wasEmittedAsGlobal()) return;
1887c3b054d2SDimitry Andric 
1888c3b054d2SDimitry Andric   const VarDecl &D = *emission.Variable;
18895e20cdd8SDimitry Andric   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1890c3b054d2SDimitry Andric   QualType type = D.getType();
1891c3b054d2SDimitry Andric 
1892ec2b103cSEd Schouten   // If this local has an initializer, emit it now.
18934c8b2481SRoman Divacky   const Expr *Init = D.getInit();
18944c8b2481SRoman Divacky 
18954c8b2481SRoman Divacky   // If we are at an unreachable point, we don't need to emit the initializer
18964c8b2481SRoman Divacky   // unless it contains a label.
18974c8b2481SRoman Divacky   if (!HaveInsertPoint()) {
1898c3b054d2SDimitry Andric     if (!Init || !ContainsLabel(Init)) return;
18994c8b2481SRoman Divacky     EnsureInsertPoint();
1900ec2b103cSEd Schouten   }
19014c8b2481SRoman Divacky 
190201af97d3SDimitry Andric   // Initialize the structure of a __block variable.
1903676fbe81SDimitry Andric   if (emission.IsEscapingByRef)
190401af97d3SDimitry Andric     emitByrefStructureInit(emission);
19054a37f65fSRoman Divacky 
190648675466SDimitry Andric   // Initialize the variable here if it doesn't have a initializer and it is a
190748675466SDimitry Andric   // C struct that is non-trivial to initialize or an array containing such a
190848675466SDimitry Andric   // struct.
190948675466SDimitry Andric   if (!Init &&
191048675466SDimitry Andric       type.isNonTrivialToPrimitiveDefaultInitialize() ==
191148675466SDimitry Andric           QualType::PDIK_Struct) {
191248675466SDimitry Andric     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1913676fbe81SDimitry Andric     if (emission.IsEscapingByRef)
191448675466SDimitry Andric       drillIntoBlockVariable(*this, Dst, &D);
191548675466SDimitry Andric     defaultInitNonTrivialCStructVar(Dst);
191648675466SDimitry Andric     return;
191748675466SDimitry Andric   }
191848675466SDimitry Andric 
1919c3b054d2SDimitry Andric   // Check whether this is a byref variable that's potentially
1920c3b054d2SDimitry Andric   // captured and moved by its own initializer.  If so, we'll need to
1921c3b054d2SDimitry Andric   // emit the initializer first, then copy into the variable.
1922676fbe81SDimitry Andric   bool capturedByInit =
1923676fbe81SDimitry Andric       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
192434d02d0bSRoman Divacky 
192522989816SDimitry Andric   bool locIsByrefHeader = !capturedByInit;
192622989816SDimitry Andric   const Address Loc =
192722989816SDimitry Andric       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1928c3b054d2SDimitry Andric 
1929676fbe81SDimitry Andric   // Note: constexpr already initializes everything correctly.
1930676fbe81SDimitry Andric   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1931676fbe81SDimitry Andric       (D.isConstexpr()
1932676fbe81SDimitry Andric            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1933676fbe81SDimitry Andric            : (D.getAttr<UninitializedAttr>()
1934676fbe81SDimitry Andric                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1935676fbe81SDimitry Andric                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1936676fbe81SDimitry Andric 
193722989816SDimitry Andric   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1938676fbe81SDimitry Andric     if (trivialAutoVarInit ==
1939676fbe81SDimitry Andric         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1940676fbe81SDimitry Andric       return;
1941676fbe81SDimitry Andric 
194222989816SDimitry Andric     // Only initialize a __block's storage: we always initialize the header.
194322989816SDimitry Andric     if (emission.IsEscapingByRef && !locIsByrefHeader)
194422989816SDimitry Andric       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1945676fbe81SDimitry Andric 
194622989816SDimitry Andric     return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1947676fbe81SDimitry Andric   };
1948676fbe81SDimitry Andric 
194922989816SDimitry Andric   if (isTrivialInitializer(Init))
195022989816SDimitry Andric     return initializeWhatIsTechnicallyUninitialized(Loc);
1951676fbe81SDimitry Andric 
19529f4dbff6SDimitry Andric   llvm::Constant *constant = nullptr;
195322989816SDimitry Andric   if (emission.IsConstantAggregate ||
195422989816SDimitry Andric       D.mightBeUsableInConstantExpressions(getContext())) {
1955dbe13110SDimitry Andric     assert(!capturedByInit && "constant init contains a capturing block?");
1956461a67faSDimitry Andric     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
195722989816SDimitry Andric     if (constant && !constant->isZeroValue() &&
195822989816SDimitry Andric         (trivialAutoVarInit !=
195922989816SDimitry Andric          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
196022989816SDimitry Andric       IsPattern isPattern =
196122989816SDimitry Andric           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
196222989816SDimitry Andric               ? IsPattern::Yes
196322989816SDimitry Andric               : IsPattern::No;
196422989816SDimitry Andric       // C guarantees that brace-init with fewer initializers than members in
196522989816SDimitry Andric       // the aggregate will initialize the rest of the aggregate as-if it were
196622989816SDimitry Andric       // static initialization. In turn static initialization guarantees that
196722989816SDimitry Andric       // padding is initialized to zero bits. We could instead pattern-init if D
196822989816SDimitry Andric       // has any ImplicitValueInitExpr, but that seems to be unintuitive
196922989816SDimitry Andric       // behavior.
197022989816SDimitry Andric       constant = constWithPadding(CGM, IsPattern::No,
197122989816SDimitry Andric                                   replaceUndef(CGM, isPattern, constant));
197222989816SDimitry Andric     }
1973ac9a064cSDimitry Andric 
1974ac9a064cSDimitry Andric     if (D.getType()->isBitIntType() &&
1975ac9a064cSDimitry Andric         CGM.getTypes().typeRequiresSplitIntoByteArray(D.getType())) {
1976ac9a064cSDimitry Andric       // Constants for long _BitInt types are split into individual bytes.
1977ac9a064cSDimitry Andric       // Try to fold these back into an integer constant so it can be stored
1978ac9a064cSDimitry Andric       // properly.
1979ac9a064cSDimitry Andric       llvm::Type *LoadType = CGM.getTypes().convertTypeForLoadStore(
1980ac9a064cSDimitry Andric           D.getType(), constant->getType());
1981ac9a064cSDimitry Andric       constant = llvm::ConstantFoldLoadFromConst(
1982ac9a064cSDimitry Andric           constant, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());
1983ac9a064cSDimitry Andric     }
1984dbe13110SDimitry Andric   }
1985dbe13110SDimitry Andric 
1986dbe13110SDimitry Andric   if (!constant) {
1987ac9a064cSDimitry Andric     if (trivialAutoVarInit !=
1988ac9a064cSDimitry Andric         LangOptions::TrivialAutoVarInitKind::Uninitialized) {
1989ac9a064cSDimitry Andric       // At this point, we know D has an Init expression, but isn't a constant.
1990ac9a064cSDimitry Andric       // - If D is not a scalar, auto-var-init conservatively (members may be
1991ac9a064cSDimitry Andric       // left uninitialized by constructor Init expressions for example).
1992ac9a064cSDimitry Andric       // - If D is a scalar, we only need to auto-var-init if there is a
1993ac9a064cSDimitry Andric       // self-reference. Otherwise, the Init expression should be sufficient.
1994ac9a064cSDimitry Andric       // It may be that the Init expression uses other uninitialized memory,
1995ac9a064cSDimitry Andric       // but auto-var-init here would not help, as auto-init would get
1996ac9a064cSDimitry Andric       // overwritten by Init.
1997ac9a064cSDimitry Andric       if (!D.getType()->isScalarType() || capturedByInit ||
1998ac9a064cSDimitry Andric           isAccessedBy(D, Init)) {
199922989816SDimitry Andric         initializeWhatIsTechnicallyUninitialized(Loc);
2000ac9a064cSDimitry Andric       }
2001ac9a064cSDimitry Andric     }
200245b53394SDimitry Andric     LValue lv = MakeAddrLValue(Loc, type);
2003180abc3dSDimitry Andric     lv.setNonGC(true);
2004180abc3dSDimitry Andric     return EmitExprAsInit(Init, &D, lv, capturedByInit);
2005180abc3dSDimitry Andric   }
2006c3b054d2SDimitry Andric 
2007bfef3995SDimitry Andric   if (!emission.IsConstantAggregate) {
2008bfef3995SDimitry Andric     // For simple scalar/complex initialization, store the value directly.
200945b53394SDimitry Andric     LValue lv = MakeAddrLValue(Loc, type);
2010bfef3995SDimitry Andric     lv.setNonGC(true);
2011bfef3995SDimitry Andric     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
2012bfef3995SDimitry Andric   }
2013bfef3995SDimitry Andric 
20147fa27ce4SDimitry Andric   emitStoresForConstant(CGM, D, Loc.withElementType(CGM.Int8Ty),
2015145449b1SDimitry Andric                         type.isVolatileQualified(), Builder, constant,
2016145449b1SDimitry Andric                         /*IsAutoInit=*/false);
201734d02d0bSRoman Divacky }
201801af97d3SDimitry Andric 
201948675466SDimitry Andric /// Emit an expression as an initializer for an object (variable, field, etc.)
202048675466SDimitry Andric /// at the given location.  The expression is not necessarily the normal
202148675466SDimitry Andric /// initializer for the object, and the address is not necessarily
202201af97d3SDimitry Andric /// its normal location.
202301af97d3SDimitry Andric ///
202401af97d3SDimitry Andric /// \param init the initializing expression
202548675466SDimitry Andric /// \param D the object to act as if we're initializing
2026cfca06d7SDimitry Andric /// \param lvalue the lvalue to initialize
202748675466SDimitry Andric /// \param capturedByInit true if \p D is a __block variable
202801af97d3SDimitry Andric ///   whose address is potentially changed by the initializer
EmitExprAsInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)202906d4ba38SDimitry Andric void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
203006d4ba38SDimitry Andric                                      LValue lvalue, bool capturedByInit) {
2031180abc3dSDimitry Andric   QualType type = D->getType();
203201af97d3SDimitry Andric 
203301af97d3SDimitry Andric   if (type->isReferenceType()) {
2034bfef3995SDimitry Andric     RValue rvalue = EmitReferenceBindingToExpr(init);
2035180abc3dSDimitry Andric     if (capturedByInit)
2036180abc3dSDimitry Andric       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
2037dbe13110SDimitry Andric     EmitStoreThroughLValue(rvalue, lvalue, true);
2038809500fcSDimitry Andric     return;
2039809500fcSDimitry Andric   }
2040809500fcSDimitry Andric   switch (getEvaluationKind(type)) {
2041809500fcSDimitry Andric   case TEK_Scalar:
2042180abc3dSDimitry Andric     EmitScalarInit(init, D, lvalue, capturedByInit);
2043809500fcSDimitry Andric     return;
2044809500fcSDimitry Andric   case TEK_Complex: {
204501af97d3SDimitry Andric     ComplexPairTy complex = EmitComplexExpr(init);
2046180abc3dSDimitry Andric     if (capturedByInit)
2047180abc3dSDimitry Andric       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
2048809500fcSDimitry Andric     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
2049809500fcSDimitry Andric     return;
2050809500fcSDimitry Andric   }
2051809500fcSDimitry Andric   case TEK_Aggregate:
2052809500fcSDimitry Andric     if (type->isAtomicType()) {
2053809500fcSDimitry Andric       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
2054ec2b103cSEd Schouten     } else {
205548675466SDimitry Andric       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
205648675466SDimitry Andric       if (isa<VarDecl>(D))
205748675466SDimitry Andric         Overlap = AggValueSlot::DoesNotOverlap;
205848675466SDimitry Andric       else if (auto *FD = dyn_cast<FieldDecl>(D))
205922989816SDimitry Andric         Overlap = getOverlapForFieldInit(FD);
2060c3b054d2SDimitry Andric       // TODO: how can we delay here if D is captured by its initializer?
2061ac9a064cSDimitry Andric       EmitAggExpr(init,
2062ac9a064cSDimitry Andric                   AggValueSlot::forLValue(lvalue, AggValueSlot::IsDestructed,
206336981b17SDimitry Andric                                           AggValueSlot::DoesNotNeedGCBarriers,
2064706b4fc4SDimitry Andric                                           AggValueSlot::IsNotAliased, Overlap));
2065ec2b103cSEd Schouten     }
2066809500fcSDimitry Andric     return;
2067809500fcSDimitry Andric   }
2068809500fcSDimitry Andric   llvm_unreachable("bad evaluation kind");
2069ec2b103cSEd Schouten }
2070ec2b103cSEd Schouten 
2071180abc3dSDimitry Andric /// Enter a destroy cleanup for the given local variable.
emitAutoVarTypeCleanup(const CodeGenFunction::AutoVarEmission & emission,QualType::DestructionKind dtorKind)2072180abc3dSDimitry Andric void CodeGenFunction::emitAutoVarTypeCleanup(
2073180abc3dSDimitry Andric                             const CodeGenFunction::AutoVarEmission &emission,
2074180abc3dSDimitry Andric                             QualType::DestructionKind dtorKind) {
2075180abc3dSDimitry Andric   assert(dtorKind != QualType::DK_none);
2076180abc3dSDimitry Andric 
2077180abc3dSDimitry Andric   // Note that for __block variables, we want to destroy the
2078180abc3dSDimitry Andric   // original stack object, not the possibly forwarded object.
207945b53394SDimitry Andric   Address addr = emission.getObjectAddress(*this);
2080180abc3dSDimitry Andric 
2081180abc3dSDimitry Andric   const VarDecl *var = emission.Variable;
2082180abc3dSDimitry Andric   QualType type = var->getType();
2083180abc3dSDimitry Andric 
2084180abc3dSDimitry Andric   CleanupKind cleanupKind = NormalAndEHCleanup;
20859f4dbff6SDimitry Andric   CodeGenFunction::Destroyer *destroyer = nullptr;
2086180abc3dSDimitry Andric 
2087180abc3dSDimitry Andric   switch (dtorKind) {
2088180abc3dSDimitry Andric   case QualType::DK_none:
2089180abc3dSDimitry Andric     llvm_unreachable("no cleanup for trivially-destructible variable");
2090180abc3dSDimitry Andric 
2091180abc3dSDimitry Andric   case QualType::DK_cxx_destructor:
2092180abc3dSDimitry Andric     // If there's an NRVO flag on the emission, we need a different
2093180abc3dSDimitry Andric     // cleanup.
2094180abc3dSDimitry Andric     if (emission.NRVOFlag) {
2095180abc3dSDimitry Andric       assert(!type->isArrayType());
2096180abc3dSDimitry Andric       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
209722989816SDimitry Andric       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
209848675466SDimitry Andric                                                   emission.NRVOFlag);
2099180abc3dSDimitry Andric       return;
2100180abc3dSDimitry Andric     }
2101180abc3dSDimitry Andric     break;
2102180abc3dSDimitry Andric 
2103180abc3dSDimitry Andric   case QualType::DK_objc_strong_lifetime:
2104180abc3dSDimitry Andric     // Suppress cleanups for pseudo-strong variables.
2105180abc3dSDimitry Andric     if (var->isARCPseudoStrong()) return;
2106180abc3dSDimitry Andric 
2107180abc3dSDimitry Andric     // Otherwise, consider whether to use an EH cleanup or not.
2108180abc3dSDimitry Andric     cleanupKind = getARCCleanupKind();
2109180abc3dSDimitry Andric 
2110180abc3dSDimitry Andric     // Use the imprecise destroyer by default.
2111180abc3dSDimitry Andric     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2112180abc3dSDimitry Andric       destroyer = CodeGenFunction::destroyARCStrongImprecise;
2113180abc3dSDimitry Andric     break;
2114180abc3dSDimitry Andric 
2115180abc3dSDimitry Andric   case QualType::DK_objc_weak_lifetime:
2116180abc3dSDimitry Andric     break;
211748675466SDimitry Andric 
211848675466SDimitry Andric   case QualType::DK_nontrivial_c_struct:
211948675466SDimitry Andric     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
212048675466SDimitry Andric     if (emission.NRVOFlag) {
212148675466SDimitry Andric       assert(!type->isArrayType());
212248675466SDimitry Andric       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
212348675466SDimitry Andric                                                 emission.NRVOFlag, type);
212448675466SDimitry Andric       return;
212548675466SDimitry Andric     }
212648675466SDimitry Andric     break;
2127180abc3dSDimitry Andric   }
2128180abc3dSDimitry Andric 
2129180abc3dSDimitry Andric   // If we haven't chosen a more specific destroyer, use the default.
2130dbe13110SDimitry Andric   if (!destroyer) destroyer = getDestroyer(dtorKind);
2131180abc3dSDimitry Andric 
2132180abc3dSDimitry Andric   // Use an EH cleanup in array destructors iff the destructor itself
2133180abc3dSDimitry Andric   // is being pushed as an EH cleanup.
2134180abc3dSDimitry Andric   bool useEHCleanup = (cleanupKind & EHCleanup);
2135180abc3dSDimitry Andric   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2136180abc3dSDimitry Andric                                      useEHCleanup);
2137180abc3dSDimitry Andric }
2138180abc3dSDimitry Andric 
EmitAutoVarCleanups(const AutoVarEmission & emission)2139c3b054d2SDimitry Andric void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2140c3b054d2SDimitry Andric   assert(emission.Variable && "emission was not valid!");
2141c3b054d2SDimitry Andric 
2142c3b054d2SDimitry Andric   // If this was emitted as a global constant, we're done.
2143c3b054d2SDimitry Andric   if (emission.wasEmittedAsGlobal()) return;
2144c3b054d2SDimitry Andric 
21456b9a6e39SDimitry Andric   // If we don't have an insertion point, we're done.  Sema prevents
21466b9a6e39SDimitry Andric   // us from jumping into any of these scopes anyway.
21476b9a6e39SDimitry Andric   if (!HaveInsertPoint()) return;
21486b9a6e39SDimitry Andric 
2149c3b054d2SDimitry Andric   const VarDecl &D = *emission.Variable;
2150c3b054d2SDimitry Andric 
2151180abc3dSDimitry Andric   // Check the type for a cleanup.
2152519fc96cSDimitry Andric   if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2153180abc3dSDimitry Andric     emitAutoVarTypeCleanup(emission, dtorKind);
2154c3b054d2SDimitry Andric 
2155180abc3dSDimitry Andric   // In GC mode, honor objc_precise_lifetime.
2156dbe13110SDimitry Andric   if (getLangOpts().getGC() != LangOptions::NonGC &&
2157180abc3dSDimitry Andric       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2158180abc3dSDimitry Andric     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
21598f57cb03SRoman Divacky   }
21604c8b2481SRoman Divacky 
2161c3b054d2SDimitry Andric   // Handle the cleanup attribute.
21625362a71cSEd Schouten   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2163ec2b103cSEd Schouten     const FunctionDecl *FD = CA->getFunctionDecl();
2164ec2b103cSEd Schouten 
21654c8b2481SRoman Divacky     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2166ec2b103cSEd Schouten     assert(F && "Could not find function!");
2167ec2b103cSEd Schouten 
2168dbe13110SDimitry Andric     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2169c3b054d2SDimitry Andric     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
217034d02d0bSRoman Divacky   }
2171ec2b103cSEd Schouten 
2172c3b054d2SDimitry Andric   // If this is a block variable, call _Block_object_destroy
217348675466SDimitry Andric   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
217448675466SDimitry Andric   // mode.
2175676fbe81SDimitry Andric   if (emission.IsEscapingByRef &&
2176676fbe81SDimitry Andric       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
217748675466SDimitry Andric     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
217848675466SDimitry Andric     if (emission.Variable->getType().isObjCGCWeak())
217948675466SDimitry Andric       Flags |= BLOCK_FIELD_IS_WEAK;
218048675466SDimitry Andric     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2181676fbe81SDimitry Andric                       /*LoadBlockVarAddr*/ false,
2182676fbe81SDimitry Andric                       cxxDestructorCanThrow(emission.Variable->getType()));
218348675466SDimitry Andric   }
2184ec2b103cSEd Schouten }
2185ec2b103cSEd Schouten 
2186dbe13110SDimitry Andric CodeGenFunction::Destroyer *
getDestroyer(QualType::DestructionKind kind)2187180abc3dSDimitry Andric CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2188180abc3dSDimitry Andric   switch (kind) {
2189180abc3dSDimitry Andric   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2190180abc3dSDimitry Andric   case QualType::DK_cxx_destructor:
2191dbe13110SDimitry Andric     return destroyCXXObject;
2192180abc3dSDimitry Andric   case QualType::DK_objc_strong_lifetime:
2193dbe13110SDimitry Andric     return destroyARCStrongPrecise;
2194180abc3dSDimitry Andric   case QualType::DK_objc_weak_lifetime:
2195dbe13110SDimitry Andric     return destroyARCWeak;
219648675466SDimitry Andric   case QualType::DK_nontrivial_c_struct:
219748675466SDimitry Andric     return destroyNonTrivialCStruct;
2198180abc3dSDimitry Andric   }
2199dbe13110SDimitry Andric   llvm_unreachable("Unknown DestructionKind");
2200180abc3dSDimitry Andric }
2201180abc3dSDimitry Andric 
2202809500fcSDimitry Andric /// pushEHDestroy - Push the standard destructor for the given type as
2203809500fcSDimitry Andric /// an EH-only cleanup.
pushEHDestroy(QualType::DestructionKind dtorKind,Address addr,QualType type)2204809500fcSDimitry Andric void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
220545b53394SDimitry Andric                                     Address addr, QualType type) {
2206809500fcSDimitry Andric   assert(dtorKind && "cannot push destructor for trivial type");
2207809500fcSDimitry Andric   assert(needsEHCleanup(dtorKind));
2208809500fcSDimitry Andric 
2209809500fcSDimitry Andric   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2210809500fcSDimitry Andric }
2211809500fcSDimitry Andric 
2212809500fcSDimitry Andric /// pushDestroy - Push the standard destructor for the given type as
2213809500fcSDimitry Andric /// at least a normal cleanup.
pushDestroy(QualType::DestructionKind dtorKind,Address addr,QualType type)2214180abc3dSDimitry Andric void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
221545b53394SDimitry Andric                                   Address addr, QualType type) {
2216180abc3dSDimitry Andric   assert(dtorKind && "cannot push destructor for trivial type");
2217180abc3dSDimitry Andric 
2218180abc3dSDimitry Andric   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2219180abc3dSDimitry Andric   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2220180abc3dSDimitry Andric               cleanupKind & EHCleanup);
2221180abc3dSDimitry Andric }
2222180abc3dSDimitry Andric 
pushDestroy(CleanupKind cleanupKind,Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)222345b53394SDimitry Andric void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2224dbe13110SDimitry Andric                                   QualType type, Destroyer *destroyer,
2225180abc3dSDimitry Andric                                   bool useEHCleanupForArray) {
2226180abc3dSDimitry Andric   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2227180abc3dSDimitry Andric                                      destroyer, useEHCleanupForArray);
2228180abc3dSDimitry Andric }
2229180abc3dSDimitry Andric 
2230ac9a064cSDimitry Andric // Pushes a destroy and defers its deactivation until its
2231ac9a064cSDimitry Andric // CleanupDeactivationScope is exited.
pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind,Address addr,QualType type)2232ac9a064cSDimitry Andric void CodeGenFunction::pushDestroyAndDeferDeactivation(
2233ac9a064cSDimitry Andric     QualType::DestructionKind dtorKind, Address addr, QualType type) {
2234ac9a064cSDimitry Andric   assert(dtorKind && "cannot push destructor for trivial type");
2235ac9a064cSDimitry Andric 
2236ac9a064cSDimitry Andric   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2237ac9a064cSDimitry Andric   pushDestroyAndDeferDeactivation(
2238ac9a064cSDimitry Andric       cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup);
2239ac9a064cSDimitry Andric }
2240ac9a064cSDimitry Andric 
pushDestroyAndDeferDeactivation(CleanupKind cleanupKind,Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)2241ac9a064cSDimitry Andric void CodeGenFunction::pushDestroyAndDeferDeactivation(
2242ac9a064cSDimitry Andric     CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
2243ac9a064cSDimitry Andric     bool useEHCleanupForArray) {
2244ac9a064cSDimitry Andric   llvm::Instruction *DominatingIP =
2245ac9a064cSDimitry Andric       Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
2246ac9a064cSDimitry Andric   pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2247ac9a064cSDimitry Andric   DeferredDeactivationCleanupStack.push_back(
2248ac9a064cSDimitry Andric       {EHStack.stable_begin(), DominatingIP});
2249ac9a064cSDimitry Andric }
2250ac9a064cSDimitry Andric 
pushStackRestore(CleanupKind Kind,Address SPMem)225145b53394SDimitry Andric void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
22529f4dbff6SDimitry Andric   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
22539f4dbff6SDimitry Andric }
22549f4dbff6SDimitry Andric 
pushKmpcAllocFree(CleanupKind Kind,std::pair<llvm::Value *,llvm::Value * > AddrSizePair)22557fa27ce4SDimitry Andric void CodeGenFunction::pushKmpcAllocFree(
22567fa27ce4SDimitry Andric     CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
22577fa27ce4SDimitry Andric   EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);
22587fa27ce4SDimitry Andric }
22597fa27ce4SDimitry Andric 
pushLifetimeExtendedDestroy(CleanupKind cleanupKind,Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)2260b60736ecSDimitry Andric void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2261b60736ecSDimitry Andric                                                   Address addr, QualType type,
2262b60736ecSDimitry Andric                                                   Destroyer *destroyer,
2263b60736ecSDimitry Andric                                                   bool useEHCleanupForArray) {
2264b60736ecSDimitry Andric   // If we're not in a conditional branch, we don't need to bother generating a
2265b60736ecSDimitry Andric   // conditional cleanup.
2266b60736ecSDimitry Andric   if (!isInConditionalBranch()) {
2267bfef3995SDimitry Andric     // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2268bfef3995SDimitry Andric     // around in case a temporary's destructor throws an exception.
2269bfef3995SDimitry Andric 
2270ac9a064cSDimitry Andric     // Add the cleanup to the EHStack. After the full-expr, this would be
2271ac9a064cSDimitry Andric     // deactivated before being popped from the stack.
2272ac9a064cSDimitry Andric     pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
2273ac9a064cSDimitry Andric                                     useEHCleanupForArray);
2274ac9a064cSDimitry Andric 
2275ac9a064cSDimitry Andric     // Since this is lifetime-extended, push it once again to the EHStack after
2276ac9a064cSDimitry Andric     // the full expression.
2277b60736ecSDimitry Andric     return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2278ac9a064cSDimitry Andric         cleanupKind, Address::invalid(), addr, type, destroyer,
2279ac9a064cSDimitry Andric         useEHCleanupForArray);
2280b60736ecSDimitry Andric   }
2281b60736ecSDimitry Andric 
2282b60736ecSDimitry Andric   // Otherwise, we should only destroy the object if it's been initialized.
2283b60736ecSDimitry Andric 
2284b60736ecSDimitry Andric   using ConditionalCleanupType =
2285b60736ecSDimitry Andric       EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2286b60736ecSDimitry Andric                                        Destroyer *, bool>;
2287ac9a064cSDimitry Andric   DominatingValue<Address>::saved_type SavedAddr = saveValueInCond(addr);
2288b60736ecSDimitry Andric 
2289ac9a064cSDimitry Andric   // Remember to emit cleanup if we branch-out before end of full-expression
2290ac9a064cSDimitry Andric   // (eg: through stmt-expr or coro suspensions).
2291ac9a064cSDimitry Andric   AllocaTrackerRAII DeactivationAllocas(*this);
2292ac9a064cSDimitry Andric   Address ActiveFlagForDeactivation = createCleanupActiveFlag();
2293b60736ecSDimitry Andric 
2294ac9a064cSDimitry Andric   pushCleanupAndDeferDeactivation<ConditionalCleanupType>(
2295ac9a064cSDimitry Andric       cleanupKind, SavedAddr, type, destroyer, useEHCleanupForArray);
2296ac9a064cSDimitry Andric   initFullExprCleanupWithFlag(ActiveFlagForDeactivation);
2297ac9a064cSDimitry Andric   EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
2298ac9a064cSDimitry Andric   // Erase the active flag if the cleanup was not emitted.
2299ac9a064cSDimitry Andric   cleanup.AddAuxAllocas(std::move(DeactivationAllocas).Take());
2300b60736ecSDimitry Andric 
2301ac9a064cSDimitry Andric   // Since this is lifetime-extended, push it once again to the EHStack after
2302ac9a064cSDimitry Andric   // the full expression.
2303ac9a064cSDimitry Andric   // The previous active flag would always be 'false' due to forced deferred
2304ac9a064cSDimitry Andric   // deactivation. Use a separate flag for lifetime-extension to correctly
2305ac9a064cSDimitry Andric   // remember if this branch was taken and the object was initialized.
2306ac9a064cSDimitry Andric   Address ActiveFlagForLifetimeExt = createCleanupActiveFlag();
2307b60736ecSDimitry Andric   pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2308ac9a064cSDimitry Andric       cleanupKind, ActiveFlagForLifetimeExt, SavedAddr, type, destroyer,
2309b60736ecSDimitry Andric       useEHCleanupForArray);
2310bfef3995SDimitry Andric }
2311bfef3995SDimitry Andric 
2312180abc3dSDimitry Andric /// emitDestroy - Immediately perform the destruction of the given
2313180abc3dSDimitry Andric /// object.
2314180abc3dSDimitry Andric ///
2315180abc3dSDimitry Andric /// \param addr - the address of the object; a type*
2316180abc3dSDimitry Andric /// \param type - the type of the object; if an array type, all
2317180abc3dSDimitry Andric ///   objects are destroyed in reverse order
2318180abc3dSDimitry Andric /// \param destroyer - the function to call to destroy individual
2319180abc3dSDimitry Andric ///   elements
2320180abc3dSDimitry Andric /// \param useEHCleanupForArray - whether an EH cleanup should be
2321180abc3dSDimitry Andric ///   used when destroying array elements, in case one of the
2322180abc3dSDimitry Andric ///   destructions throws an exception
emitDestroy(Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)232345b53394SDimitry Andric void CodeGenFunction::emitDestroy(Address addr, QualType type,
2324dbe13110SDimitry Andric                                   Destroyer *destroyer,
2325180abc3dSDimitry Andric                                   bool useEHCleanupForArray) {
2326180abc3dSDimitry Andric   const ArrayType *arrayType = getContext().getAsArrayType(type);
2327180abc3dSDimitry Andric   if (!arrayType)
2328180abc3dSDimitry Andric     return destroyer(*this, addr, type);
2329180abc3dSDimitry Andric 
233045b53394SDimitry Andric   llvm::Value *length = emitArrayLength(arrayType, type, addr);
233145b53394SDimitry Andric 
233245b53394SDimitry Andric   CharUnits elementAlign =
233345b53394SDimitry Andric     addr.getAlignment()
233445b53394SDimitry Andric         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2335180abc3dSDimitry Andric 
2336180abc3dSDimitry Andric   // Normally we have to check whether the array is zero-length.
2337180abc3dSDimitry Andric   bool checkZeroLength = true;
2338180abc3dSDimitry Andric 
2339180abc3dSDimitry Andric   // But if the array length is constant, we can suppress that.
2340180abc3dSDimitry Andric   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2341180abc3dSDimitry Andric     // ...and if it's constant zero, we can just skip the entire thing.
2342180abc3dSDimitry Andric     if (constLength->isZero()) return;
2343180abc3dSDimitry Andric     checkZeroLength = false;
2344180abc3dSDimitry Andric   }
2345180abc3dSDimitry Andric 
2346ac9a064cSDimitry Andric   llvm::Value *begin = addr.emitRawPointer(*this);
2347344a3780SDimitry Andric   llvm::Value *end =
2348344a3780SDimitry Andric       Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
234945b53394SDimitry Andric   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2350180abc3dSDimitry Andric                    checkZeroLength, useEHCleanupForArray);
2351180abc3dSDimitry Andric }
2352180abc3dSDimitry Andric 
2353180abc3dSDimitry Andric /// emitArrayDestroy - Destroys all the elements of the given array,
2354180abc3dSDimitry Andric /// beginning from last to first.  The array cannot be zero-length.
2355180abc3dSDimitry Andric ///
2356180abc3dSDimitry Andric /// \param begin - a type* denoting the first element of the array
2357180abc3dSDimitry Andric /// \param end - a type* denoting one past the end of the array
235845b53394SDimitry Andric /// \param elementType - the element type of the array
2359180abc3dSDimitry Andric /// \param destroyer - the function to call to destroy elements
2360180abc3dSDimitry Andric /// \param useEHCleanup - whether to push an EH cleanup to destroy
2361180abc3dSDimitry Andric ///   the remaining elements in case the destruction of a single
2362180abc3dSDimitry Andric ///   element throws
emitArrayDestroy(llvm::Value * begin,llvm::Value * end,QualType elementType,CharUnits elementAlign,Destroyer * destroyer,bool checkZeroLength,bool useEHCleanup)2363180abc3dSDimitry Andric void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2364180abc3dSDimitry Andric                                        llvm::Value *end,
236545b53394SDimitry Andric                                        QualType elementType,
236645b53394SDimitry Andric                                        CharUnits elementAlign,
2367dbe13110SDimitry Andric                                        Destroyer *destroyer,
2368180abc3dSDimitry Andric                                        bool checkZeroLength,
2369180abc3dSDimitry Andric                                        bool useEHCleanup) {
237045b53394SDimitry Andric   assert(!elementType->isArrayType());
2371180abc3dSDimitry Andric 
2372180abc3dSDimitry Andric   // The basic structure here is a do-while loop, because we don't
2373180abc3dSDimitry Andric   // need to check for the zero-element case.
2374180abc3dSDimitry Andric   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2375180abc3dSDimitry Andric   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2376180abc3dSDimitry Andric 
2377180abc3dSDimitry Andric   if (checkZeroLength) {
2378180abc3dSDimitry Andric     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2379180abc3dSDimitry Andric                                                 "arraydestroy.isempty");
2380180abc3dSDimitry Andric     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2381180abc3dSDimitry Andric   }
2382180abc3dSDimitry Andric 
2383180abc3dSDimitry Andric   // Enter the loop body, making that address the current address.
2384180abc3dSDimitry Andric   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2385180abc3dSDimitry Andric   EmitBlock(bodyBB);
2386180abc3dSDimitry Andric   llvm::PHINode *elementPast =
2387180abc3dSDimitry Andric     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2388180abc3dSDimitry Andric   elementPast->addIncoming(end, entryBB);
2389180abc3dSDimitry Andric 
2390180abc3dSDimitry Andric   // Shift the address back by one element.
2391180abc3dSDimitry Andric   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
23926f8fc217SDimitry Andric   llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2393344a3780SDimitry Andric   llvm::Value *element = Builder.CreateInBoundsGEP(
23946f8fc217SDimitry Andric       llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2395180abc3dSDimitry Andric 
2396180abc3dSDimitry Andric   if (useEHCleanup)
239745b53394SDimitry Andric     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
239845b53394SDimitry Andric                                    destroyer);
2399180abc3dSDimitry Andric 
2400180abc3dSDimitry Andric   // Perform the actual destruction there.
24016f8fc217SDimitry Andric   destroyer(*this, Address(element, llvmElementType, elementAlign),
24026f8fc217SDimitry Andric             elementType);
2403180abc3dSDimitry Andric 
2404180abc3dSDimitry Andric   if (useEHCleanup)
2405180abc3dSDimitry Andric     PopCleanupBlock();
2406180abc3dSDimitry Andric 
2407180abc3dSDimitry Andric   // Check whether we've reached the end.
2408180abc3dSDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2409180abc3dSDimitry Andric   Builder.CreateCondBr(done, doneBB, bodyBB);
2410180abc3dSDimitry Andric   elementPast->addIncoming(element, Builder.GetInsertBlock());
2411180abc3dSDimitry Andric 
2412180abc3dSDimitry Andric   // Done.
2413180abc3dSDimitry Andric   EmitBlock(doneBB);
2414180abc3dSDimitry Andric }
2415180abc3dSDimitry Andric 
2416180abc3dSDimitry Andric /// Perform partial array destruction as if in an EH cleanup.  Unlike
2417180abc3dSDimitry Andric /// emitArrayDestroy, the element type here may still be an array type.
emitPartialArrayDestroy(CodeGenFunction & CGF,llvm::Value * begin,llvm::Value * end,QualType type,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)2418180abc3dSDimitry Andric static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2419180abc3dSDimitry Andric                                     llvm::Value *begin, llvm::Value *end,
242045b53394SDimitry Andric                                     QualType type, CharUnits elementAlign,
2421dbe13110SDimitry Andric                                     CodeGenFunction::Destroyer *destroyer) {
2422145449b1SDimitry Andric   llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2423145449b1SDimitry Andric 
2424180abc3dSDimitry Andric   // If the element type is itself an array, drill down.
2425180abc3dSDimitry Andric   unsigned arrayDepth = 0;
2426180abc3dSDimitry Andric   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2427180abc3dSDimitry Andric     // VLAs don't require a GEP index to walk into.
2428180abc3dSDimitry Andric     if (!isa<VariableArrayType>(arrayType))
2429180abc3dSDimitry Andric       arrayDepth++;
2430180abc3dSDimitry Andric     type = arrayType->getElementType();
2431180abc3dSDimitry Andric   }
2432180abc3dSDimitry Andric 
2433180abc3dSDimitry Andric   if (arrayDepth) {
243445b53394SDimitry Andric     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2435180abc3dSDimitry Andric 
243645b53394SDimitry Andric     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2437344a3780SDimitry Andric     begin = CGF.Builder.CreateInBoundsGEP(
2438344a3780SDimitry Andric         elemTy, begin, gepIndices, "pad.arraybegin");
2439344a3780SDimitry Andric     end = CGF.Builder.CreateInBoundsGEP(
2440344a3780SDimitry Andric         elemTy, end, gepIndices, "pad.arrayend");
2441180abc3dSDimitry Andric   }
2442180abc3dSDimitry Andric 
2443180abc3dSDimitry Andric   // Destroy the array.  We don't ever need an EH cleanup because we
2444180abc3dSDimitry Andric   // assume that we're in an EH cleanup ourselves, so a throwing
2445180abc3dSDimitry Andric   // destructor causes an immediate terminate.
244645b53394SDimitry Andric   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2447180abc3dSDimitry Andric                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2448180abc3dSDimitry Andric }
2449180abc3dSDimitry Andric 
2450180abc3dSDimitry Andric namespace {
2451180abc3dSDimitry Andric   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2452180abc3dSDimitry Andric   /// array destroy where the end pointer is regularly determined and
2453180abc3dSDimitry Andric   /// does not need to be loaded from a local.
245445b53394SDimitry Andric   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2455180abc3dSDimitry Andric     llvm::Value *ArrayBegin;
2456180abc3dSDimitry Andric     llvm::Value *ArrayEnd;
2457180abc3dSDimitry Andric     QualType ElementType;
2458dbe13110SDimitry Andric     CodeGenFunction::Destroyer *Destroyer;
245945b53394SDimitry Andric     CharUnits ElementAlign;
2460180abc3dSDimitry Andric   public:
RegularPartialArrayDestroy(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)2461180abc3dSDimitry Andric     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
246245b53394SDimitry Andric                                QualType elementType, CharUnits elementAlign,
2463180abc3dSDimitry Andric                                CodeGenFunction::Destroyer *destroyer)
2464180abc3dSDimitry Andric       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
246545b53394SDimitry Andric         ElementType(elementType), Destroyer(destroyer),
246645b53394SDimitry Andric         ElementAlign(elementAlign) {}
2467180abc3dSDimitry Andric 
Emit(CodeGenFunction & CGF,Flags flags)24689f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
2469180abc3dSDimitry Andric       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
247045b53394SDimitry Andric                               ElementType, ElementAlign, Destroyer);
2471180abc3dSDimitry Andric     }
2472180abc3dSDimitry Andric   };
2473180abc3dSDimitry Andric 
2474180abc3dSDimitry Andric   /// IrregularPartialArrayDestroy - a cleanup which performs a
2475180abc3dSDimitry Andric   /// partial array destroy where the end pointer is irregularly
2476180abc3dSDimitry Andric   /// determined and must be loaded from a local.
247745b53394SDimitry Andric   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2478180abc3dSDimitry Andric     llvm::Value *ArrayBegin;
247945b53394SDimitry Andric     Address ArrayEndPointer;
2480180abc3dSDimitry Andric     QualType ElementType;
2481dbe13110SDimitry Andric     CodeGenFunction::Destroyer *Destroyer;
248245b53394SDimitry Andric     CharUnits ElementAlign;
2483180abc3dSDimitry Andric   public:
IrregularPartialArrayDestroy(llvm::Value * arrayBegin,Address arrayEndPointer,QualType elementType,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)2484180abc3dSDimitry Andric     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
248545b53394SDimitry Andric                                  Address arrayEndPointer,
2486180abc3dSDimitry Andric                                  QualType elementType,
248745b53394SDimitry Andric                                  CharUnits elementAlign,
2488180abc3dSDimitry Andric                                  CodeGenFunction::Destroyer *destroyer)
2489180abc3dSDimitry Andric       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
249045b53394SDimitry Andric         ElementType(elementType), Destroyer(destroyer),
249145b53394SDimitry Andric         ElementAlign(elementAlign) {}
2492180abc3dSDimitry Andric 
Emit(CodeGenFunction & CGF,Flags flags)24939f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
2494180abc3dSDimitry Andric       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2495180abc3dSDimitry Andric       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
249645b53394SDimitry Andric                               ElementType, ElementAlign, Destroyer);
2497180abc3dSDimitry Andric     }
2498180abc3dSDimitry Andric   };
24992b6b257fSDimitry Andric } // end anonymous namespace
2500180abc3dSDimitry Andric 
2501ac9a064cSDimitry Andric /// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to
2502ac9a064cSDimitry Andric /// destroy already-constructed elements of the given array.  The cleanup may be
2503ac9a064cSDimitry Andric /// popped with DeactivateCleanupBlock or PopCleanupBlock.
2504180abc3dSDimitry Andric ///
2505180abc3dSDimitry Andric /// \param elementType - the immediate element type of the array;
2506180abc3dSDimitry Andric ///   possibly still an array type
pushIrregularPartialArrayCleanup(llvm::Value * arrayBegin,Address arrayEndPointer,QualType elementType,CharUnits elementAlign,Destroyer * destroyer)2507180abc3dSDimitry Andric void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
250845b53394SDimitry Andric                                                        Address arrayEndPointer,
2509180abc3dSDimitry Andric                                                        QualType elementType,
251045b53394SDimitry Andric                                                        CharUnits elementAlign,
2511dbe13110SDimitry Andric                                                        Destroyer *destroyer) {
2512ac9a064cSDimitry Andric   pushFullExprCleanup<IrregularPartialArrayDestroy>(
2513ac9a064cSDimitry Andric       NormalAndEHCleanup, arrayBegin, arrayEndPointer, elementType,
2514ac9a064cSDimitry Andric       elementAlign, destroyer);
2515180abc3dSDimitry Andric }
2516180abc3dSDimitry Andric 
2517180abc3dSDimitry Andric /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2518180abc3dSDimitry Andric /// already-constructed elements of the given array.  The cleanup
2519180abc3dSDimitry Andric /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2520180abc3dSDimitry Andric ///
2521180abc3dSDimitry Andric /// \param elementType - the immediate element type of the array;
2522180abc3dSDimitry Andric ///   possibly still an array type
pushRegularPartialArrayCleanup(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,CharUnits elementAlign,Destroyer * destroyer)2523180abc3dSDimitry Andric void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2524180abc3dSDimitry Andric                                                      llvm::Value *arrayEnd,
2525180abc3dSDimitry Andric                                                      QualType elementType,
252645b53394SDimitry Andric                                                      CharUnits elementAlign,
2527dbe13110SDimitry Andric                                                      Destroyer *destroyer) {
2528180abc3dSDimitry Andric   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2529180abc3dSDimitry Andric                                                   arrayBegin, arrayEnd,
253045b53394SDimitry Andric                                                   elementType, elementAlign,
253145b53394SDimitry Andric                                                   destroyer);
2532180abc3dSDimitry Andric }
2533180abc3dSDimitry Andric 
2534809500fcSDimitry Andric /// Lazily declare the @llvm.lifetime.start intrinsic.
getLLVMLifetimeStartFn()253522989816SDimitry Andric llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
25367442d6faSDimitry Andric   if (LifetimeStartFn)
25377442d6faSDimitry Andric     return LifetimeStartFn;
2538809500fcSDimitry Andric   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2539583e75ccSDimitry Andric     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2540809500fcSDimitry Andric   return LifetimeStartFn;
2541809500fcSDimitry Andric }
2542809500fcSDimitry Andric 
2543809500fcSDimitry Andric /// Lazily declare the @llvm.lifetime.end intrinsic.
getLLVMLifetimeEndFn()254422989816SDimitry Andric llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
25457442d6faSDimitry Andric   if (LifetimeEndFn)
25467442d6faSDimitry Andric     return LifetimeEndFn;
2547809500fcSDimitry Andric   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2548583e75ccSDimitry Andric     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2549809500fcSDimitry Andric   return LifetimeEndFn;
2550809500fcSDimitry Andric }
2551809500fcSDimitry Andric 
2552180abc3dSDimitry Andric namespace {
2553180abc3dSDimitry Andric   /// A cleanup to perform a release of an object at the end of a
2554180abc3dSDimitry Andric   /// function.  This is used to balance out the incoming +1 of a
2555180abc3dSDimitry Andric   /// ns_consumed argument when we can't reasonably do that just by
2556180abc3dSDimitry Andric   /// not doing the initial retain for a __block argument.
255745b53394SDimitry Andric   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
ConsumeARCParameter__anon7fada2950511::ConsumeARCParameter2558809500fcSDimitry Andric     ConsumeARCParameter(llvm::Value *param,
2559809500fcSDimitry Andric                         ARCPreciseLifetime_t precise)
2560809500fcSDimitry Andric       : Param(param), Precise(precise) {}
2561180abc3dSDimitry Andric 
2562180abc3dSDimitry Andric     llvm::Value *Param;
2563809500fcSDimitry Andric     ARCPreciseLifetime_t Precise;
2564180abc3dSDimitry Andric 
Emit__anon7fada2950511::ConsumeARCParameter25659f4dbff6SDimitry Andric     void Emit(CodeGenFunction &CGF, Flags flags) override {
2566809500fcSDimitry Andric       CGF.EmitARCRelease(Param, Precise);
2567180abc3dSDimitry Andric     }
2568180abc3dSDimitry Andric   };
25692b6b257fSDimitry Andric } // end anonymous namespace
2570180abc3dSDimitry Andric 
2571ec2b103cSEd Schouten /// Emit an alloca (or GlobalValue depending on target)
2572ec2b103cSEd Schouten /// for the specified parameter and set up LocalDeclMap.
EmitParmDecl(const VarDecl & D,ParamValue Arg,unsigned ArgNo)257345b53394SDimitry Andric void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
257445b53394SDimitry Andric                                    unsigned ArgNo) {
2575145449b1SDimitry Andric   bool NoDebugInfo = false;
2576ec2b103cSEd Schouten   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2577ec2b103cSEd Schouten   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2578ec2b103cSEd Schouten          "Invalid argument to EmitParmDecl");
2579c3b054d2SDimitry Andric 
25807fa27ce4SDimitry Andric   // Set the name of the parameter's initial value to make IR easier to
25817fa27ce4SDimitry Andric   // read. Don't modify the names of globals.
25827fa27ce4SDimitry Andric   if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))
258345b53394SDimitry Andric     Arg.getAnyValue()->setName(D.getName());
2584c3b054d2SDimitry Andric 
2585809500fcSDimitry Andric   QualType Ty = D.getType();
2586809500fcSDimitry Andric 
2587c3b054d2SDimitry Andric   // Use better IR generation for certain implicit parameters.
258845b53394SDimitry Andric   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2589c3b054d2SDimitry Andric     // The only implicit argument a block has is its literal.
259048675466SDimitry Andric     // This may be passed as an inalloca'ed value on Windows x86.
2591c3b054d2SDimitry Andric     if (BlockInfo) {
259248675466SDimitry Andric       llvm::Value *V = Arg.isIndirect()
259348675466SDimitry Andric                            ? Builder.CreateLoad(Arg.getIndirectAddress())
259448675466SDimitry Andric                            : Arg.getDirectValue();
259548675466SDimitry Andric       setBlockContextParameter(IPD, ArgNo, V);
2596c3b054d2SDimitry Andric       return;
2597c3b054d2SDimitry Andric     }
2598145449b1SDimitry Andric     // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2599145449b1SDimitry Andric     // debug info of TLS variables.
2600145449b1SDimitry Andric     NoDebugInfo =
2601b1c73532SDimitry Andric         (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2602c3b054d2SDimitry Andric   }
2603c3b054d2SDimitry Andric 
260445b53394SDimitry Andric   Address DeclPtr = Address::invalid();
2605ac9a064cSDimitry Andric   RawAddress AllocaPtr = Address::invalid();
26069f4dbff6SDimitry Andric   bool DoStore = false;
26079f4dbff6SDimitry Andric   bool IsScalar = hasScalarEvaluationKind(Ty);
26087fa27ce4SDimitry Andric   bool UseIndirectDebugAddress = false;
26097fa27ce4SDimitry Andric 
26109f4dbff6SDimitry Andric   // If we already have a pointer to the argument, reuse the input pointer.
261145b53394SDimitry Andric   if (Arg.isIndirect()) {
2612145449b1SDimitry Andric     DeclPtr = Arg.getIndirectAddress();
26137fa27ce4SDimitry Andric     DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
261448675466SDimitry Andric     // Indirect argument is in alloca address space, which may be different
261548675466SDimitry Andric     // from the default address space.
261648675466SDimitry Andric     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2617ac9a064cSDimitry Andric     auto *V = DeclPtr.emitRawPointer(*this);
2618ac9a064cSDimitry Andric     AllocaPtr = RawAddress(V, DeclPtr.getElementType(), DeclPtr.getAlignment());
26197fa27ce4SDimitry Andric 
26207fa27ce4SDimitry Andric     // For truly ABI indirect arguments -- those that are not `byval` -- store
26217fa27ce4SDimitry Andric     // the address of the argument on the stack to preserve debug information.
26227fa27ce4SDimitry Andric     ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
26237fa27ce4SDimitry Andric     if (ArgInfo.isIndirect())
26247fa27ce4SDimitry Andric       UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
26257fa27ce4SDimitry Andric     if (UseIndirectDebugAddress) {
26267fa27ce4SDimitry Andric       auto PtrTy = getContext().getPointerType(Ty);
26277fa27ce4SDimitry Andric       AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
26287fa27ce4SDimitry Andric                                 D.getName() + ".indirect_addr");
26297fa27ce4SDimitry Andric       EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
26307fa27ce4SDimitry Andric     }
26317fa27ce4SDimitry Andric 
263248675466SDimitry Andric     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
263348675466SDimitry Andric     auto DestLangAS =
263448675466SDimitry Andric         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
263548675466SDimitry Andric     if (SrcLangAS != DestLangAS) {
263648675466SDimitry Andric       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
263748675466SDimitry Andric              CGM.getDataLayout().getAllocaAddrSpace());
263848675466SDimitry Andric       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
26397fa27ce4SDimitry Andric       auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
26407fa27ce4SDimitry Andric       DeclPtr =
26417fa27ce4SDimitry Andric           DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
26427fa27ce4SDimitry Andric                                   *this, V, SrcLangAS, DestLangAS, T, true),
26437fa27ce4SDimitry Andric                               DeclPtr.isKnownNonNull());
264448675466SDimitry Andric     }
264545b53394SDimitry Andric 
2646bfef3995SDimitry Andric     // Push a destructor cleanup for this parameter if the ABI requires it.
264706d4ba38SDimitry Andric     // Don't push a cleanup in a thunk for a method that will also emit a
264806d4ba38SDimitry Andric     // cleanup.
2649344a3780SDimitry Andric     if (Ty->isRecordType() && !CurFuncIsThunk &&
2650519fc96cSDimitry Andric         Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2651519fc96cSDimitry Andric       if (QualType::DestructionKind DtorKind =
2652519fc96cSDimitry Andric               D.needsDestruction(getContext())) {
265348675466SDimitry Andric         assert((DtorKind == QualType::DK_cxx_destructor ||
265448675466SDimitry Andric                 DtorKind == QualType::DK_nontrivial_c_struct) &&
265548675466SDimitry Andric                "unexpected destructor type");
265648675466SDimitry Andric         pushDestroy(DtorKind, DeclPtr, Ty);
265748675466SDimitry Andric         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
265848675466SDimitry Andric             EHStack.stable_begin();
2659bfef3995SDimitry Andric       }
266048675466SDimitry Andric     }
266148675466SDimitry Andric   } else {
266248675466SDimitry Andric     // Check if the parameter address is controlled by OpenMP runtime.
266348675466SDimitry Andric     Address OpenMPLocalAddr =
266448675466SDimitry Andric         getLangOpts().OpenMP
266548675466SDimitry Andric             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
266648675466SDimitry Andric             : Address::invalid();
266748675466SDimitry Andric     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
266848675466SDimitry Andric       DeclPtr = OpenMPLocalAddr;
2669c0981da4SDimitry Andric       AllocaPtr = DeclPtr;
2670ec2b103cSEd Schouten     } else {
2671ecb7e5c8SRoman Divacky       // Otherwise, create a temporary to hold the value.
267245b53394SDimitry Andric       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2673c0981da4SDimitry Andric                               D.getName() + ".addr", &AllocaPtr);
267448675466SDimitry Andric     }
26759f4dbff6SDimitry Andric     DoStore = true;
26769f4dbff6SDimitry Andric   }
2677ec2b103cSEd Schouten 
267845b53394SDimitry Andric   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
267945b53394SDimitry Andric 
268045b53394SDimitry Andric   LValue lv = MakeAddrLValue(DeclPtr, Ty);
26819f4dbff6SDimitry Andric   if (IsScalar) {
26829f4dbff6SDimitry Andric     Qualifiers qs = Ty.getQualifiers();
2683180abc3dSDimitry Andric     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2684180abc3dSDimitry Andric       // We honor __attribute__((ns_consumed)) for types with lifetime.
2685180abc3dSDimitry Andric       // For __strong, it's handled by just skipping the initial retain;
2686180abc3dSDimitry Andric       // otherwise we have to balance out the initial +1 with an extra
2687180abc3dSDimitry Andric       // cleanup to do the release at the end of the function.
2688180abc3dSDimitry Andric       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2689180abc3dSDimitry Andric 
2690676fbe81SDimitry Andric       // If a parameter is pseudo-strong then we can omit the implicit retain.
2691180abc3dSDimitry Andric       if (D.isARCPseudoStrong()) {
2692676fbe81SDimitry Andric         assert(lt == Qualifiers::OCL_Strong &&
2693676fbe81SDimitry Andric                "pseudo-strong variable isn't strong?");
2694676fbe81SDimitry Andric         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2695180abc3dSDimitry Andric         lt = Qualifiers::OCL_ExplicitNone;
2696180abc3dSDimitry Andric       }
2697180abc3dSDimitry Andric 
2698cf1b4019SDimitry Andric       // Load objects passed indirectly.
2699cf1b4019SDimitry Andric       if (Arg.isIndirect() && !ArgVal)
2700cf1b4019SDimitry Andric         ArgVal = Builder.CreateLoad(DeclPtr);
2701cf1b4019SDimitry Andric 
2702180abc3dSDimitry Andric       if (lt == Qualifiers::OCL_Strong) {
2703809500fcSDimitry Andric         if (!isConsumed) {
2704809500fcSDimitry Andric           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2705809500fcSDimitry Andric             // use objc_storeStrong(&dest, value) for retaining the
2706809500fcSDimitry Andric             // object. But first, store a null into 'dest' because
2707809500fcSDimitry Andric             // objc_storeStrong attempts to release its old value.
2708809500fcSDimitry Andric             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2709809500fcSDimitry Andric             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2710ac9a064cSDimitry Andric             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
27119f4dbff6SDimitry Andric             DoStore = false;
2712809500fcSDimitry Andric           }
2713809500fcSDimitry Andric           else
2714180abc3dSDimitry Andric           // Don't use objc_retainBlock for block pointers, because we
2715180abc3dSDimitry Andric           // don't want to Block_copy something just because we got it
2716180abc3dSDimitry Andric           // as a parameter.
271745b53394SDimitry Andric             ArgVal = EmitARCRetainNonBlock(ArgVal);
2718809500fcSDimitry Andric         }
2719180abc3dSDimitry Andric       } else {
2720180abc3dSDimitry Andric         // Push the cleanup for a consumed parameter.
2721809500fcSDimitry Andric         if (isConsumed) {
2722809500fcSDimitry Andric           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2723809500fcSDimitry Andric                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
272445b53394SDimitry Andric           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2725809500fcSDimitry Andric                                                    precise);
2726809500fcSDimitry Andric         }
2727180abc3dSDimitry Andric 
2728180abc3dSDimitry Andric         if (lt == Qualifiers::OCL_Weak) {
272945b53394SDimitry Andric           EmitARCInitWeak(DeclPtr, ArgVal);
27309f4dbff6SDimitry Andric           DoStore = false; // The weak init is a store, no need to do two.
2731180abc3dSDimitry Andric         }
2732180abc3dSDimitry Andric       }
2733180abc3dSDimitry Andric 
2734180abc3dSDimitry Andric       // Enter the cleanup scope.
2735180abc3dSDimitry Andric       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2736180abc3dSDimitry Andric     }
2737180abc3dSDimitry Andric   }
2738ec2b103cSEd Schouten 
27399f4dbff6SDimitry Andric   // Store the initial value into the alloca.
27409f4dbff6SDimitry Andric   if (DoStore)
274145b53394SDimitry Andric     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
27429f4dbff6SDimitry Andric 
274345b53394SDimitry Andric   setAddrOfLocalVar(&D, DeclPtr);
2744ec2b103cSEd Schouten 
2745519fc96cSDimitry Andric   // Emit debug info for param declarations in non-thunk functions.
274656d91b49SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
2747145449b1SDimitry Andric     if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&
2748145449b1SDimitry Andric         !NoDebugInfo) {
2749344a3780SDimitry Andric       llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
27507fa27ce4SDimitry Andric           &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2751344a3780SDimitry Andric       if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2752344a3780SDimitry Andric         DI->getParamDbgMappings().insert({Var, DILocalVar});
275356d91b49SDimitry Andric     }
275456d91b49SDimitry Andric   }
275536981b17SDimitry Andric 
275636981b17SDimitry Andric   if (D.hasAttr<AnnotateAttr>())
2757ac9a064cSDimitry Andric     EmitVarAnnotations(&D, DeclPtr.emitRawPointer(*this));
27587442d6faSDimitry Andric 
27597442d6faSDimitry Andric   // We can only check return value nullability if all arguments to the
27607442d6faSDimitry Andric   // function satisfy their nullability preconditions. This makes it necessary
27617442d6faSDimitry Andric   // to emit null checks for args in the function body itself.
27627442d6faSDimitry Andric   if (requiresReturnValueNullabilityCheck()) {
2763e3b55780SDimitry Andric     auto Nullability = Ty->getNullability();
27647442d6faSDimitry Andric     if (Nullability && *Nullability == NullabilityKind::NonNull) {
27657442d6faSDimitry Andric       SanitizerScope SanScope(this);
27667442d6faSDimitry Andric       RetValNullabilityPrecondition =
27677442d6faSDimitry Andric           Builder.CreateAnd(RetValNullabilityPrecondition,
27687442d6faSDimitry Andric                             Builder.CreateIsNotNull(Arg.getAnyValue()));
27697442d6faSDimitry Andric     }
27707442d6faSDimitry Andric   }
2771ec2b103cSEd Schouten }
27722b6b257fSDimitry Andric 
EmitOMPDeclareReduction(const OMPDeclareReductionDecl * D,CodeGenFunction * CGF)27732b6b257fSDimitry Andric void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
27742b6b257fSDimitry Andric                                             CodeGenFunction *CGF) {
27752b6b257fSDimitry Andric   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
27762b6b257fSDimitry Andric     return;
27772b6b257fSDimitry Andric   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
27782b6b257fSDimitry Andric }
2779676fbe81SDimitry Andric 
EmitOMPDeclareMapper(const OMPDeclareMapperDecl * D,CodeGenFunction * CGF)278022989816SDimitry Andric void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
278122989816SDimitry Andric                                          CodeGenFunction *CGF) {
2782519fc96cSDimitry Andric   if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2783519fc96cSDimitry Andric       (!LangOpts.EmitAllDecls && !D->isUsed()))
278422989816SDimitry Andric     return;
2785519fc96cSDimitry Andric   getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
278622989816SDimitry Andric }
278722989816SDimitry Andric 
EmitOMPRequiresDecl(const OMPRequiresDecl * D)2788676fbe81SDimitry Andric void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2789cfca06d7SDimitry Andric   getOpenMPRuntime().processRequiresDirective(D);
2790676fbe81SDimitry Andric }
2791344a3780SDimitry Andric 
EmitOMPAllocateDecl(const OMPAllocateDecl * D)2792344a3780SDimitry Andric void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2793344a3780SDimitry Andric   for (const Expr *E : D->varlists()) {
2794344a3780SDimitry Andric     const auto *DE = cast<DeclRefExpr>(E);
2795344a3780SDimitry Andric     const auto *VD = cast<VarDecl>(DE->getDecl());
2796344a3780SDimitry Andric 
2797344a3780SDimitry Andric     // Skip all but globals.
2798344a3780SDimitry Andric     if (!VD->hasGlobalStorage())
2799344a3780SDimitry Andric       continue;
2800344a3780SDimitry Andric 
2801344a3780SDimitry Andric     // Check if the global has been materialized yet or not. If not, we are done
2802344a3780SDimitry Andric     // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2803344a3780SDimitry Andric     // we already emitted the global we might have done so before the
2804344a3780SDimitry Andric     // OMPAllocateDeclAttr was attached, leading to the wrong address space
2805344a3780SDimitry Andric     // (potentially). While not pretty, common practise is to remove the old IR
2806344a3780SDimitry Andric     // global and generate a new one, so we do that here too. Uses are replaced
2807344a3780SDimitry Andric     // properly.
2808344a3780SDimitry Andric     StringRef MangledName = getMangledName(VD);
2809344a3780SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2810344a3780SDimitry Andric     if (!Entry)
2811344a3780SDimitry Andric       continue;
2812344a3780SDimitry Andric 
2813344a3780SDimitry Andric     // We can also keep the existing global if the address space is what we
2814344a3780SDimitry Andric     // expect it to be, if not, it is replaced.
2815344a3780SDimitry Andric     QualType ASTTy = VD->getType();
2816344a3780SDimitry Andric     clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2817344a3780SDimitry Andric     auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2818344a3780SDimitry Andric     if (Entry->getType()->getAddressSpace() == TargetAS)
2819344a3780SDimitry Andric       continue;
2820344a3780SDimitry Andric 
2821344a3780SDimitry Andric     // Make a new global with the correct type / address space.
2822344a3780SDimitry Andric     llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2823344a3780SDimitry Andric     llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2824344a3780SDimitry Andric 
2825344a3780SDimitry Andric     // Replace all uses of the old global with a cast. Since we mutate the type
2826344a3780SDimitry Andric     // in place we neeed an intermediate that takes the spot of the old entry
2827344a3780SDimitry Andric     // until we can create the cast.
2828344a3780SDimitry Andric     llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2829344a3780SDimitry Andric         getModule(), Entry->getValueType(), false,
2830344a3780SDimitry Andric         llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2831344a3780SDimitry Andric         llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2832344a3780SDimitry Andric     Entry->replaceAllUsesWith(DummyGV);
2833344a3780SDimitry Andric 
2834344a3780SDimitry Andric     Entry->mutateType(PTy);
2835344a3780SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
2836344a3780SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2837344a3780SDimitry Andric             Entry, DummyGV->getType());
2838344a3780SDimitry Andric 
2839344a3780SDimitry Andric     // Now we have a casted version of the changed global, the dummy can be
2840344a3780SDimitry Andric     // replaced and deleted.
2841344a3780SDimitry Andric     DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2842344a3780SDimitry Andric     DummyGV->eraseFromParent();
2843344a3780SDimitry Andric   }
2844344a3780SDimitry Andric }
2845145449b1SDimitry Andric 
2846e3b55780SDimitry Andric std::optional<CharUnits>
getOMPAllocateAlignment(const VarDecl * VD)2847145449b1SDimitry Andric CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {
2848145449b1SDimitry Andric   if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2849145449b1SDimitry Andric     if (Expr *Alignment = AA->getAlignment()) {
2850145449b1SDimitry Andric       unsigned UserAlign =
2851145449b1SDimitry Andric           Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2852145449b1SDimitry Andric       CharUnits NaturalAlign =
2853145449b1SDimitry Andric           getNaturalTypeAlignment(VD->getType().getNonReferenceType());
2854145449b1SDimitry Andric 
2855145449b1SDimitry Andric       // OpenMP5.1 pg 185 lines 7-10
2856145449b1SDimitry Andric       //   Each item in the align modifier list must be aligned to the maximum
2857145449b1SDimitry Andric       //   of the specified alignment and the type's natural alignment.
2858145449b1SDimitry Andric       return CharUnits::fromQuantity(
2859145449b1SDimitry Andric           std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2860145449b1SDimitry Andric     }
2861145449b1SDimitry Andric   }
2862e3b55780SDimitry Andric   return std::nullopt;
2863145449b1SDimitry Andric }
2864