Path: blob/main/contrib/llvm-project/clang/lib/CodeGen/CGDecl.cpp
35233 views
//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This contains code to emit Decl nodes as LLVM code.9//10//===----------------------------------------------------------------------===//1112#include "CGBlocks.h"13#include "CGCXXABI.h"14#include "CGCleanup.h"15#include "CGDebugInfo.h"16#include "CGOpenCLRuntime.h"17#include "CGOpenMPRuntime.h"18#include "CodeGenFunction.h"19#include "CodeGenModule.h"20#include "ConstantEmitter.h"21#include "EHScopeStack.h"22#include "PatternInit.h"23#include "TargetInfo.h"24#include "clang/AST/ASTContext.h"25#include "clang/AST/Attr.h"26#include "clang/AST/CharUnits.h"27#include "clang/AST/Decl.h"28#include "clang/AST/DeclObjC.h"29#include "clang/AST/DeclOpenMP.h"30#include "clang/Basic/CodeGenOptions.h"31#include "clang/Basic/SourceManager.h"32#include "clang/Basic/TargetInfo.h"33#include "clang/CodeGen/CGFunctionInfo.h"34#include "clang/Sema/Sema.h"35#include "llvm/Analysis/ConstantFolding.h"36#include "llvm/Analysis/ValueTracking.h"37#include "llvm/IR/DataLayout.h"38#include "llvm/IR/GlobalVariable.h"39#include "llvm/IR/Instructions.h"40#include "llvm/IR/Intrinsics.h"41#include "llvm/IR/Type.h"42#include <optional>4344using namespace clang;45using namespace CodeGen;4647static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,48"Clang max alignment greater than what LLVM supports?");4950void CodeGenFunction::EmitDecl(const Decl &D) {51switch (D.getKind()) {52case Decl::BuiltinTemplate:53case Decl::TranslationUnit:54case Decl::ExternCContext:55case Decl::Namespace:56case Decl::UnresolvedUsingTypename:57case Decl::ClassTemplateSpecialization:58case Decl::ClassTemplatePartialSpecialization:59case Decl::VarTemplateSpecialization:60case Decl::VarTemplatePartialSpecialization:61case Decl::TemplateTypeParm:62case Decl::UnresolvedUsingValue:63case Decl::NonTypeTemplateParm:64case Decl::CXXDeductionGuide:65case Decl::CXXMethod:66case Decl::CXXConstructor:67case Decl::CXXDestructor:68case Decl::CXXConversion:69case Decl::Field:70case Decl::MSProperty:71case Decl::IndirectField:72case Decl::ObjCIvar:73case Decl::ObjCAtDefsField:74case Decl::ParmVar:75case Decl::ImplicitParam:76case Decl::ClassTemplate:77case Decl::VarTemplate:78case Decl::FunctionTemplate:79case Decl::TypeAliasTemplate:80case Decl::TemplateTemplateParm:81case Decl::ObjCMethod:82case Decl::ObjCCategory:83case Decl::ObjCProtocol:84case Decl::ObjCInterface:85case Decl::ObjCCategoryImpl:86case Decl::ObjCImplementation:87case Decl::ObjCProperty:88case Decl::ObjCCompatibleAlias:89case Decl::PragmaComment:90case Decl::PragmaDetectMismatch:91case Decl::AccessSpec:92case Decl::LinkageSpec:93case Decl::Export:94case Decl::ObjCPropertyImpl:95case Decl::FileScopeAsm:96case Decl::TopLevelStmt:97case Decl::Friend:98case Decl::FriendTemplate:99case Decl::Block:100case Decl::Captured:101case Decl::UsingShadow:102case Decl::ConstructorUsingShadow:103case Decl::ObjCTypeParam:104case Decl::Binding:105case Decl::UnresolvedUsingIfExists:106case Decl::HLSLBuffer:107llvm_unreachable("Declaration should not be in declstmts!");108case Decl::Record: // struct/union/class X;109case Decl::CXXRecord: // struct/union/class X; [C++]110if (CGDebugInfo *DI = getDebugInfo())111if (cast<RecordDecl>(D).getDefinition())112DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));113return;114case Decl::Enum: // enum X;115if (CGDebugInfo *DI = getDebugInfo())116if (cast<EnumDecl>(D).getDefinition())117DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));118return;119case Decl::Function: // void X();120case Decl::EnumConstant: // enum ? { X = ? }121case Decl::StaticAssert: // static_assert(X, ""); [C++0x]122case Decl::Label: // __label__ x;123case Decl::Import:124case Decl::MSGuid: // __declspec(uuid("..."))125case Decl::UnnamedGlobalConstant:126case Decl::TemplateParamObject:127case Decl::OMPThreadPrivate:128case Decl::OMPAllocate:129case Decl::OMPCapturedExpr:130case Decl::OMPRequires:131case Decl::Empty:132case Decl::Concept:133case Decl::ImplicitConceptSpecialization:134case Decl::LifetimeExtendedTemporary:135case Decl::RequiresExprBody:136// None of these decls require codegen support.137return;138139case Decl::NamespaceAlias:140if (CGDebugInfo *DI = getDebugInfo())141DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));142return;143case Decl::Using: // using X; [C++]144if (CGDebugInfo *DI = getDebugInfo())145DI->EmitUsingDecl(cast<UsingDecl>(D));146return;147case Decl::UsingEnum: // using enum X; [C++]148if (CGDebugInfo *DI = getDebugInfo())149DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));150return;151case Decl::UsingPack:152for (auto *Using : cast<UsingPackDecl>(D).expansions())153EmitDecl(*Using);154return;155case Decl::UsingDirective: // using namespace X; [C++]156if (CGDebugInfo *DI = getDebugInfo())157DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));158return;159case Decl::Var:160case Decl::Decomposition: {161const VarDecl &VD = cast<VarDecl>(D);162assert(VD.isLocalVarDecl() &&163"Should not see file-scope variables inside a function!");164EmitVarDecl(VD);165if (auto *DD = dyn_cast<DecompositionDecl>(&VD))166for (auto *B : DD->bindings())167if (auto *HD = B->getHoldingVar())168EmitVarDecl(*HD);169return;170}171172case Decl::OMPDeclareReduction:173return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);174175case Decl::OMPDeclareMapper:176return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);177178case Decl::Typedef: // typedef int X;179case Decl::TypeAlias: { // using X = int; [C++0x]180QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();181if (CGDebugInfo *DI = getDebugInfo())182DI->EmitAndRetainType(Ty);183if (Ty->isVariablyModifiedType())184EmitVariablyModifiedType(Ty);185return;186}187}188}189190/// EmitVarDecl - This method handles emission of any variable declaration191/// inside a function, including static vars etc.192void CodeGenFunction::EmitVarDecl(const VarDecl &D) {193if (D.hasExternalStorage())194// Don't emit it now, allow it to be emitted lazily on its first use.195return;196197// Some function-scope variable does not have static storage but still198// needs to be emitted like a static variable, e.g. a function-scope199// variable in constant address space in OpenCL.200if (D.getStorageDuration() != SD_Automatic) {201// Static sampler variables translated to function calls.202if (D.getType()->isSamplerT())203return;204205llvm::GlobalValue::LinkageTypes Linkage =206CGM.getLLVMLinkageVarDefinition(&D);207208// FIXME: We need to force the emission/use of a guard variable for209// some variables even if we can constant-evaluate them because210// we can't guarantee every translation unit will constant-evaluate them.211212return EmitStaticVarDecl(D, Linkage);213}214215if (D.getType().getAddressSpace() == LangAS::opencl_local)216return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);217218assert(D.hasLocalStorage());219return EmitAutoVarDecl(D);220}221222static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {223if (CGM.getLangOpts().CPlusPlus)224return CGM.getMangledName(&D).str();225226// If this isn't C++, we don't need a mangled name, just a pretty one.227assert(!D.isExternallyVisible() && "name shouldn't matter");228std::string ContextName;229const DeclContext *DC = D.getDeclContext();230if (auto *CD = dyn_cast<CapturedDecl>(DC))231DC = cast<DeclContext>(CD->getNonClosureContext());232if (const auto *FD = dyn_cast<FunctionDecl>(DC))233ContextName = std::string(CGM.getMangledName(FD));234else if (const auto *BD = dyn_cast<BlockDecl>(DC))235ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));236else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))237ContextName = OMD->getSelector().getAsString();238else239llvm_unreachable("Unknown context for static var decl");240241ContextName += "." + D.getNameAsString();242return ContextName;243}244245llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(246const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {247// In general, we don't always emit static var decls once before we reference248// them. It is possible to reference them before emitting the function that249// contains them, and it is possible to emit the containing function multiple250// times.251if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])252return ExistingGV;253254QualType Ty = D.getType();255assert(Ty->isConstantSizeType() && "VLAs can't be static");256257// Use the label if the variable is renamed with the asm-label extension.258std::string Name;259if (D.hasAttr<AsmLabelAttr>())260Name = std::string(getMangledName(&D));261else262Name = getStaticDeclName(*this, D);263264llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);265LangAS AS = GetGlobalVarAddressSpace(&D);266unsigned TargetAS = getContext().getTargetAddressSpace(AS);267268// OpenCL variables in local address space and CUDA shared269// variables cannot have an initializer.270llvm::Constant *Init = nullptr;271if (Ty.getAddressSpace() == LangAS::opencl_local ||272D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())273Init = llvm::UndefValue::get(LTy);274else275Init = EmitNullConstant(Ty);276277llvm::GlobalVariable *GV = new llvm::GlobalVariable(278getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,279nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);280GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());281282if (supportsCOMDAT() && GV->isWeakForLinker())283GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));284285if (D.getTLSKind())286setTLSMode(GV, D);287288setGVProperties(GV, &D);289getTargetCodeGenInfo().setTargetAttributes(cast<Decl>(&D), GV, *this);290291// Make sure the result is of the correct type.292LangAS ExpectedAS = Ty.getAddressSpace();293llvm::Constant *Addr = GV;294if (AS != ExpectedAS) {295Addr = getTargetCodeGenInfo().performAddrSpaceCast(296*this, GV, AS, ExpectedAS,297llvm::PointerType::get(getLLVMContext(),298getContext().getTargetAddressSpace(ExpectedAS)));299}300301setStaticLocalDeclAddress(&D, Addr);302303// Ensure that the static local gets initialized by making sure the parent304// function gets emitted eventually.305const Decl *DC = cast<Decl>(D.getDeclContext());306307// We can't name blocks or captured statements directly, so try to emit their308// parents.309if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {310DC = DC->getNonClosureContext();311// FIXME: Ensure that global blocks get emitted.312if (!DC)313return Addr;314}315316GlobalDecl GD;317if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))318GD = GlobalDecl(CD, Ctor_Base);319else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))320GD = GlobalDecl(DD, Dtor_Base);321else if (const auto *FD = dyn_cast<FunctionDecl>(DC))322GD = GlobalDecl(FD);323else {324// Don't do anything for Obj-C method decls or global closures. We should325// never defer them.326assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");327}328if (GD.getDecl()) {329// Disable emission of the parent function for the OpenMP device codegen.330CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);331(void)GetAddrOfGlobal(GD);332}333334return Addr;335}336337/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the338/// global variable that has already been created for it. If the initializer339/// has a different type than GV does, this may free GV and return a different340/// one. Otherwise it just returns GV.341llvm::GlobalVariable *342CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,343llvm::GlobalVariable *GV) {344ConstantEmitter emitter(*this);345llvm::Constant *Init = emitter.tryEmitForInitializer(D);346347// If constant emission failed, then this should be a C++ static348// initializer.349if (!Init) {350if (!getLangOpts().CPlusPlus)351CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");352else if (D.hasFlexibleArrayInit(getContext()))353CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");354else if (HaveInsertPoint()) {355// Since we have a static initializer, this global variable can't356// be constant.357GV->setConstant(false);358359EmitCXXGuardedInit(D, GV, /*PerformInit*/true);360}361return GV;362}363364#ifndef NDEBUG365CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +366D.getFlexibleArrayInitChars(getContext());367CharUnits CstSize = CharUnits::fromQuantity(368CGM.getDataLayout().getTypeAllocSize(Init->getType()));369assert(VarSize == CstSize && "Emitted constant has unexpected size");370#endif371372// The initializer may differ in type from the global. Rewrite373// the global to match the initializer. (We have to do this374// because some types, like unions, can't be completely represented375// in the LLVM type system.)376if (GV->getValueType() != Init->getType()) {377llvm::GlobalVariable *OldGV = GV;378379GV = new llvm::GlobalVariable(380CGM.getModule(), Init->getType(), OldGV->isConstant(),381OldGV->getLinkage(), Init, "",382/*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),383OldGV->getType()->getPointerAddressSpace());384GV->setVisibility(OldGV->getVisibility());385GV->setDSOLocal(OldGV->isDSOLocal());386GV->setComdat(OldGV->getComdat());387388// Steal the name of the old global389GV->takeName(OldGV);390391// Replace all uses of the old global with the new global392OldGV->replaceAllUsesWith(GV);393394// Erase the old global, since it is no longer used.395OldGV->eraseFromParent();396}397398bool NeedsDtor =399D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;400401GV->setConstant(402D.getType().isConstantStorage(getContext(), true, !NeedsDtor));403GV->setInitializer(Init);404405emitter.finalize(GV);406407if (NeedsDtor && HaveInsertPoint()) {408// We have a constant initializer, but a nontrivial destructor. We still409// need to perform a guarded "initialization" in order to register the410// destructor.411EmitCXXGuardedInit(D, GV, /*PerformInit*/false);412}413414return GV;415}416417void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,418llvm::GlobalValue::LinkageTypes Linkage) {419// Check to see if we already have a global variable for this420// declaration. This can happen when double-emitting function421// bodies, e.g. with complete and base constructors.422llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);423CharUnits alignment = getContext().getDeclAlign(&D);424425// Store into LocalDeclMap before generating initializer to handle426// circular references.427llvm::Type *elemTy = ConvertTypeForMem(D.getType());428setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));429430// We can't have a VLA here, but we can have a pointer to a VLA,431// even though that doesn't really make any sense.432// Make sure to evaluate VLA bounds now so that we have them for later.433if (D.getType()->isVariablyModifiedType())434EmitVariablyModifiedType(D.getType());435436// Save the type in case adding the initializer forces a type change.437llvm::Type *expectedType = addr->getType();438439llvm::GlobalVariable *var =440cast<llvm::GlobalVariable>(addr->stripPointerCasts());441442// CUDA's local and local static __shared__ variables should not443// have any non-empty initializers. This is ensured by Sema.444// Whatever initializer such variable may have when it gets here is445// a no-op and should not be emitted.446bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&447D.hasAttr<CUDASharedAttr>();448// If this value has an initializer, emit it.449if (D.getInit() && !isCudaSharedVar)450var = AddInitializerToStaticVarDecl(D, var);451452var->setAlignment(alignment.getAsAlign());453454if (D.hasAttr<AnnotateAttr>())455CGM.AddGlobalAnnotations(&D, var);456457if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())458var->addAttribute("bss-section", SA->getName());459if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())460var->addAttribute("data-section", SA->getName());461if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())462var->addAttribute("rodata-section", SA->getName());463if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())464var->addAttribute("relro-section", SA->getName());465466if (const SectionAttr *SA = D.getAttr<SectionAttr>())467var->setSection(SA->getName());468469if (D.hasAttr<RetainAttr>())470CGM.addUsedGlobal(var);471else if (D.hasAttr<UsedAttr>())472CGM.addUsedOrCompilerUsedGlobal(var);473474if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)475CGM.addUsedOrCompilerUsedGlobal(var);476477// We may have to cast the constant because of the initializer478// mismatch above.479//480// FIXME: It is really dangerous to store this in the map; if anyone481// RAUW's the GV uses of this constant will be invalid.482llvm::Constant *castedAddr =483llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);484LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);485CGM.setStaticLocalDeclAddress(&D, castedAddr);486487CGM.getSanitizerMetadata()->reportGlobal(var, D);488489// Emit global variable debug descriptor for static vars.490CGDebugInfo *DI = getDebugInfo();491if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {492DI->setLocation(D.getLocation());493DI->EmitGlobalVariable(var, &D);494}495}496497namespace {498struct DestroyObject final : EHScopeStack::Cleanup {499DestroyObject(Address addr, QualType type,500CodeGenFunction::Destroyer *destroyer,501bool useEHCleanupForArray)502: addr(addr), type(type), destroyer(destroyer),503useEHCleanupForArray(useEHCleanupForArray) {}504505Address addr;506QualType type;507CodeGenFunction::Destroyer *destroyer;508bool useEHCleanupForArray;509510void Emit(CodeGenFunction &CGF, Flags flags) override {511// Don't use an EH cleanup recursively from an EH cleanup.512bool useEHCleanupForArray =513flags.isForNormalCleanup() && this->useEHCleanupForArray;514515CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);516}517};518519template <class Derived>520struct DestroyNRVOVariable : EHScopeStack::Cleanup {521DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)522: NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}523524llvm::Value *NRVOFlag;525Address Loc;526QualType Ty;527528void Emit(CodeGenFunction &CGF, Flags flags) override {529// Along the exceptions path we always execute the dtor.530bool NRVO = flags.isForNormalCleanup() && NRVOFlag;531532llvm::BasicBlock *SkipDtorBB = nullptr;533if (NRVO) {534// If we exited via NRVO, we skip the destructor call.535llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");536SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");537llvm::Value *DidNRVO =538CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");539CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);540CGF.EmitBlock(RunDtorBB);541}542543static_cast<Derived *>(this)->emitDestructorCall(CGF);544545if (NRVO) CGF.EmitBlock(SkipDtorBB);546}547548virtual ~DestroyNRVOVariable() = default;549};550551struct DestroyNRVOVariableCXX final552: DestroyNRVOVariable<DestroyNRVOVariableCXX> {553DestroyNRVOVariableCXX(Address addr, QualType type,554const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)555: DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),556Dtor(Dtor) {}557558const CXXDestructorDecl *Dtor;559560void emitDestructorCall(CodeGenFunction &CGF) {561CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,562/*ForVirtualBase=*/false,563/*Delegating=*/false, Loc, Ty);564}565};566567struct DestroyNRVOVariableC final568: DestroyNRVOVariable<DestroyNRVOVariableC> {569DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)570: DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}571572void emitDestructorCall(CodeGenFunction &CGF) {573CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);574}575};576577struct CallStackRestore final : EHScopeStack::Cleanup {578Address Stack;579CallStackRestore(Address Stack) : Stack(Stack) {}580bool isRedundantBeforeReturn() override { return true; }581void Emit(CodeGenFunction &CGF, Flags flags) override {582llvm::Value *V = CGF.Builder.CreateLoad(Stack);583CGF.Builder.CreateStackRestore(V);584}585};586587struct KmpcAllocFree final : EHScopeStack::Cleanup {588std::pair<llvm::Value *, llvm::Value *> AddrSizePair;589KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)590: AddrSizePair(AddrSizePair) {}591void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {592auto &RT = CGF.CGM.getOpenMPRuntime();593RT.getKmpcFreeShared(CGF, AddrSizePair);594}595};596597struct ExtendGCLifetime final : EHScopeStack::Cleanup {598const VarDecl &Var;599ExtendGCLifetime(const VarDecl *var) : Var(*var) {}600601void Emit(CodeGenFunction &CGF, Flags flags) override {602// Compute the address of the local variable, in case it's a603// byref or something.604DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,605Var.getType(), VK_LValue, SourceLocation());606llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),607SourceLocation());608CGF.EmitExtendGCLifetime(value);609}610};611612struct CallCleanupFunction final : EHScopeStack::Cleanup {613llvm::Constant *CleanupFn;614const CGFunctionInfo &FnInfo;615const VarDecl &Var;616617CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,618const VarDecl *Var)619: CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}620621void Emit(CodeGenFunction &CGF, Flags flags) override {622DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,623Var.getType(), VK_LValue, SourceLocation());624// Compute the address of the local variable, in case it's a byref625// or something.626llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);627628// In some cases, the type of the function argument will be different from629// the type of the pointer. An example of this is630// void f(void* arg);631// __attribute__((cleanup(f))) void *g;632//633// To fix this we insert a bitcast here.634QualType ArgTy = FnInfo.arg_begin()->type;635llvm::Value *Arg =636CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));637638CallArgList Args;639Args.add(RValue::get(Arg),640CGF.getContext().getPointerType(Var.getType()));641auto Callee = CGCallee::forDirect(CleanupFn);642CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);643}644};645} // end anonymous namespace646647/// EmitAutoVarWithLifetime - Does the setup required for an automatic648/// variable with lifetime.649static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,650Address addr,651Qualifiers::ObjCLifetime lifetime) {652switch (lifetime) {653case Qualifiers::OCL_None:654llvm_unreachable("present but none");655656case Qualifiers::OCL_ExplicitNone:657// nothing to do658break;659660case Qualifiers::OCL_Strong: {661CodeGenFunction::Destroyer *destroyer =662(var.hasAttr<ObjCPreciseLifetimeAttr>()663? CodeGenFunction::destroyARCStrongPrecise664: CodeGenFunction::destroyARCStrongImprecise);665666CleanupKind cleanupKind = CGF.getARCCleanupKind();667CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,668cleanupKind & EHCleanup);669break;670}671case Qualifiers::OCL_Autoreleasing:672// nothing to do673break;674675case Qualifiers::OCL_Weak:676// __weak objects always get EH cleanups; otherwise, exceptions677// could cause really nasty crashes instead of mere leaks.678CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),679CodeGenFunction::destroyARCWeak,680/*useEHCleanup*/ true);681break;682}683}684685static bool isAccessedBy(const VarDecl &var, const Stmt *s) {686if (const Expr *e = dyn_cast<Expr>(s)) {687// Skip the most common kinds of expressions that make688// hierarchy-walking expensive.689s = e = e->IgnoreParenCasts();690691if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))692return (ref->getDecl() == &var);693if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {694const BlockDecl *block = be->getBlockDecl();695for (const auto &I : block->captures()) {696if (I.getVariable() == &var)697return true;698}699}700}701702for (const Stmt *SubStmt : s->children())703// SubStmt might be null; as in missing decl or conditional of an if-stmt.704if (SubStmt && isAccessedBy(var, SubStmt))705return true;706707return false;708}709710static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {711if (!decl) return false;712if (!isa<VarDecl>(decl)) return false;713const VarDecl *var = cast<VarDecl>(decl);714return isAccessedBy(*var, e);715}716717static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,718const LValue &destLV, const Expr *init) {719bool needsCast = false;720721while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {722switch (castExpr->getCastKind()) {723// Look through casts that don't require representation changes.724case CK_NoOp:725case CK_BitCast:726case CK_BlockPointerToObjCPointerCast:727needsCast = true;728break;729730// If we find an l-value to r-value cast from a __weak variable,731// emit this operation as a copy or move.732case CK_LValueToRValue: {733const Expr *srcExpr = castExpr->getSubExpr();734if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)735return false;736737// Emit the source l-value.738LValue srcLV = CGF.EmitLValue(srcExpr);739740// Handle a formal type change to avoid asserting.741auto srcAddr = srcLV.getAddress();742if (needsCast) {743srcAddr = srcAddr.withElementType(destLV.getAddress().getElementType());744}745746// If it was an l-value, use objc_copyWeak.747if (srcExpr->isLValue()) {748CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);749} else {750assert(srcExpr->isXValue());751CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);752}753return true;754}755756// Stop at anything else.757default:758return false;759}760761init = castExpr->getSubExpr();762}763return false;764}765766static void drillIntoBlockVariable(CodeGenFunction &CGF,767LValue &lvalue,768const VarDecl *var) {769lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));770}771772void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,773SourceLocation Loc) {774if (!SanOpts.has(SanitizerKind::NullabilityAssign))775return;776777auto Nullability = LHS.getType()->getNullability();778if (!Nullability || *Nullability != NullabilityKind::NonNull)779return;780781// Check if the right hand side of the assignment is nonnull, if the left782// hand side must be nonnull.783SanitizerScope SanScope(this);784llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);785llvm::Constant *StaticData[] = {786EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),787llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.788llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};789EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},790SanitizerHandler::TypeMismatch, StaticData, RHS);791}792793void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,794LValue lvalue, bool capturedByInit) {795Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();796if (!lifetime) {797llvm::Value *value = EmitScalarExpr(init);798if (capturedByInit)799drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));800EmitNullabilityCheck(lvalue, value, init->getExprLoc());801EmitStoreThroughLValue(RValue::get(value), lvalue, true);802return;803}804805if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))806init = DIE->getExpr();807808// If we're emitting a value with lifetime, we have to do the809// initialization *before* we leave the cleanup scopes.810if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {811CodeGenFunction::RunCleanupsScope Scope(*this);812return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);813}814815// We have to maintain the illusion that the variable is816// zero-initialized. If the variable might be accessed in its817// initializer, zero-initialize before running the initializer, then818// actually perform the initialization with an assign.819bool accessedByInit = false;820if (lifetime != Qualifiers::OCL_ExplicitNone)821accessedByInit = (capturedByInit || isAccessedBy(D, init));822if (accessedByInit) {823LValue tempLV = lvalue;824// Drill down to the __block object if necessary.825if (capturedByInit) {826// We can use a simple GEP for this because it can't have been827// moved yet.828tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),829cast<VarDecl>(D),830/*follow*/ false));831}832833auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());834llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());835836// If __weak, we want to use a barrier under certain conditions.837if (lifetime == Qualifiers::OCL_Weak)838EmitARCInitWeak(tempLV.getAddress(), zero);839840// Otherwise just do a simple store.841else842EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);843}844845// Emit the initializer.846llvm::Value *value = nullptr;847848switch (lifetime) {849case Qualifiers::OCL_None:850llvm_unreachable("present but none");851852case Qualifiers::OCL_Strong: {853if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {854value = EmitARCRetainScalarExpr(init);855break;856}857// If D is pseudo-strong, treat it like __unsafe_unretained here. This means858// that we omit the retain, and causes non-autoreleased return values to be859// immediately released.860[[fallthrough]];861}862863case Qualifiers::OCL_ExplicitNone:864value = EmitARCUnsafeUnretainedScalarExpr(init);865break;866867case Qualifiers::OCL_Weak: {868// If it's not accessed by the initializer, try to emit the869// initialization with a copy or move.870if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {871return;872}873874// No way to optimize a producing initializer into this. It's not875// worth optimizing for, because the value will immediately876// disappear in the common case.877value = EmitScalarExpr(init);878879if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));880if (accessedByInit)881EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);882else883EmitARCInitWeak(lvalue.getAddress(), value);884return;885}886887case Qualifiers::OCL_Autoreleasing:888value = EmitARCRetainAutoreleaseScalarExpr(init);889break;890}891892if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));893894EmitNullabilityCheck(lvalue, value, init->getExprLoc());895896// If the variable might have been accessed by its initializer, we897// might have to initialize with a barrier. We have to do this for898// both __weak and __strong, but __weak got filtered out above.899if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {900llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());901EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);902EmitARCRelease(oldValue, ARCImpreciseLifetime);903return;904}905906EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);907}908909/// Decide whether we can emit the non-zero parts of the specified initializer910/// with equal or fewer than NumStores scalar stores.911static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,912unsigned &NumStores) {913// Zero and Undef never requires any extra stores.914if (isa<llvm::ConstantAggregateZero>(Init) ||915isa<llvm::ConstantPointerNull>(Init) ||916isa<llvm::UndefValue>(Init))917return true;918if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||919isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||920isa<llvm::ConstantExpr>(Init))921return Init->isNullValue() || NumStores--;922923// See if we can emit each element.924if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {925for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {926llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));927if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))928return false;929}930return true;931}932933if (llvm::ConstantDataSequential *CDS =934dyn_cast<llvm::ConstantDataSequential>(Init)) {935for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {936llvm::Constant *Elt = CDS->getElementAsConstant(i);937if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))938return false;939}940return true;941}942943// Anything else is hard and scary.944return false;945}946947/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit948/// the scalar stores that would be required.949static void emitStoresForInitAfterBZero(CodeGenModule &CGM,950llvm::Constant *Init, Address Loc,951bool isVolatile, CGBuilderTy &Builder,952bool IsAutoInit) {953assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&954"called emitStoresForInitAfterBZero for zero or undef value.");955956if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||957isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||958isa<llvm::ConstantExpr>(Init)) {959auto *I = Builder.CreateStore(Init, Loc, isVolatile);960if (IsAutoInit)961I->addAnnotationMetadata("auto-init");962return;963}964965if (llvm::ConstantDataSequential *CDS =966dyn_cast<llvm::ConstantDataSequential>(Init)) {967for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {968llvm::Constant *Elt = CDS->getElementAsConstant(i);969970// If necessary, get a pointer to the element and emit it.971if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))972emitStoresForInitAfterBZero(973CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,974Builder, IsAutoInit);975}976return;977}978979assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&980"Unknown value type!");981982for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {983llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));984985// If necessary, get a pointer to the element and emit it.986if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))987emitStoresForInitAfterBZero(CGM, Elt,988Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),989isVolatile, Builder, IsAutoInit);990}991}992993/// Decide whether we should use bzero plus some stores to initialize a local994/// variable instead of using a memcpy from a constant global. It is beneficial995/// to use bzero if the global is all zeros, or mostly zeros and large.996static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,997uint64_t GlobalSize) {998// If a global is all zeros, always use a bzero.999if (isa<llvm::ConstantAggregateZero>(Init)) return true;10001001// If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,1002// do it if it will require 6 or fewer scalar stores.1003// TODO: Should budget depends on the size? Avoiding a large global warrants1004// plopping in more stores.1005unsigned StoreBudget = 6;1006uint64_t SizeLimit = 32;10071008return GlobalSize > SizeLimit &&1009canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);1010}10111012/// Decide whether we should use memset to initialize a local variable instead1013/// of using a memcpy from a constant global. Assumes we've already decided to1014/// not user bzero.1015/// FIXME We could be more clever, as we are for bzero above, and generate1016/// memset followed by stores. It's unclear that's worth the effort.1017static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,1018uint64_t GlobalSize,1019const llvm::DataLayout &DL) {1020uint64_t SizeLimit = 32;1021if (GlobalSize <= SizeLimit)1022return nullptr;1023return llvm::isBytewiseValue(Init, DL);1024}10251026/// Decide whether we want to split a constant structure or array store into a1027/// sequence of its fields' stores. This may cost us code size and compilation1028/// speed, but plays better with store optimizations.1029static bool shouldSplitConstantStore(CodeGenModule &CGM,1030uint64_t GlobalByteSize) {1031// Don't break things that occupy more than one cacheline.1032uint64_t ByteSizeLimit = 64;1033if (CGM.getCodeGenOpts().OptimizationLevel == 0)1034return false;1035if (GlobalByteSize <= ByteSizeLimit)1036return true;1037return false;1038}10391040enum class IsPattern { No, Yes };10411042/// Generate a constant filled with either a pattern or zeroes.1043static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,1044llvm::Type *Ty) {1045if (isPattern == IsPattern::Yes)1046return initializationPatternFor(CGM, Ty);1047else1048return llvm::Constant::getNullValue(Ty);1049}10501051static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,1052llvm::Constant *constant);10531054/// Helper function for constWithPadding() to deal with padding in structures.1055static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,1056IsPattern isPattern,1057llvm::StructType *STy,1058llvm::Constant *constant) {1059const llvm::DataLayout &DL = CGM.getDataLayout();1060const llvm::StructLayout *Layout = DL.getStructLayout(STy);1061llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());1062unsigned SizeSoFar = 0;1063SmallVector<llvm::Constant *, 8> Values;1064bool NestedIntact = true;1065for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {1066unsigned CurOff = Layout->getElementOffset(i);1067if (SizeSoFar < CurOff) {1068assert(!STy->isPacked());1069auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);1070Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));1071}1072llvm::Constant *CurOp;1073if (constant->isZeroValue())1074CurOp = llvm::Constant::getNullValue(STy->getElementType(i));1075else1076CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));1077auto *NewOp = constWithPadding(CGM, isPattern, CurOp);1078if (CurOp != NewOp)1079NestedIntact = false;1080Values.push_back(NewOp);1081SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());1082}1083unsigned TotalSize = Layout->getSizeInBytes();1084if (SizeSoFar < TotalSize) {1085auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);1086Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));1087}1088if (NestedIntact && Values.size() == STy->getNumElements())1089return constant;1090return llvm::ConstantStruct::getAnon(Values, STy->isPacked());1091}10921093/// Replace all padding bytes in a given constant with either a pattern byte or1094/// 0x00.1095static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,1096llvm::Constant *constant) {1097llvm::Type *OrigTy = constant->getType();1098if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))1099return constStructWithPadding(CGM, isPattern, STy, constant);1100if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {1101llvm::SmallVector<llvm::Constant *, 8> Values;1102uint64_t Size = ArrayTy->getNumElements();1103if (!Size)1104return constant;1105llvm::Type *ElemTy = ArrayTy->getElementType();1106bool ZeroInitializer = constant->isNullValue();1107llvm::Constant *OpValue, *PaddedOp;1108if (ZeroInitializer) {1109OpValue = llvm::Constant::getNullValue(ElemTy);1110PaddedOp = constWithPadding(CGM, isPattern, OpValue);1111}1112for (unsigned Op = 0; Op != Size; ++Op) {1113if (!ZeroInitializer) {1114OpValue = constant->getAggregateElement(Op);1115PaddedOp = constWithPadding(CGM, isPattern, OpValue);1116}1117Values.push_back(PaddedOp);1118}1119auto *NewElemTy = Values[0]->getType();1120if (NewElemTy == ElemTy)1121return constant;1122auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);1123return llvm::ConstantArray::get(NewArrayTy, Values);1124}1125// FIXME: Add handling for tail padding in vectors. Vectors don't1126// have padding between or inside elements, but the total amount of1127// data can be less than the allocated size.1128return constant;1129}11301131Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,1132llvm::Constant *Constant,1133CharUnits Align) {1134auto FunctionName = [&](const DeclContext *DC) -> std::string {1135if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {1136if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))1137return CC->getNameAsString();1138if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))1139return CD->getNameAsString();1140return std::string(getMangledName(FD));1141} else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {1142return OM->getNameAsString();1143} else if (isa<BlockDecl>(DC)) {1144return "<block>";1145} else if (isa<CapturedDecl>(DC)) {1146return "<captured>";1147} else {1148llvm_unreachable("expected a function or method");1149}1150};11511152// Form a simple per-variable cache of these values in case we find we1153// want to reuse them.1154llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];1155if (!CacheEntry || CacheEntry->getInitializer() != Constant) {1156auto *Ty = Constant->getType();1157bool isConstant = true;1158llvm::GlobalVariable *InsertBefore = nullptr;1159unsigned AS =1160getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());1161std::string Name;1162if (D.hasGlobalStorage())1163Name = getMangledName(&D).str() + ".const";1164else if (const DeclContext *DC = D.getParentFunctionOrMethod())1165Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();1166else1167llvm_unreachable("local variable has no parent function or method");1168llvm::GlobalVariable *GV = new llvm::GlobalVariable(1169getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,1170Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);1171GV->setAlignment(Align.getAsAlign());1172GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);1173CacheEntry = GV;1174} else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {1175CacheEntry->setAlignment(Align.getAsAlign());1176}11771178return Address(CacheEntry, CacheEntry->getValueType(), Align);1179}11801181static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,1182const VarDecl &D,1183CGBuilderTy &Builder,1184llvm::Constant *Constant,1185CharUnits Align) {1186Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);1187return SrcPtr.withElementType(CGM.Int8Ty);1188}11891190static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,1191Address Loc, bool isVolatile,1192CGBuilderTy &Builder,1193llvm::Constant *constant, bool IsAutoInit) {1194auto *Ty = constant->getType();1195uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);1196if (!ConstantSize)1197return;11981199bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||1200Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();1201if (canDoSingleStore) {1202auto *I = Builder.CreateStore(constant, Loc, isVolatile);1203if (IsAutoInit)1204I->addAnnotationMetadata("auto-init");1205return;1206}12071208auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);12091210// If the initializer is all or mostly the same, codegen with bzero / memset1211// then do a few stores afterward.1212if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {1213auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),1214SizeVal, isVolatile);1215if (IsAutoInit)1216I->addAnnotationMetadata("auto-init");12171218bool valueAlreadyCorrect =1219constant->isNullValue() || isa<llvm::UndefValue>(constant);1220if (!valueAlreadyCorrect) {1221Loc = Loc.withElementType(Ty);1222emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,1223IsAutoInit);1224}1225return;1226}12271228// If the initializer is a repeated byte pattern, use memset.1229llvm::Value *Pattern =1230shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());1231if (Pattern) {1232uint64_t Value = 0x00;1233if (!isa<llvm::UndefValue>(Pattern)) {1234const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();1235assert(AP.getBitWidth() <= 8);1236Value = AP.getLimitedValue();1237}1238auto *I = Builder.CreateMemSet(1239Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);1240if (IsAutoInit)1241I->addAnnotationMetadata("auto-init");1242return;1243}12441245// If the initializer is small or trivialAutoVarInit is set, use a handful of1246// stores.1247bool IsTrivialAutoVarInitPattern =1248CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==1249LangOptions::TrivialAutoVarInitKind::Pattern;1250if (shouldSplitConstantStore(CGM, ConstantSize)) {1251if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {1252if (STy == Loc.getElementType() ||1253(STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {1254const llvm::StructLayout *Layout =1255CGM.getDataLayout().getStructLayout(STy);1256for (unsigned i = 0; i != constant->getNumOperands(); i++) {1257CharUnits CurOff =1258CharUnits::fromQuantity(Layout->getElementOffset(i));1259Address EltPtr = Builder.CreateConstInBoundsByteGEP(1260Loc.withElementType(CGM.Int8Ty), CurOff);1261emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,1262constant->getAggregateElement(i), IsAutoInit);1263}1264return;1265}1266} else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {1267if (ATy == Loc.getElementType() ||1268(ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {1269for (unsigned i = 0; i != ATy->getNumElements(); i++) {1270Address EltPtr = Builder.CreateConstGEP(1271Loc.withElementType(ATy->getElementType()), i);1272emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,1273constant->getAggregateElement(i), IsAutoInit);1274}1275return;1276}1277}1278}12791280// Copy from a global.1281auto *I =1282Builder.CreateMemCpy(Loc,1283createUnnamedGlobalForMemcpyFrom(1284CGM, D, Builder, constant, Loc.getAlignment()),1285SizeVal, isVolatile);1286if (IsAutoInit)1287I->addAnnotationMetadata("auto-init");1288}12891290static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,1291Address Loc, bool isVolatile,1292CGBuilderTy &Builder) {1293llvm::Type *ElTy = Loc.getElementType();1294llvm::Constant *constant =1295constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));1296emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,1297/*IsAutoInit=*/true);1298}12991300static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,1301Address Loc, bool isVolatile,1302CGBuilderTy &Builder) {1303llvm::Type *ElTy = Loc.getElementType();1304llvm::Constant *constant = constWithPadding(1305CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));1306assert(!isa<llvm::UndefValue>(constant));1307emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,1308/*IsAutoInit=*/true);1309}13101311static bool containsUndef(llvm::Constant *constant) {1312auto *Ty = constant->getType();1313if (isa<llvm::UndefValue>(constant))1314return true;1315if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())1316for (llvm::Use &Op : constant->operands())1317if (containsUndef(cast<llvm::Constant>(Op)))1318return true;1319return false;1320}13211322static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,1323llvm::Constant *constant) {1324auto *Ty = constant->getType();1325if (isa<llvm::UndefValue>(constant))1326return patternOrZeroFor(CGM, isPattern, Ty);1327if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))1328return constant;1329if (!containsUndef(constant))1330return constant;1331llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());1332for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {1333auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));1334Values[Op] = replaceUndef(CGM, isPattern, OpValue);1335}1336if (Ty->isStructTy())1337return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);1338if (Ty->isArrayTy())1339return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);1340assert(Ty->isVectorTy());1341return llvm::ConstantVector::get(Values);1342}13431344/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a1345/// variable declaration with auto, register, or no storage class specifier.1346/// These turn into simple stack objects, or GlobalValues depending on target.1347void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {1348AutoVarEmission emission = EmitAutoVarAlloca(D);1349EmitAutoVarInit(emission);1350EmitAutoVarCleanups(emission);1351}13521353/// Emit a lifetime.begin marker if some criteria are satisfied.1354/// \return a pointer to the temporary size Value if a marker was emitted, null1355/// otherwise1356llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,1357llvm::Value *Addr) {1358if (!ShouldEmitLifetimeMarkers)1359return nullptr;13601361assert(Addr->getType()->getPointerAddressSpace() ==1362CGM.getDataLayout().getAllocaAddrSpace() &&1363"Pointer should be in alloca address space");1364llvm::Value *SizeV = llvm::ConstantInt::get(1365Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());1366llvm::CallInst *C =1367Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});1368C->setDoesNotThrow();1369return SizeV;1370}13711372void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {1373assert(Addr->getType()->getPointerAddressSpace() ==1374CGM.getDataLayout().getAllocaAddrSpace() &&1375"Pointer should be in alloca address space");1376llvm::CallInst *C =1377Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});1378C->setDoesNotThrow();1379}13801381void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(1382CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {1383// For each dimension stores its QualType and corresponding1384// size-expression Value.1385SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;1386SmallVector<const IdentifierInfo *, 4> VLAExprNames;13871388// Break down the array into individual dimensions.1389QualType Type1D = D.getType();1390while (getContext().getAsVariableArrayType(Type1D)) {1391auto VlaSize = getVLAElements1D(Type1D);1392if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))1393Dimensions.emplace_back(C, Type1D.getUnqualifiedType());1394else {1395// Generate a locally unique name for the size expression.1396Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);1397SmallString<12> Buffer;1398StringRef NameRef = Name.toStringRef(Buffer);1399auto &Ident = getContext().Idents.getOwn(NameRef);1400VLAExprNames.push_back(&Ident);1401auto SizeExprAddr =1402CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);1403Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);1404Dimensions.emplace_back(SizeExprAddr.getPointer(),1405Type1D.getUnqualifiedType());1406}1407Type1D = VlaSize.Type;1408}14091410if (!EmitDebugInfo)1411return;14121413// Register each dimension's size-expression with a DILocalVariable,1414// so that it can be used by CGDebugInfo when instantiating a DISubrange1415// to describe this array.1416unsigned NameIdx = 0;1417for (auto &VlaSize : Dimensions) {1418llvm::Metadata *MD;1419if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))1420MD = llvm::ConstantAsMetadata::get(C);1421else {1422// Create an artificial VarDecl to generate debug info for.1423const IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];1424auto QT = getContext().getIntTypeForBitwidth(1425SizeTy->getScalarSizeInBits(), false);1426auto *ArtificialDecl = VarDecl::Create(1427getContext(), const_cast<DeclContext *>(D.getDeclContext()),1428D.getLocation(), D.getLocation(), NameIdent, QT,1429getContext().CreateTypeSourceInfo(QT), SC_Auto);1430ArtificialDecl->setImplicit();14311432MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,1433Builder);1434}1435assert(MD && "No Size expression debug node created");1436DI->registerVLASizeExpression(VlaSize.Type, MD);1437}1438}14391440/// EmitAutoVarAlloca - Emit the alloca and debug information for a1441/// local variable. Does not emit initialization or destruction.1442CodeGenFunction::AutoVarEmission1443CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {1444QualType Ty = D.getType();1445assert(1446Ty.getAddressSpace() == LangAS::Default ||1447(Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));14481449AutoVarEmission emission(D);14501451bool isEscapingByRef = D.isEscapingByref();1452emission.IsEscapingByRef = isEscapingByRef;14531454CharUnits alignment = getContext().getDeclAlign(&D);14551456// If the type is variably-modified, emit all the VLA sizes for it.1457if (Ty->isVariablyModifiedType())1458EmitVariablyModifiedType(Ty);14591460auto *DI = getDebugInfo();1461bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();14621463Address address = Address::invalid();1464RawAddress AllocaAddr = RawAddress::invalid();1465Address OpenMPLocalAddr = Address::invalid();1466if (CGM.getLangOpts().OpenMPIRBuilder)1467OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);1468else1469OpenMPLocalAddr =1470getLangOpts().OpenMP1471? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)1472: Address::invalid();14731474bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();14751476if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {1477address = OpenMPLocalAddr;1478AllocaAddr = OpenMPLocalAddr;1479} else if (Ty->isConstantSizeType()) {1480// If this value is an array or struct with a statically determinable1481// constant initializer, there are optimizations we can do.1482//1483// TODO: We should constant-evaluate the initializer of any variable,1484// as long as it is initialized by a constant expression. Currently,1485// isConstantInitializer produces wrong answers for structs with1486// reference or bitfield members, and a few other cases, and checking1487// for POD-ness protects us from some of these.1488if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&1489(D.isConstexpr() ||1490((Ty.isPODType(getContext()) ||1491getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&1492D.getInit()->isConstantInitializer(getContext(), false)))) {14931494// If the variable's a const type, and it's neither an NRVO1495// candidate nor a __block variable and has no mutable members,1496// emit it as a global instead.1497// Exception is if a variable is located in non-constant address space1498// in OpenCL.1499bool NeedsDtor =1500D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;1501if ((!getLangOpts().OpenCL ||1502Ty.getAddressSpace() == LangAS::opencl_constant) &&1503(CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&1504!isEscapingByRef &&1505Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {1506EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);15071508// Signal this condition to later callbacks.1509emission.Addr = Address::invalid();1510assert(emission.wasEmittedAsGlobal());1511return emission;1512}15131514// Otherwise, tell the initialization code that we're in this case.1515emission.IsConstantAggregate = true;1516}15171518// A normal fixed sized variable becomes an alloca in the entry block,1519// unless:1520// - it's an NRVO variable.1521// - we are compiling OpenMP and it's an OpenMP local variable.1522if (NRVO) {1523// The named return value optimization: allocate this variable in the1524// return slot, so that we can elide the copy when returning this1525// variable (C++0x [class.copy]p34).1526address = ReturnValue;1527AllocaAddr =1528RawAddress(ReturnValue.emitRawPointer(*this),1529ReturnValue.getElementType(), ReturnValue.getAlignment());1530;15311532if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {1533const auto *RD = RecordTy->getDecl();1534const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);1535if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||1536RD->isNonTrivialToPrimitiveDestroy()) {1537// Create a flag that is used to indicate when the NRVO was applied1538// to this variable. Set it to zero to indicate that NRVO was not1539// applied.1540llvm::Value *Zero = Builder.getFalse();1541RawAddress NRVOFlag =1542CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");1543EnsureInsertPoint();1544Builder.CreateStore(Zero, NRVOFlag);15451546// Record the NRVO flag for this variable.1547NRVOFlags[&D] = NRVOFlag.getPointer();1548emission.NRVOFlag = NRVOFlag.getPointer();1549}1550}1551} else {1552CharUnits allocaAlignment;1553llvm::Type *allocaTy;1554if (isEscapingByRef) {1555auto &byrefInfo = getBlockByrefInfo(&D);1556allocaTy = byrefInfo.Type;1557allocaAlignment = byrefInfo.ByrefAlignment;1558} else {1559allocaTy = ConvertTypeForMem(Ty);1560allocaAlignment = alignment;1561}15621563// Create the alloca. Note that we set the name separately from1564// building the instruction so that it's there even in no-asserts1565// builds.1566address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),1567/*ArraySize=*/nullptr, &AllocaAddr);15681569// Don't emit lifetime markers for MSVC catch parameters. The lifetime of1570// the catch parameter starts in the catchpad instruction, and we can't1571// insert code in those basic blocks.1572bool IsMSCatchParam =1573D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();15741575// Emit a lifetime intrinsic if meaningful. There's no point in doing this1576// if we don't have a valid insertion point (?).1577if (HaveInsertPoint() && !IsMSCatchParam) {1578// If there's a jump into the lifetime of this variable, its lifetime1579// gets broken up into several regions in IR, which requires more work1580// to handle correctly. For now, just omit the intrinsics; this is a1581// rare case, and it's better to just be conservatively correct.1582// PR28267.1583//1584// We have to do this in all language modes if there's a jump past the1585// declaration. We also have to do it in C if there's a jump to an1586// earlier point in the current block because non-VLA lifetimes begin as1587// soon as the containing block is entered, not when its variables1588// actually come into scope; suppressing the lifetime annotations1589// completely in this case is unnecessarily pessimistic, but again, this1590// is rare.1591if (!Bypasses.IsBypassed(&D) &&1592!(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {1593llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);1594emission.SizeForLifetimeMarkers =1595EmitLifetimeStart(Size, AllocaAddr.getPointer());1596}1597} else {1598assert(!emission.useLifetimeMarkers());1599}1600}1601} else {1602EnsureInsertPoint();16031604// Delayed globalization for variable length declarations. This ensures that1605// the expression representing the length has been emitted and can be used1606// by the definition of the VLA. Since this is an escaped declaration, in1607// OpenMP we have to use a call to __kmpc_alloc_shared(). The matching1608// deallocation call to __kmpc_free_shared() is emitted later.1609bool VarAllocated = false;1610if (getLangOpts().OpenMPIsTargetDevice) {1611auto &RT = CGM.getOpenMPRuntime();1612if (RT.isDelayedVariableLengthDecl(*this, &D)) {1613// Emit call to __kmpc_alloc_shared() instead of the alloca.1614std::pair<llvm::Value *, llvm::Value *> AddrSizePair =1615RT.getKmpcAllocShared(*this, &D);16161617// Save the address of the allocation:1618LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),1619CGM.getContext().getDeclAlign(&D),1620AlignmentSource::Decl);1621address = Base.getAddress();16221623// Push a cleanup block to emit the call to __kmpc_free_shared in the1624// appropriate location at the end of the scope of the1625// __kmpc_alloc_shared functions:1626pushKmpcAllocFree(NormalCleanup, AddrSizePair);16271628// Mark variable as allocated:1629VarAllocated = true;1630}1631}16321633if (!VarAllocated) {1634if (!DidCallStackSave) {1635// Save the stack.1636Address Stack =1637CreateDefaultAlignTempAlloca(AllocaInt8PtrTy, "saved_stack");16381639llvm::Value *V = Builder.CreateStackSave();1640assert(V->getType() == AllocaInt8PtrTy);1641Builder.CreateStore(V, Stack);16421643DidCallStackSave = true;16441645// Push a cleanup block and restore the stack there.1646// FIXME: in general circumstances, this should be an EH cleanup.1647pushStackRestore(NormalCleanup, Stack);1648}16491650auto VlaSize = getVLASize(Ty);1651llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);16521653// Allocate memory for the array.1654address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,1655&AllocaAddr);1656}16571658// If we have debug info enabled, properly describe the VLA dimensions for1659// this type by registering the vla size expression for each of the1660// dimensions.1661EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);1662}16631664setAddrOfLocalVar(&D, address);1665emission.Addr = address;1666emission.AllocaAddr = AllocaAddr;16671668// Emit debug info for local var declaration.1669if (EmitDebugInfo && HaveInsertPoint()) {1670Address DebugAddr = address;1671bool UsePointerValue = NRVO && ReturnValuePointer.isValid();1672DI->setLocation(D.getLocation());16731674// If NRVO, use a pointer to the return address.1675if (UsePointerValue) {1676DebugAddr = ReturnValuePointer;1677AllocaAddr = ReturnValuePointer;1678}1679(void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,1680UsePointerValue);1681}16821683if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())1684EmitVarAnnotations(&D, address.emitRawPointer(*this));16851686// Make sure we call @llvm.lifetime.end.1687if (emission.useLifetimeMarkers())1688EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,1689emission.getOriginalAllocatedAddress(),1690emission.getSizeForLifetimeMarkers());16911692return emission;1693}16941695static bool isCapturedBy(const VarDecl &, const Expr *);16961697/// Determines whether the given __block variable is potentially1698/// captured by the given statement.1699static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {1700if (const Expr *E = dyn_cast<Expr>(S))1701return isCapturedBy(Var, E);1702for (const Stmt *SubStmt : S->children())1703if (isCapturedBy(Var, SubStmt))1704return true;1705return false;1706}17071708/// Determines whether the given __block variable is potentially1709/// captured by the given expression.1710static bool isCapturedBy(const VarDecl &Var, const Expr *E) {1711// Skip the most common kinds of expressions that make1712// hierarchy-walking expensive.1713E = E->IgnoreParenCasts();17141715if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {1716const BlockDecl *Block = BE->getBlockDecl();1717for (const auto &I : Block->captures()) {1718if (I.getVariable() == &Var)1719return true;1720}17211722// No need to walk into the subexpressions.1723return false;1724}17251726if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {1727const CompoundStmt *CS = SE->getSubStmt();1728for (const auto *BI : CS->body())1729if (const auto *BIE = dyn_cast<Expr>(BI)) {1730if (isCapturedBy(Var, BIE))1731return true;1732}1733else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {1734// special case declarations1735for (const auto *I : DS->decls()) {1736if (const auto *VD = dyn_cast<VarDecl>((I))) {1737const Expr *Init = VD->getInit();1738if (Init && isCapturedBy(Var, Init))1739return true;1740}1741}1742}1743else1744// FIXME. Make safe assumption assuming arbitrary statements cause capturing.1745// Later, provide code to poke into statements for capture analysis.1746return true;1747return false;1748}17491750for (const Stmt *SubStmt : E->children())1751if (isCapturedBy(Var, SubStmt))1752return true;17531754return false;1755}17561757/// Determine whether the given initializer is trivial in the sense1758/// that it requires no code to be generated.1759bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {1760if (!Init)1761return true;17621763if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))1764if (CXXConstructorDecl *Constructor = Construct->getConstructor())1765if (Constructor->isTrivial() &&1766Constructor->isDefaultConstructor() &&1767!Construct->requiresZeroInitialization())1768return true;17691770return false;1771}17721773void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,1774const VarDecl &D,1775Address Loc) {1776auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();1777auto trivialAutoVarInitMaxSize =1778getContext().getLangOpts().TrivialAutoVarInitMaxSize;1779CharUnits Size = getContext().getTypeSizeInChars(type);1780bool isVolatile = type.isVolatileQualified();1781if (!Size.isZero()) {1782// We skip auto-init variables by their alloc size. Take this as an example:1783// "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.1784// All Foo type variables will be skipped. Ideally, we only skip the buff1785// array and still auto-init X in this example.1786// TODO: Improve the size filtering to by member size.1787auto allocSize = CGM.getDataLayout().getTypeAllocSize(Loc.getElementType());1788switch (trivialAutoVarInit) {1789case LangOptions::TrivialAutoVarInitKind::Uninitialized:1790llvm_unreachable("Uninitialized handled by caller");1791case LangOptions::TrivialAutoVarInitKind::Zero:1792if (CGM.stopAutoInit())1793return;1794if (trivialAutoVarInitMaxSize > 0 &&1795allocSize > trivialAutoVarInitMaxSize)1796return;1797emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);1798break;1799case LangOptions::TrivialAutoVarInitKind::Pattern:1800if (CGM.stopAutoInit())1801return;1802if (trivialAutoVarInitMaxSize > 0 &&1803allocSize > trivialAutoVarInitMaxSize)1804return;1805emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);1806break;1807}1808return;1809}18101811// VLAs look zero-sized to getTypeInfo. We can't emit constant stores to1812// them, so emit a memcpy with the VLA size to initialize each element.1813// Technically zero-sized or negative-sized VLAs are undefined, and UBSan1814// will catch that code, but there exists code which generates zero-sized1815// VLAs. Be nice and initialize whatever they requested.1816const auto *VlaType = getContext().getAsVariableArrayType(type);1817if (!VlaType)1818return;1819auto VlaSize = getVLASize(VlaType);1820auto SizeVal = VlaSize.NumElts;1821CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);1822switch (trivialAutoVarInit) {1823case LangOptions::TrivialAutoVarInitKind::Uninitialized:1824llvm_unreachable("Uninitialized handled by caller");18251826case LangOptions::TrivialAutoVarInitKind::Zero: {1827if (CGM.stopAutoInit())1828return;1829if (!EltSize.isOne())1830SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));1831auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),1832SizeVal, isVolatile);1833I->addAnnotationMetadata("auto-init");1834break;1835}18361837case LangOptions::TrivialAutoVarInitKind::Pattern: {1838if (CGM.stopAutoInit())1839return;1840llvm::Type *ElTy = Loc.getElementType();1841llvm::Constant *Constant = constWithPadding(1842CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));1843CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);1844llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");1845llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");1846llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");1847llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(1848SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),1849"vla.iszerosized");1850Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);1851EmitBlock(SetupBB);1852if (!EltSize.isOne())1853SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));1854llvm::Value *BaseSizeInChars =1855llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());1856Address Begin = Loc.withElementType(Int8Ty);1857llvm::Value *End = Builder.CreateInBoundsGEP(Begin.getElementType(),1858Begin.emitRawPointer(*this),1859SizeVal, "vla.end");1860llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();1861EmitBlock(LoopBB);1862llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");1863Cur->addIncoming(Begin.emitRawPointer(*this), OriginBB);1864CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);1865auto *I =1866Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),1867createUnnamedGlobalForMemcpyFrom(1868CGM, D, Builder, Constant, ConstantAlign),1869BaseSizeInChars, isVolatile);1870I->addAnnotationMetadata("auto-init");1871llvm::Value *Next =1872Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");1873llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");1874Builder.CreateCondBr(Done, ContBB, LoopBB);1875Cur->addIncoming(Next, LoopBB);1876EmitBlock(ContBB);1877} break;1878}1879}18801881void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {1882assert(emission.Variable && "emission was not valid!");18831884// If this was emitted as a global constant, we're done.1885if (emission.wasEmittedAsGlobal()) return;18861887const VarDecl &D = *emission.Variable;1888auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());1889QualType type = D.getType();18901891// If this local has an initializer, emit it now.1892const Expr *Init = D.getInit();18931894// If we are at an unreachable point, we don't need to emit the initializer1895// unless it contains a label.1896if (!HaveInsertPoint()) {1897if (!Init || !ContainsLabel(Init)) return;1898EnsureInsertPoint();1899}19001901// Initialize the structure of a __block variable.1902if (emission.IsEscapingByRef)1903emitByrefStructureInit(emission);19041905// Initialize the variable here if it doesn't have a initializer and it is a1906// C struct that is non-trivial to initialize or an array containing such a1907// struct.1908if (!Init &&1909type.isNonTrivialToPrimitiveDefaultInitialize() ==1910QualType::PDIK_Struct) {1911LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);1912if (emission.IsEscapingByRef)1913drillIntoBlockVariable(*this, Dst, &D);1914defaultInitNonTrivialCStructVar(Dst);1915return;1916}19171918// Check whether this is a byref variable that's potentially1919// captured and moved by its own initializer. If so, we'll need to1920// emit the initializer first, then copy into the variable.1921bool capturedByInit =1922Init && emission.IsEscapingByRef && isCapturedBy(D, Init);19231924bool locIsByrefHeader = !capturedByInit;1925const Address Loc =1926locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;19271928// Note: constexpr already initializes everything correctly.1929LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =1930(D.isConstexpr()1931? LangOptions::TrivialAutoVarInitKind::Uninitialized1932: (D.getAttr<UninitializedAttr>()1933? LangOptions::TrivialAutoVarInitKind::Uninitialized1934: getContext().getLangOpts().getTrivialAutoVarInit()));19351936auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {1937if (trivialAutoVarInit ==1938LangOptions::TrivialAutoVarInitKind::Uninitialized)1939return;19401941// Only initialize a __block's storage: we always initialize the header.1942if (emission.IsEscapingByRef && !locIsByrefHeader)1943Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);19441945return emitZeroOrPatternForAutoVarInit(type, D, Loc);1946};19471948if (isTrivialInitializer(Init))1949return initializeWhatIsTechnicallyUninitialized(Loc);19501951llvm::Constant *constant = nullptr;1952if (emission.IsConstantAggregate ||1953D.mightBeUsableInConstantExpressions(getContext())) {1954assert(!capturedByInit && "constant init contains a capturing block?");1955constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);1956if (constant && !constant->isZeroValue() &&1957(trivialAutoVarInit !=1958LangOptions::TrivialAutoVarInitKind::Uninitialized)) {1959IsPattern isPattern =1960(trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)1961? IsPattern::Yes1962: IsPattern::No;1963// C guarantees that brace-init with fewer initializers than members in1964// the aggregate will initialize the rest of the aggregate as-if it were1965// static initialization. In turn static initialization guarantees that1966// padding is initialized to zero bits. We could instead pattern-init if D1967// has any ImplicitValueInitExpr, but that seems to be unintuitive1968// behavior.1969constant = constWithPadding(CGM, IsPattern::No,1970replaceUndef(CGM, isPattern, constant));1971}19721973if (D.getType()->isBitIntType() &&1974CGM.getTypes().typeRequiresSplitIntoByteArray(D.getType())) {1975// Constants for long _BitInt types are split into individual bytes.1976// Try to fold these back into an integer constant so it can be stored1977// properly.1978llvm::Type *LoadType = CGM.getTypes().convertTypeForLoadStore(1979D.getType(), constant->getType());1980constant = llvm::ConstantFoldLoadFromConst(1981constant, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());1982}1983}19841985if (!constant) {1986if (trivialAutoVarInit !=1987LangOptions::TrivialAutoVarInitKind::Uninitialized) {1988// At this point, we know D has an Init expression, but isn't a constant.1989// - If D is not a scalar, auto-var-init conservatively (members may be1990// left uninitialized by constructor Init expressions for example).1991// - If D is a scalar, we only need to auto-var-init if there is a1992// self-reference. Otherwise, the Init expression should be sufficient.1993// It may be that the Init expression uses other uninitialized memory,1994// but auto-var-init here would not help, as auto-init would get1995// overwritten by Init.1996if (!D.getType()->isScalarType() || capturedByInit ||1997isAccessedBy(D, Init)) {1998initializeWhatIsTechnicallyUninitialized(Loc);1999}2000}2001LValue lv = MakeAddrLValue(Loc, type);2002lv.setNonGC(true);2003return EmitExprAsInit(Init, &D, lv, capturedByInit);2004}20052006if (!emission.IsConstantAggregate) {2007// For simple scalar/complex initialization, store the value directly.2008LValue lv = MakeAddrLValue(Loc, type);2009lv.setNonGC(true);2010return EmitStoreThroughLValue(RValue::get(constant), lv, true);2011}20122013emitStoresForConstant(CGM, D, Loc.withElementType(CGM.Int8Ty),2014type.isVolatileQualified(), Builder, constant,2015/*IsAutoInit=*/false);2016}20172018/// Emit an expression as an initializer for an object (variable, field, etc.)2019/// at the given location. The expression is not necessarily the normal2020/// initializer for the object, and the address is not necessarily2021/// its normal location.2022///2023/// \param init the initializing expression2024/// \param D the object to act as if we're initializing2025/// \param lvalue the lvalue to initialize2026/// \param capturedByInit true if \p D is a __block variable2027/// whose address is potentially changed by the initializer2028void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,2029LValue lvalue, bool capturedByInit) {2030QualType type = D->getType();20312032if (type->isReferenceType()) {2033RValue rvalue = EmitReferenceBindingToExpr(init);2034if (capturedByInit)2035drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));2036EmitStoreThroughLValue(rvalue, lvalue, true);2037return;2038}2039switch (getEvaluationKind(type)) {2040case TEK_Scalar:2041EmitScalarInit(init, D, lvalue, capturedByInit);2042return;2043case TEK_Complex: {2044ComplexPairTy complex = EmitComplexExpr(init);2045if (capturedByInit)2046drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));2047EmitStoreOfComplex(complex, lvalue, /*init*/ true);2048return;2049}2050case TEK_Aggregate:2051if (type->isAtomicType()) {2052EmitAtomicInit(const_cast<Expr*>(init), lvalue);2053} else {2054AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;2055if (isa<VarDecl>(D))2056Overlap = AggValueSlot::DoesNotOverlap;2057else if (auto *FD = dyn_cast<FieldDecl>(D))2058Overlap = getOverlapForFieldInit(FD);2059// TODO: how can we delay here if D is captured by its initializer?2060EmitAggExpr(init,2061AggValueSlot::forLValue(lvalue, AggValueSlot::IsDestructed,2062AggValueSlot::DoesNotNeedGCBarriers,2063AggValueSlot::IsNotAliased, Overlap));2064}2065return;2066}2067llvm_unreachable("bad evaluation kind");2068}20692070/// Enter a destroy cleanup for the given local variable.2071void CodeGenFunction::emitAutoVarTypeCleanup(2072const CodeGenFunction::AutoVarEmission &emission,2073QualType::DestructionKind dtorKind) {2074assert(dtorKind != QualType::DK_none);20752076// Note that for __block variables, we want to destroy the2077// original stack object, not the possibly forwarded object.2078Address addr = emission.getObjectAddress(*this);20792080const VarDecl *var = emission.Variable;2081QualType type = var->getType();20822083CleanupKind cleanupKind = NormalAndEHCleanup;2084CodeGenFunction::Destroyer *destroyer = nullptr;20852086switch (dtorKind) {2087case QualType::DK_none:2088llvm_unreachable("no cleanup for trivially-destructible variable");20892090case QualType::DK_cxx_destructor:2091// If there's an NRVO flag on the emission, we need a different2092// cleanup.2093if (emission.NRVOFlag) {2094assert(!type->isArrayType());2095CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();2096EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,2097emission.NRVOFlag);2098return;2099}2100break;21012102case QualType::DK_objc_strong_lifetime:2103// Suppress cleanups for pseudo-strong variables.2104if (var->isARCPseudoStrong()) return;21052106// Otherwise, consider whether to use an EH cleanup or not.2107cleanupKind = getARCCleanupKind();21082109// Use the imprecise destroyer by default.2110if (!var->hasAttr<ObjCPreciseLifetimeAttr>())2111destroyer = CodeGenFunction::destroyARCStrongImprecise;2112break;21132114case QualType::DK_objc_weak_lifetime:2115break;21162117case QualType::DK_nontrivial_c_struct:2118destroyer = CodeGenFunction::destroyNonTrivialCStruct;2119if (emission.NRVOFlag) {2120assert(!type->isArrayType());2121EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,2122emission.NRVOFlag, type);2123return;2124}2125break;2126}21272128// If we haven't chosen a more specific destroyer, use the default.2129if (!destroyer) destroyer = getDestroyer(dtorKind);21302131// Use an EH cleanup in array destructors iff the destructor itself2132// is being pushed as an EH cleanup.2133bool useEHCleanup = (cleanupKind & EHCleanup);2134EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,2135useEHCleanup);2136}21372138void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {2139assert(emission.Variable && "emission was not valid!");21402141// If this was emitted as a global constant, we're done.2142if (emission.wasEmittedAsGlobal()) return;21432144// If we don't have an insertion point, we're done. Sema prevents2145// us from jumping into any of these scopes anyway.2146if (!HaveInsertPoint()) return;21472148const VarDecl &D = *emission.Variable;21492150// Check the type for a cleanup.2151if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))2152emitAutoVarTypeCleanup(emission, dtorKind);21532154// In GC mode, honor objc_precise_lifetime.2155if (getLangOpts().getGC() != LangOptions::NonGC &&2156D.hasAttr<ObjCPreciseLifetimeAttr>()) {2157EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);2158}21592160// Handle the cleanup attribute.2161if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {2162const FunctionDecl *FD = CA->getFunctionDecl();21632164llvm::Constant *F = CGM.GetAddrOfFunction(FD);2165assert(F && "Could not find function!");21662167const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);2168EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);2169}21702171// If this is a block variable, call _Block_object_destroy2172// (on the unforwarded address). Don't enter this cleanup if we're in pure-GC2173// mode.2174if (emission.IsEscapingByRef &&2175CGM.getLangOpts().getGC() != LangOptions::GCOnly) {2176BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;2177if (emission.Variable->getType().isObjCGCWeak())2178Flags |= BLOCK_FIELD_IS_WEAK;2179enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,2180/*LoadBlockVarAddr*/ false,2181cxxDestructorCanThrow(emission.Variable->getType()));2182}2183}21842185CodeGenFunction::Destroyer *2186CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {2187switch (kind) {2188case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");2189case QualType::DK_cxx_destructor:2190return destroyCXXObject;2191case QualType::DK_objc_strong_lifetime:2192return destroyARCStrongPrecise;2193case QualType::DK_objc_weak_lifetime:2194return destroyARCWeak;2195case QualType::DK_nontrivial_c_struct:2196return destroyNonTrivialCStruct;2197}2198llvm_unreachable("Unknown DestructionKind");2199}22002201/// pushEHDestroy - Push the standard destructor for the given type as2202/// an EH-only cleanup.2203void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,2204Address addr, QualType type) {2205assert(dtorKind && "cannot push destructor for trivial type");2206assert(needsEHCleanup(dtorKind));22072208pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);2209}22102211/// pushDestroy - Push the standard destructor for the given type as2212/// at least a normal cleanup.2213void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,2214Address addr, QualType type) {2215assert(dtorKind && "cannot push destructor for trivial type");22162217CleanupKind cleanupKind = getCleanupKind(dtorKind);2218pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),2219cleanupKind & EHCleanup);2220}22212222void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,2223QualType type, Destroyer *destroyer,2224bool useEHCleanupForArray) {2225pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,2226destroyer, useEHCleanupForArray);2227}22282229// Pushes a destroy and defers its deactivation until its2230// CleanupDeactivationScope is exited.2231void CodeGenFunction::pushDestroyAndDeferDeactivation(2232QualType::DestructionKind dtorKind, Address addr, QualType type) {2233assert(dtorKind && "cannot push destructor for trivial type");22342235CleanupKind cleanupKind = getCleanupKind(dtorKind);2236pushDestroyAndDeferDeactivation(2237cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup);2238}22392240void CodeGenFunction::pushDestroyAndDeferDeactivation(2241CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,2242bool useEHCleanupForArray) {2243llvm::Instruction *DominatingIP =2244Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));2245pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray);2246DeferredDeactivationCleanupStack.push_back(2247{EHStack.stable_begin(), DominatingIP});2248}22492250void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {2251EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);2252}22532254void CodeGenFunction::pushKmpcAllocFree(2255CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {2256EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);2257}22582259void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,2260Address addr, QualType type,2261Destroyer *destroyer,2262bool useEHCleanupForArray) {2263// If we're not in a conditional branch, we don't need to bother generating a2264// conditional cleanup.2265if (!isInConditionalBranch()) {2266// FIXME: When popping normal cleanups, we need to keep this EH cleanup2267// around in case a temporary's destructor throws an exception.22682269// Add the cleanup to the EHStack. After the full-expr, this would be2270// deactivated before being popped from the stack.2271pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,2272useEHCleanupForArray);22732274// Since this is lifetime-extended, push it once again to the EHStack after2275// the full expression.2276return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(2277cleanupKind, Address::invalid(), addr, type, destroyer,2278useEHCleanupForArray);2279}22802281// Otherwise, we should only destroy the object if it's been initialized.22822283using ConditionalCleanupType =2284EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,2285Destroyer *, bool>;2286DominatingValue<Address>::saved_type SavedAddr = saveValueInCond(addr);22872288// Remember to emit cleanup if we branch-out before end of full-expression2289// (eg: through stmt-expr or coro suspensions).2290AllocaTrackerRAII DeactivationAllocas(*this);2291Address ActiveFlagForDeactivation = createCleanupActiveFlag();22922293pushCleanupAndDeferDeactivation<ConditionalCleanupType>(2294cleanupKind, SavedAddr, type, destroyer, useEHCleanupForArray);2295initFullExprCleanupWithFlag(ActiveFlagForDeactivation);2296EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());2297// Erase the active flag if the cleanup was not emitted.2298cleanup.AddAuxAllocas(std::move(DeactivationAllocas).Take());22992300// Since this is lifetime-extended, push it once again to the EHStack after2301// the full expression.2302// The previous active flag would always be 'false' due to forced deferred2303// deactivation. Use a separate flag for lifetime-extension to correctly2304// remember if this branch was taken and the object was initialized.2305Address ActiveFlagForLifetimeExt = createCleanupActiveFlag();2306pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(2307cleanupKind, ActiveFlagForLifetimeExt, SavedAddr, type, destroyer,2308useEHCleanupForArray);2309}23102311/// emitDestroy - Immediately perform the destruction of the given2312/// object.2313///2314/// \param addr - the address of the object; a type*2315/// \param type - the type of the object; if an array type, all2316/// objects are destroyed in reverse order2317/// \param destroyer - the function to call to destroy individual2318/// elements2319/// \param useEHCleanupForArray - whether an EH cleanup should be2320/// used when destroying array elements, in case one of the2321/// destructions throws an exception2322void CodeGenFunction::emitDestroy(Address addr, QualType type,2323Destroyer *destroyer,2324bool useEHCleanupForArray) {2325const ArrayType *arrayType = getContext().getAsArrayType(type);2326if (!arrayType)2327return destroyer(*this, addr, type);23282329llvm::Value *length = emitArrayLength(arrayType, type, addr);23302331CharUnits elementAlign =2332addr.getAlignment()2333.alignmentOfArrayElement(getContext().getTypeSizeInChars(type));23342335// Normally we have to check whether the array is zero-length.2336bool checkZeroLength = true;23372338// But if the array length is constant, we can suppress that.2339if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {2340// ...and if it's constant zero, we can just skip the entire thing.2341if (constLength->isZero()) return;2342checkZeroLength = false;2343}23442345llvm::Value *begin = addr.emitRawPointer(*this);2346llvm::Value *end =2347Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);2348emitArrayDestroy(begin, end, type, elementAlign, destroyer,2349checkZeroLength, useEHCleanupForArray);2350}23512352/// emitArrayDestroy - Destroys all the elements of the given array,2353/// beginning from last to first. The array cannot be zero-length.2354///2355/// \param begin - a type* denoting the first element of the array2356/// \param end - a type* denoting one past the end of the array2357/// \param elementType - the element type of the array2358/// \param destroyer - the function to call to destroy elements2359/// \param useEHCleanup - whether to push an EH cleanup to destroy2360/// the remaining elements in case the destruction of a single2361/// element throws2362void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,2363llvm::Value *end,2364QualType elementType,2365CharUnits elementAlign,2366Destroyer *destroyer,2367bool checkZeroLength,2368bool useEHCleanup) {2369assert(!elementType->isArrayType());23702371// The basic structure here is a do-while loop, because we don't2372// need to check for the zero-element case.2373llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");2374llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");23752376if (checkZeroLength) {2377llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,2378"arraydestroy.isempty");2379Builder.CreateCondBr(isEmpty, doneBB, bodyBB);2380}23812382// Enter the loop body, making that address the current address.2383llvm::BasicBlock *entryBB = Builder.GetInsertBlock();2384EmitBlock(bodyBB);2385llvm::PHINode *elementPast =2386Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");2387elementPast->addIncoming(end, entryBB);23882389// Shift the address back by one element.2390llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);2391llvm::Type *llvmElementType = ConvertTypeForMem(elementType);2392llvm::Value *element = Builder.CreateInBoundsGEP(2393llvmElementType, elementPast, negativeOne, "arraydestroy.element");23942395if (useEHCleanup)2396pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,2397destroyer);23982399// Perform the actual destruction there.2400destroyer(*this, Address(element, llvmElementType, elementAlign),2401elementType);24022403if (useEHCleanup)2404PopCleanupBlock();24052406// Check whether we've reached the end.2407llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");2408Builder.CreateCondBr(done, doneBB, bodyBB);2409elementPast->addIncoming(element, Builder.GetInsertBlock());24102411// Done.2412EmitBlock(doneBB);2413}24142415/// Perform partial array destruction as if in an EH cleanup. Unlike2416/// emitArrayDestroy, the element type here may still be an array type.2417static void emitPartialArrayDestroy(CodeGenFunction &CGF,2418llvm::Value *begin, llvm::Value *end,2419QualType type, CharUnits elementAlign,2420CodeGenFunction::Destroyer *destroyer) {2421llvm::Type *elemTy = CGF.ConvertTypeForMem(type);24222423// If the element type is itself an array, drill down.2424unsigned arrayDepth = 0;2425while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {2426// VLAs don't require a GEP index to walk into.2427if (!isa<VariableArrayType>(arrayType))2428arrayDepth++;2429type = arrayType->getElementType();2430}24312432if (arrayDepth) {2433llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);24342435SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);2436begin = CGF.Builder.CreateInBoundsGEP(2437elemTy, begin, gepIndices, "pad.arraybegin");2438end = CGF.Builder.CreateInBoundsGEP(2439elemTy, end, gepIndices, "pad.arrayend");2440}24412442// Destroy the array. We don't ever need an EH cleanup because we2443// assume that we're in an EH cleanup ourselves, so a throwing2444// destructor causes an immediate terminate.2445CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,2446/*checkZeroLength*/ true, /*useEHCleanup*/ false);2447}24482449namespace {2450/// RegularPartialArrayDestroy - a cleanup which performs a partial2451/// array destroy where the end pointer is regularly determined and2452/// does not need to be loaded from a local.2453class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {2454llvm::Value *ArrayBegin;2455llvm::Value *ArrayEnd;2456QualType ElementType;2457CodeGenFunction::Destroyer *Destroyer;2458CharUnits ElementAlign;2459public:2460RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,2461QualType elementType, CharUnits elementAlign,2462CodeGenFunction::Destroyer *destroyer)2463: ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),2464ElementType(elementType), Destroyer(destroyer),2465ElementAlign(elementAlign) {}24662467void Emit(CodeGenFunction &CGF, Flags flags) override {2468emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,2469ElementType, ElementAlign, Destroyer);2470}2471};24722473/// IrregularPartialArrayDestroy - a cleanup which performs a2474/// partial array destroy where the end pointer is irregularly2475/// determined and must be loaded from a local.2476class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {2477llvm::Value *ArrayBegin;2478Address ArrayEndPointer;2479QualType ElementType;2480CodeGenFunction::Destroyer *Destroyer;2481CharUnits ElementAlign;2482public:2483IrregularPartialArrayDestroy(llvm::Value *arrayBegin,2484Address arrayEndPointer,2485QualType elementType,2486CharUnits elementAlign,2487CodeGenFunction::Destroyer *destroyer)2488: ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),2489ElementType(elementType), Destroyer(destroyer),2490ElementAlign(elementAlign) {}24912492void Emit(CodeGenFunction &CGF, Flags flags) override {2493llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);2494emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,2495ElementType, ElementAlign, Destroyer);2496}2497};2498} // end anonymous namespace24992500/// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to2501/// destroy already-constructed elements of the given array. The cleanup may be2502/// popped with DeactivateCleanupBlock or PopCleanupBlock.2503///2504/// \param elementType - the immediate element type of the array;2505/// possibly still an array type2506void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,2507Address arrayEndPointer,2508QualType elementType,2509CharUnits elementAlign,2510Destroyer *destroyer) {2511pushFullExprCleanup<IrregularPartialArrayDestroy>(2512NormalAndEHCleanup, arrayBegin, arrayEndPointer, elementType,2513elementAlign, destroyer);2514}25152516/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy2517/// already-constructed elements of the given array. The cleanup2518/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.2519///2520/// \param elementType - the immediate element type of the array;2521/// possibly still an array type2522void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,2523llvm::Value *arrayEnd,2524QualType elementType,2525CharUnits elementAlign,2526Destroyer *destroyer) {2527pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,2528arrayBegin, arrayEnd,2529elementType, elementAlign,2530destroyer);2531}25322533/// Lazily declare the @llvm.lifetime.start intrinsic.2534llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {2535if (LifetimeStartFn)2536return LifetimeStartFn;2537LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),2538llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);2539return LifetimeStartFn;2540}25412542/// Lazily declare the @llvm.lifetime.end intrinsic.2543llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {2544if (LifetimeEndFn)2545return LifetimeEndFn;2546LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),2547llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);2548return LifetimeEndFn;2549}25502551namespace {2552/// A cleanup to perform a release of an object at the end of a2553/// function. This is used to balance out the incoming +1 of a2554/// ns_consumed argument when we can't reasonably do that just by2555/// not doing the initial retain for a __block argument.2556struct ConsumeARCParameter final : EHScopeStack::Cleanup {2557ConsumeARCParameter(llvm::Value *param,2558ARCPreciseLifetime_t precise)2559: Param(param), Precise(precise) {}25602561llvm::Value *Param;2562ARCPreciseLifetime_t Precise;25632564void Emit(CodeGenFunction &CGF, Flags flags) override {2565CGF.EmitARCRelease(Param, Precise);2566}2567};2568} // end anonymous namespace25692570/// Emit an alloca (or GlobalValue depending on target)2571/// for the specified parameter and set up LocalDeclMap.2572void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,2573unsigned ArgNo) {2574bool NoDebugInfo = false;2575// FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?2576assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&2577"Invalid argument to EmitParmDecl");25782579// Set the name of the parameter's initial value to make IR easier to2580// read. Don't modify the names of globals.2581if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))2582Arg.getAnyValue()->setName(D.getName());25832584QualType Ty = D.getType();25852586// Use better IR generation for certain implicit parameters.2587if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {2588// The only implicit argument a block has is its literal.2589// This may be passed as an inalloca'ed value on Windows x86.2590if (BlockInfo) {2591llvm::Value *V = Arg.isIndirect()2592? Builder.CreateLoad(Arg.getIndirectAddress())2593: Arg.getDirectValue();2594setBlockContextParameter(IPD, ArgNo, V);2595return;2596}2597// Suppressing debug info for ThreadPrivateVar parameters, else it hides2598// debug info of TLS variables.2599NoDebugInfo =2600(IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);2601}26022603Address DeclPtr = Address::invalid();2604RawAddress AllocaPtr = Address::invalid();2605bool DoStore = false;2606bool IsScalar = hasScalarEvaluationKind(Ty);2607bool UseIndirectDebugAddress = false;26082609// If we already have a pointer to the argument, reuse the input pointer.2610if (Arg.isIndirect()) {2611DeclPtr = Arg.getIndirectAddress();2612DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));2613// Indirect argument is in alloca address space, which may be different2614// from the default address space.2615auto AllocaAS = CGM.getASTAllocaAddressSpace();2616auto *V = DeclPtr.emitRawPointer(*this);2617AllocaPtr = RawAddress(V, DeclPtr.getElementType(), DeclPtr.getAlignment());26182619// For truly ABI indirect arguments -- those that are not `byval` -- store2620// the address of the argument on the stack to preserve debug information.2621ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;2622if (ArgInfo.isIndirect())2623UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();2624if (UseIndirectDebugAddress) {2625auto PtrTy = getContext().getPointerType(Ty);2626AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),2627D.getName() + ".indirect_addr");2628EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);2629}26302631auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;2632auto DestLangAS =2633getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;2634if (SrcLangAS != DestLangAS) {2635assert(getContext().getTargetAddressSpace(SrcLangAS) ==2636CGM.getDataLayout().getAllocaAddrSpace());2637auto DestAS = getContext().getTargetAddressSpace(DestLangAS);2638auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);2639DeclPtr =2640DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(2641*this, V, SrcLangAS, DestLangAS, T, true),2642DeclPtr.isKnownNonNull());2643}26442645// Push a destructor cleanup for this parameter if the ABI requires it.2646// Don't push a cleanup in a thunk for a method that will also emit a2647// cleanup.2648if (Ty->isRecordType() && !CurFuncIsThunk &&2649Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {2650if (QualType::DestructionKind DtorKind =2651D.needsDestruction(getContext())) {2652assert((DtorKind == QualType::DK_cxx_destructor ||2653DtorKind == QualType::DK_nontrivial_c_struct) &&2654"unexpected destructor type");2655pushDestroy(DtorKind, DeclPtr, Ty);2656CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =2657EHStack.stable_begin();2658}2659}2660} else {2661// Check if the parameter address is controlled by OpenMP runtime.2662Address OpenMPLocalAddr =2663getLangOpts().OpenMP2664? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)2665: Address::invalid();2666if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {2667DeclPtr = OpenMPLocalAddr;2668AllocaPtr = DeclPtr;2669} else {2670// Otherwise, create a temporary to hold the value.2671DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),2672D.getName() + ".addr", &AllocaPtr);2673}2674DoStore = true;2675}26762677llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);26782679LValue lv = MakeAddrLValue(DeclPtr, Ty);2680if (IsScalar) {2681Qualifiers qs = Ty.getQualifiers();2682if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {2683// We honor __attribute__((ns_consumed)) for types with lifetime.2684// For __strong, it's handled by just skipping the initial retain;2685// otherwise we have to balance out the initial +1 with an extra2686// cleanup to do the release at the end of the function.2687bool isConsumed = D.hasAttr<NSConsumedAttr>();26882689// If a parameter is pseudo-strong then we can omit the implicit retain.2690if (D.isARCPseudoStrong()) {2691assert(lt == Qualifiers::OCL_Strong &&2692"pseudo-strong variable isn't strong?");2693assert(qs.hasConst() && "pseudo-strong variable should be const!");2694lt = Qualifiers::OCL_ExplicitNone;2695}26962697// Load objects passed indirectly.2698if (Arg.isIndirect() && !ArgVal)2699ArgVal = Builder.CreateLoad(DeclPtr);27002701if (lt == Qualifiers::OCL_Strong) {2702if (!isConsumed) {2703if (CGM.getCodeGenOpts().OptimizationLevel == 0) {2704// use objc_storeStrong(&dest, value) for retaining the2705// object. But first, store a null into 'dest' because2706// objc_storeStrong attempts to release its old value.2707llvm::Value *Null = CGM.EmitNullConstant(D.getType());2708EmitStoreOfScalar(Null, lv, /* isInitialization */ true);2709EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);2710DoStore = false;2711}2712else2713// Don't use objc_retainBlock for block pointers, because we2714// don't want to Block_copy something just because we got it2715// as a parameter.2716ArgVal = EmitARCRetainNonBlock(ArgVal);2717}2718} else {2719// Push the cleanup for a consumed parameter.2720if (isConsumed) {2721ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()2722? ARCPreciseLifetime : ARCImpreciseLifetime);2723EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,2724precise);2725}27262727if (lt == Qualifiers::OCL_Weak) {2728EmitARCInitWeak(DeclPtr, ArgVal);2729DoStore = false; // The weak init is a store, no need to do two.2730}2731}27322733// Enter the cleanup scope.2734EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);2735}2736}27372738// Store the initial value into the alloca.2739if (DoStore)2740EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);27412742setAddrOfLocalVar(&D, DeclPtr);27432744// Emit debug info for param declarations in non-thunk functions.2745if (CGDebugInfo *DI = getDebugInfo()) {2746if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk &&2747!NoDebugInfo) {2748llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(2749&D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);2750if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))2751DI->getParamDbgMappings().insert({Var, DILocalVar});2752}2753}27542755if (D.hasAttr<AnnotateAttr>())2756EmitVarAnnotations(&D, DeclPtr.emitRawPointer(*this));27572758// We can only check return value nullability if all arguments to the2759// function satisfy their nullability preconditions. This makes it necessary2760// to emit null checks for args in the function body itself.2761if (requiresReturnValueNullabilityCheck()) {2762auto Nullability = Ty->getNullability();2763if (Nullability && *Nullability == NullabilityKind::NonNull) {2764SanitizerScope SanScope(this);2765RetValNullabilityPrecondition =2766Builder.CreateAnd(RetValNullabilityPrecondition,2767Builder.CreateIsNotNull(Arg.getAnyValue()));2768}2769}2770}27712772void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,2773CodeGenFunction *CGF) {2774if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))2775return;2776getOpenMPRuntime().emitUserDefinedReduction(CGF, D);2777}27782779void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,2780CodeGenFunction *CGF) {2781if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||2782(!LangOpts.EmitAllDecls && !D->isUsed()))2783return;2784getOpenMPRuntime().emitUserDefinedMapper(D, CGF);2785}27862787void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {2788getOpenMPRuntime().processRequiresDirective(D);2789}27902791void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {2792for (const Expr *E : D->varlists()) {2793const auto *DE = cast<DeclRefExpr>(E);2794const auto *VD = cast<VarDecl>(DE->getDecl());27952796// Skip all but globals.2797if (!VD->hasGlobalStorage())2798continue;27992800// Check if the global has been materialized yet or not. If not, we are done2801// as any later generation will utilize the OMPAllocateDeclAttr. However, if2802// we already emitted the global we might have done so before the2803// OMPAllocateDeclAttr was attached, leading to the wrong address space2804// (potentially). While not pretty, common practise is to remove the old IR2805// global and generate a new one, so we do that here too. Uses are replaced2806// properly.2807StringRef MangledName = getMangledName(VD);2808llvm::GlobalValue *Entry = GetGlobalValue(MangledName);2809if (!Entry)2810continue;28112812// We can also keep the existing global if the address space is what we2813// expect it to be, if not, it is replaced.2814QualType ASTTy = VD->getType();2815clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);2816auto TargetAS = getContext().getTargetAddressSpace(GVAS);2817if (Entry->getType()->getAddressSpace() == TargetAS)2818continue;28192820// Make a new global with the correct type / address space.2821llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);2822llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);28232824// Replace all uses of the old global with a cast. Since we mutate the type2825// in place we neeed an intermediate that takes the spot of the old entry2826// until we can create the cast.2827llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(2828getModule(), Entry->getValueType(), false,2829llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,2830llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());2831Entry->replaceAllUsesWith(DummyGV);28322833Entry->mutateType(PTy);2834llvm::Constant *NewPtrForOldDecl =2835llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(2836Entry, DummyGV->getType());28372838// Now we have a casted version of the changed global, the dummy can be2839// replaced and deleted.2840DummyGV->replaceAllUsesWith(NewPtrForOldDecl);2841DummyGV->eraseFromParent();2842}2843}28442845std::optional<CharUnits>2846CodeGenModule::getOMPAllocateAlignment(const VarDecl *VD) {2847if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {2848if (Expr *Alignment = AA->getAlignment()) {2849unsigned UserAlign =2850Alignment->EvaluateKnownConstInt(getContext()).getExtValue();2851CharUnits NaturalAlign =2852getNaturalTypeAlignment(VD->getType().getNonReferenceType());28532854// OpenMP5.1 pg 185 lines 7-102855// Each item in the align modifier list must be aligned to the maximum2856// of the specified alignment and the type's natural alignment.2857return CharUnits::fromQuantity(2858std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));2859}2860}2861return std::nullopt;2862}286328642865