Path: blob/main/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp
35269 views
//===-- llvm/lib/Target/AMDGPU/AMDGPUCallLowering.cpp - Call lowering -----===//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/// \file9/// This file implements the lowering of LLVM calls to machine code calls for10/// GlobalISel.11///12//===----------------------------------------------------------------------===//1314#include "AMDGPUCallLowering.h"15#include "AMDGPU.h"16#include "AMDGPULegalizerInfo.h"17#include "AMDGPUTargetMachine.h"18#include "SIMachineFunctionInfo.h"19#include "SIRegisterInfo.h"20#include "llvm/CodeGen/Analysis.h"21#include "llvm/CodeGen/FunctionLoweringInfo.h"22#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"23#include "llvm/CodeGen/MachineFrameInfo.h"24#include "llvm/IR/IntrinsicsAMDGPU.h"2526#define DEBUG_TYPE "amdgpu-call-lowering"2728using namespace llvm;2930namespace {3132/// Wrapper around extendRegister to ensure we extend to a full 32-bit register.33static Register extendRegisterMin32(CallLowering::ValueHandler &Handler,34Register ValVReg, const CCValAssign &VA) {35if (VA.getLocVT().getSizeInBits() < 32) {36// 16-bit types are reported as legal for 32-bit registers. We need to37// extend and do a 32-bit copy to avoid the verifier complaining about it.38return Handler.MIRBuilder.buildAnyExt(LLT::scalar(32), ValVReg).getReg(0);39}4041return Handler.extendRegister(ValVReg, VA);42}4344struct AMDGPUOutgoingValueHandler : public CallLowering::OutgoingValueHandler {45AMDGPUOutgoingValueHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI,46MachineInstrBuilder MIB)47: OutgoingValueHandler(B, MRI), MIB(MIB) {}4849MachineInstrBuilder MIB;5051Register getStackAddress(uint64_t Size, int64_t Offset,52MachinePointerInfo &MPO,53ISD::ArgFlagsTy Flags) override {54llvm_unreachable("not implemented");55}5657void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,58const MachinePointerInfo &MPO,59const CCValAssign &VA) override {60llvm_unreachable("not implemented");61}6263void assignValueToReg(Register ValVReg, Register PhysReg,64const CCValAssign &VA) override {65Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);6667// If this is a scalar return, insert a readfirstlane just in case the value68// ends up in a VGPR.69// FIXME: Assert this is a shader return.70const SIRegisterInfo *TRI71= static_cast<const SIRegisterInfo *>(MRI.getTargetRegisterInfo());72if (TRI->isSGPRReg(MRI, PhysReg)) {73LLT Ty = MRI.getType(ExtReg);74LLT S32 = LLT::scalar(32);75if (Ty != S32) {76// FIXME: We should probably support readfirstlane intrinsics with all77// legal 32-bit types.78assert(Ty.getSizeInBits() == 32);79if (Ty.isPointer())80ExtReg = MIRBuilder.buildPtrToInt(S32, ExtReg).getReg(0);81else82ExtReg = MIRBuilder.buildBitcast(S32, ExtReg).getReg(0);83}8485auto ToSGPR = MIRBuilder86.buildIntrinsic(Intrinsic::amdgcn_readfirstlane,87{MRI.getType(ExtReg)})88.addReg(ExtReg);89ExtReg = ToSGPR.getReg(0);90}9192MIRBuilder.buildCopy(PhysReg, ExtReg);93MIB.addUse(PhysReg, RegState::Implicit);94}95};9697struct AMDGPUIncomingArgHandler : public CallLowering::IncomingValueHandler {98uint64_t StackUsed = 0;99100AMDGPUIncomingArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)101: IncomingValueHandler(B, MRI) {}102103Register getStackAddress(uint64_t Size, int64_t Offset,104MachinePointerInfo &MPO,105ISD::ArgFlagsTy Flags) override {106auto &MFI = MIRBuilder.getMF().getFrameInfo();107108// Byval is assumed to be writable memory, but other stack passed arguments109// are not.110const bool IsImmutable = !Flags.isByVal();111int FI = MFI.CreateFixedObject(Size, Offset, IsImmutable);112MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);113auto AddrReg = MIRBuilder.buildFrameIndex(114LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32), FI);115StackUsed = std::max(StackUsed, Size + Offset);116return AddrReg.getReg(0);117}118119void assignValueToReg(Register ValVReg, Register PhysReg,120const CCValAssign &VA) override {121markPhysRegUsed(PhysReg);122123if (VA.getLocVT().getSizeInBits() < 32) {124// 16-bit types are reported as legal for 32-bit registers. We need to do125// a 32-bit copy, and truncate to avoid the verifier complaining about it.126auto Copy = MIRBuilder.buildCopy(LLT::scalar(32), PhysReg);127128// If we have signext/zeroext, it applies to the whole 32-bit register129// before truncation.130auto Extended =131buildExtensionHint(VA, Copy.getReg(0), LLT(VA.getLocVT()));132MIRBuilder.buildTrunc(ValVReg, Extended);133return;134}135136IncomingValueHandler::assignValueToReg(ValVReg, PhysReg, VA);137}138139void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,140const MachinePointerInfo &MPO,141const CCValAssign &VA) override {142MachineFunction &MF = MIRBuilder.getMF();143144auto MMO = MF.getMachineMemOperand(145MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, MemTy,146inferAlignFromPtrInfo(MF, MPO));147MIRBuilder.buildLoad(ValVReg, Addr, *MMO);148}149150/// How the physical register gets marked varies between formal151/// parameters (it's a basic-block live-in), and a call instruction152/// (it's an implicit-def of the BL).153virtual void markPhysRegUsed(unsigned PhysReg) = 0;154};155156struct FormalArgHandler : public AMDGPUIncomingArgHandler {157FormalArgHandler(MachineIRBuilder &B, MachineRegisterInfo &MRI)158: AMDGPUIncomingArgHandler(B, MRI) {}159160void markPhysRegUsed(unsigned PhysReg) override {161MIRBuilder.getMBB().addLiveIn(PhysReg);162}163};164165struct CallReturnHandler : public AMDGPUIncomingArgHandler {166CallReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,167MachineInstrBuilder MIB)168: AMDGPUIncomingArgHandler(MIRBuilder, MRI), MIB(MIB) {}169170void markPhysRegUsed(unsigned PhysReg) override {171MIB.addDef(PhysReg, RegState::Implicit);172}173174MachineInstrBuilder MIB;175};176177struct AMDGPUOutgoingArgHandler : public AMDGPUOutgoingValueHandler {178/// For tail calls, the byte offset of the call's argument area from the179/// callee's. Unused elsewhere.180int FPDiff;181182// Cache the SP register vreg if we need it more than once in this call site.183Register SPReg;184185bool IsTailCall;186187AMDGPUOutgoingArgHandler(MachineIRBuilder &MIRBuilder,188MachineRegisterInfo &MRI, MachineInstrBuilder MIB,189bool IsTailCall = false, int FPDiff = 0)190: AMDGPUOutgoingValueHandler(MIRBuilder, MRI, MIB), FPDiff(FPDiff),191IsTailCall(IsTailCall) {}192193Register getStackAddress(uint64_t Size, int64_t Offset,194MachinePointerInfo &MPO,195ISD::ArgFlagsTy Flags) override {196MachineFunction &MF = MIRBuilder.getMF();197const LLT PtrTy = LLT::pointer(AMDGPUAS::PRIVATE_ADDRESS, 32);198const LLT S32 = LLT::scalar(32);199200if (IsTailCall) {201Offset += FPDiff;202int FI = MF.getFrameInfo().CreateFixedObject(Size, Offset, true);203auto FIReg = MIRBuilder.buildFrameIndex(PtrTy, FI);204MPO = MachinePointerInfo::getFixedStack(MF, FI);205return FIReg.getReg(0);206}207208const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();209210if (!SPReg) {211const GCNSubtarget &ST = MIRBuilder.getMF().getSubtarget<GCNSubtarget>();212if (ST.enableFlatScratch()) {213// The stack is accessed unswizzled, so we can use a regular copy.214SPReg = MIRBuilder.buildCopy(PtrTy,215MFI->getStackPtrOffsetReg()).getReg(0);216} else {217// The address we produce here, without knowing the use context, is going218// to be interpreted as a vector address, so we need to convert to a219// swizzled address.220SPReg = MIRBuilder.buildInstr(AMDGPU::G_AMDGPU_WAVE_ADDRESS, {PtrTy},221{MFI->getStackPtrOffsetReg()}).getReg(0);222}223}224225auto OffsetReg = MIRBuilder.buildConstant(S32, Offset);226227auto AddrReg = MIRBuilder.buildPtrAdd(PtrTy, SPReg, OffsetReg);228MPO = MachinePointerInfo::getStack(MF, Offset);229return AddrReg.getReg(0);230}231232void assignValueToReg(Register ValVReg, Register PhysReg,233const CCValAssign &VA) override {234MIB.addUse(PhysReg, RegState::Implicit);235Register ExtReg = extendRegisterMin32(*this, ValVReg, VA);236MIRBuilder.buildCopy(PhysReg, ExtReg);237}238239void assignValueToAddress(Register ValVReg, Register Addr, LLT MemTy,240const MachinePointerInfo &MPO,241const CCValAssign &VA) override {242MachineFunction &MF = MIRBuilder.getMF();243uint64_t LocMemOffset = VA.getLocMemOffset();244const auto &ST = MF.getSubtarget<GCNSubtarget>();245246auto MMO = MF.getMachineMemOperand(247MPO, MachineMemOperand::MOStore, MemTy,248commonAlignment(ST.getStackAlignment(), LocMemOffset));249MIRBuilder.buildStore(ValVReg, Addr, *MMO);250}251252void assignValueToAddress(const CallLowering::ArgInfo &Arg,253unsigned ValRegIndex, Register Addr, LLT MemTy,254const MachinePointerInfo &MPO,255const CCValAssign &VA) override {256Register ValVReg = VA.getLocInfo() != CCValAssign::LocInfo::FPExt257? extendRegister(Arg.Regs[ValRegIndex], VA)258: Arg.Regs[ValRegIndex];259assignValueToAddress(ValVReg, Addr, MemTy, MPO, VA);260}261};262} // anonymous namespace263264AMDGPUCallLowering::AMDGPUCallLowering(const AMDGPUTargetLowering &TLI)265: CallLowering(&TLI) {266}267268// FIXME: Compatibility shim269static ISD::NodeType extOpcodeToISDExtOpcode(unsigned MIOpc) {270switch (MIOpc) {271case TargetOpcode::G_SEXT:272return ISD::SIGN_EXTEND;273case TargetOpcode::G_ZEXT:274return ISD::ZERO_EXTEND;275case TargetOpcode::G_ANYEXT:276return ISD::ANY_EXTEND;277default:278llvm_unreachable("not an extend opcode");279}280}281282bool AMDGPUCallLowering::canLowerReturn(MachineFunction &MF,283CallingConv::ID CallConv,284SmallVectorImpl<BaseArgInfo> &Outs,285bool IsVarArg) const {286// For shaders. Vector types should be explicitly handled by CC.287if (AMDGPU::isEntryFunctionCC(CallConv))288return true;289290SmallVector<CCValAssign, 16> ArgLocs;291const SITargetLowering &TLI = *getTLI<SITargetLowering>();292CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs,293MF.getFunction().getContext());294295return checkReturn(CCInfo, Outs, TLI.CCAssignFnForReturn(CallConv, IsVarArg));296}297298/// Lower the return value for the already existing \p Ret. This assumes that299/// \p B's insertion point is correct.300bool AMDGPUCallLowering::lowerReturnVal(MachineIRBuilder &B,301const Value *Val, ArrayRef<Register> VRegs,302MachineInstrBuilder &Ret) const {303if (!Val)304return true;305306auto &MF = B.getMF();307const auto &F = MF.getFunction();308const DataLayout &DL = MF.getDataLayout();309MachineRegisterInfo *MRI = B.getMRI();310LLVMContext &Ctx = F.getContext();311312CallingConv::ID CC = F.getCallingConv();313const SITargetLowering &TLI = *getTLI<SITargetLowering>();314315SmallVector<EVT, 8> SplitEVTs;316ComputeValueVTs(TLI, DL, Val->getType(), SplitEVTs);317assert(VRegs.size() == SplitEVTs.size() &&318"For each split Type there should be exactly one VReg.");319320SmallVector<ArgInfo, 8> SplitRetInfos;321322for (unsigned i = 0; i < SplitEVTs.size(); ++i) {323EVT VT = SplitEVTs[i];324Register Reg = VRegs[i];325ArgInfo RetInfo(Reg, VT.getTypeForEVT(Ctx), 0);326setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);327328if (VT.isScalarInteger()) {329unsigned ExtendOp = TargetOpcode::G_ANYEXT;330if (RetInfo.Flags[0].isSExt()) {331assert(RetInfo.Regs.size() == 1 && "expect only simple return values");332ExtendOp = TargetOpcode::G_SEXT;333} else if (RetInfo.Flags[0].isZExt()) {334assert(RetInfo.Regs.size() == 1 && "expect only simple return values");335ExtendOp = TargetOpcode::G_ZEXT;336}337338EVT ExtVT = TLI.getTypeForExtReturn(Ctx, VT,339extOpcodeToISDExtOpcode(ExtendOp));340if (ExtVT != VT) {341RetInfo.Ty = ExtVT.getTypeForEVT(Ctx);342LLT ExtTy = getLLTForType(*RetInfo.Ty, DL);343Reg = B.buildInstr(ExtendOp, {ExtTy}, {Reg}).getReg(0);344}345}346347if (Reg != RetInfo.Regs[0]) {348RetInfo.Regs[0] = Reg;349// Reset the arg flags after modifying Reg.350setArgFlags(RetInfo, AttributeList::ReturnIndex, DL, F);351}352353splitToValueTypes(RetInfo, SplitRetInfos, DL, CC);354}355356CCAssignFn *AssignFn = TLI.CCAssignFnForReturn(CC, F.isVarArg());357358OutgoingValueAssigner Assigner(AssignFn);359AMDGPUOutgoingValueHandler RetHandler(B, *MRI, Ret);360return determineAndHandleAssignments(RetHandler, Assigner, SplitRetInfos, B,361CC, F.isVarArg());362}363364bool AMDGPUCallLowering::lowerReturn(MachineIRBuilder &B, const Value *Val,365ArrayRef<Register> VRegs,366FunctionLoweringInfo &FLI) const {367368MachineFunction &MF = B.getMF();369SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();370MFI->setIfReturnsVoid(!Val);371372assert(!Val == VRegs.empty() && "Return value without a vreg");373374CallingConv::ID CC = B.getMF().getFunction().getCallingConv();375const bool IsShader = AMDGPU::isShader(CC);376const bool IsWaveEnd =377(IsShader && MFI->returnsVoid()) || AMDGPU::isKernel(CC);378if (IsWaveEnd) {379B.buildInstr(AMDGPU::S_ENDPGM)380.addImm(0);381return true;382}383384unsigned ReturnOpc =385IsShader ? AMDGPU::SI_RETURN_TO_EPILOG : AMDGPU::SI_RETURN;386auto Ret = B.buildInstrNoInsert(ReturnOpc);387388if (!FLI.CanLowerReturn)389insertSRetStores(B, Val->getType(), VRegs, FLI.DemoteRegister);390else if (!lowerReturnVal(B, Val, VRegs, Ret))391return false;392393// TODO: Handle CalleeSavedRegsViaCopy.394395B.insertInstr(Ret);396return true;397}398399void AMDGPUCallLowering::lowerParameterPtr(Register DstReg, MachineIRBuilder &B,400uint64_t Offset) const {401MachineFunction &MF = B.getMF();402const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();403MachineRegisterInfo &MRI = MF.getRegInfo();404Register KernArgSegmentPtr =405MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);406Register KernArgSegmentVReg = MRI.getLiveInVirtReg(KernArgSegmentPtr);407408auto OffsetReg = B.buildConstant(LLT::scalar(64), Offset);409410B.buildPtrAdd(DstReg, KernArgSegmentVReg, OffsetReg);411}412413void AMDGPUCallLowering::lowerParameter(MachineIRBuilder &B, ArgInfo &OrigArg,414uint64_t Offset,415Align Alignment) const {416MachineFunction &MF = B.getMF();417const Function &F = MF.getFunction();418const DataLayout &DL = F.getDataLayout();419MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);420421LLT PtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);422423SmallVector<ArgInfo, 32> SplitArgs;424SmallVector<uint64_t> FieldOffsets;425splitToValueTypes(OrigArg, SplitArgs, DL, F.getCallingConv(), &FieldOffsets);426427unsigned Idx = 0;428for (ArgInfo &SplitArg : SplitArgs) {429Register PtrReg = B.getMRI()->createGenericVirtualRegister(PtrTy);430lowerParameterPtr(PtrReg, B, Offset + FieldOffsets[Idx]);431432LLT ArgTy = getLLTForType(*SplitArg.Ty, DL);433if (SplitArg.Flags[0].isPointer()) {434// Compensate for losing pointeriness in splitValueTypes.435LLT PtrTy = LLT::pointer(SplitArg.Flags[0].getPointerAddrSpace(),436ArgTy.getScalarSizeInBits());437ArgTy = ArgTy.isVector() ? LLT::vector(ArgTy.getElementCount(), PtrTy)438: PtrTy;439}440441MachineMemOperand *MMO = MF.getMachineMemOperand(442PtrInfo,443MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |444MachineMemOperand::MOInvariant,445ArgTy, commonAlignment(Alignment, FieldOffsets[Idx]));446447assert(SplitArg.Regs.size() == 1);448449B.buildLoad(SplitArg.Regs[0], PtrReg, *MMO);450++Idx;451}452}453454// Allocate special inputs passed in user SGPRs.455static void allocateHSAUserSGPRs(CCState &CCInfo,456MachineIRBuilder &B,457MachineFunction &MF,458const SIRegisterInfo &TRI,459SIMachineFunctionInfo &Info) {460// FIXME: How should these inputs interact with inreg / custom SGPR inputs?461const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();462if (UserSGPRInfo.hasPrivateSegmentBuffer()) {463Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);464MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);465CCInfo.AllocateReg(PrivateSegmentBufferReg);466}467468if (UserSGPRInfo.hasDispatchPtr()) {469Register DispatchPtrReg = Info.addDispatchPtr(TRI);470MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);471CCInfo.AllocateReg(DispatchPtrReg);472}473474const Module *M = MF.getFunction().getParent();475if (UserSGPRInfo.hasQueuePtr() &&476AMDGPU::getAMDHSACodeObjectVersion(*M) < AMDGPU::AMDHSA_COV5) {477Register QueuePtrReg = Info.addQueuePtr(TRI);478MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);479CCInfo.AllocateReg(QueuePtrReg);480}481482if (UserSGPRInfo.hasKernargSegmentPtr()) {483MachineRegisterInfo &MRI = MF.getRegInfo();484Register InputPtrReg = Info.addKernargSegmentPtr(TRI);485const LLT P4 = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);486Register VReg = MRI.createGenericVirtualRegister(P4);487MRI.addLiveIn(InputPtrReg, VReg);488B.getMBB().addLiveIn(InputPtrReg);489B.buildCopy(VReg, InputPtrReg);490CCInfo.AllocateReg(InputPtrReg);491}492493if (UserSGPRInfo.hasDispatchID()) {494Register DispatchIDReg = Info.addDispatchID(TRI);495MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);496CCInfo.AllocateReg(DispatchIDReg);497}498499if (UserSGPRInfo.hasFlatScratchInit()) {500Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);501MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);502CCInfo.AllocateReg(FlatScratchInitReg);503}504505// TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read506// these from the dispatch pointer.507}508509bool AMDGPUCallLowering::lowerFormalArgumentsKernel(510MachineIRBuilder &B, const Function &F,511ArrayRef<ArrayRef<Register>> VRegs) const {512MachineFunction &MF = B.getMF();513const GCNSubtarget *Subtarget = &MF.getSubtarget<GCNSubtarget>();514MachineRegisterInfo &MRI = MF.getRegInfo();515SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();516const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();517const SITargetLowering &TLI = *getTLI<SITargetLowering>();518const DataLayout &DL = F.getDataLayout();519520SmallVector<CCValAssign, 16> ArgLocs;521CCState CCInfo(F.getCallingConv(), F.isVarArg(), MF, ArgLocs, F.getContext());522523allocateHSAUserSGPRs(CCInfo, B, MF, *TRI, *Info);524525unsigned i = 0;526const Align KernArgBaseAlign(16);527const unsigned BaseOffset = Subtarget->getExplicitKernelArgOffset();528uint64_t ExplicitArgOffset = 0;529530// TODO: Align down to dword alignment and extract bits for extending loads.531for (auto &Arg : F.args()) {532const bool IsByRef = Arg.hasByRefAttr();533Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();534unsigned AllocSize = DL.getTypeAllocSize(ArgTy);535if (AllocSize == 0)536continue;537538MaybeAlign ParamAlign = IsByRef ? Arg.getParamAlign() : std::nullopt;539Align ABIAlign = DL.getValueOrABITypeAlignment(ParamAlign, ArgTy);540541uint64_t ArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + BaseOffset;542ExplicitArgOffset = alignTo(ExplicitArgOffset, ABIAlign) + AllocSize;543544if (Arg.use_empty()) {545++i;546continue;547}548549Align Alignment = commonAlignment(KernArgBaseAlign, ArgOffset);550551if (IsByRef) {552unsigned ByRefAS = cast<PointerType>(Arg.getType())->getAddressSpace();553554assert(VRegs[i].size() == 1 &&555"expected only one register for byval pointers");556if (ByRefAS == AMDGPUAS::CONSTANT_ADDRESS) {557lowerParameterPtr(VRegs[i][0], B, ArgOffset);558} else {559const LLT ConstPtrTy = LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64);560Register PtrReg = MRI.createGenericVirtualRegister(ConstPtrTy);561lowerParameterPtr(PtrReg, B, ArgOffset);562563B.buildAddrSpaceCast(VRegs[i][0], PtrReg);564}565} else {566ArgInfo OrigArg(VRegs[i], Arg, i);567const unsigned OrigArgIdx = i + AttributeList::FirstArgIndex;568setArgFlags(OrigArg, OrigArgIdx, DL, F);569lowerParameter(B, OrigArg, ArgOffset, Alignment);570}571572++i;573}574575TLI.allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);576TLI.allocateSystemSGPRs(CCInfo, MF, *Info, F.getCallingConv(), false);577return true;578}579580bool AMDGPUCallLowering::lowerFormalArguments(581MachineIRBuilder &B, const Function &F, ArrayRef<ArrayRef<Register>> VRegs,582FunctionLoweringInfo &FLI) const {583CallingConv::ID CC = F.getCallingConv();584585// The infrastructure for normal calling convention lowering is essentially586// useless for kernels. We want to avoid any kind of legalization or argument587// splitting.588if (CC == CallingConv::AMDGPU_KERNEL)589return lowerFormalArgumentsKernel(B, F, VRegs);590591const bool IsGraphics = AMDGPU::isGraphics(CC);592const bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CC);593594MachineFunction &MF = B.getMF();595MachineBasicBlock &MBB = B.getMBB();596MachineRegisterInfo &MRI = MF.getRegInfo();597SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();598const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();599const SIRegisterInfo *TRI = Subtarget.getRegisterInfo();600const DataLayout &DL = F.getDataLayout();601602SmallVector<CCValAssign, 16> ArgLocs;603CCState CCInfo(CC, F.isVarArg(), MF, ArgLocs, F.getContext());604const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();605606if (UserSGPRInfo.hasImplicitBufferPtr()) {607Register ImplicitBufferPtrReg = Info->addImplicitBufferPtr(*TRI);608MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);609CCInfo.AllocateReg(ImplicitBufferPtrReg);610}611612// FIXME: This probably isn't defined for mesa613if (UserSGPRInfo.hasFlatScratchInit() && !Subtarget.isAmdPalOS()) {614Register FlatScratchInitReg = Info->addFlatScratchInit(*TRI);615MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);616CCInfo.AllocateReg(FlatScratchInitReg);617}618619SmallVector<ArgInfo, 32> SplitArgs;620unsigned Idx = 0;621unsigned PSInputNum = 0;622623// Insert the hidden sret parameter if the return value won't fit in the624// return registers.625if (!FLI.CanLowerReturn)626insertSRetIncomingArgument(F, SplitArgs, FLI.DemoteRegister, MRI, DL);627628for (auto &Arg : F.args()) {629if (DL.getTypeStoreSize(Arg.getType()) == 0)630continue;631632const bool InReg = Arg.hasAttribute(Attribute::InReg);633634if (Arg.hasAttribute(Attribute::SwiftSelf) ||635Arg.hasAttribute(Attribute::SwiftError) ||636Arg.hasAttribute(Attribute::Nest))637return false;638639if (CC == CallingConv::AMDGPU_PS && !InReg && PSInputNum <= 15) {640const bool ArgUsed = !Arg.use_empty();641bool SkipArg = !ArgUsed && !Info->isPSInputAllocated(PSInputNum);642643if (!SkipArg) {644Info->markPSInputAllocated(PSInputNum);645if (ArgUsed)646Info->markPSInputEnabled(PSInputNum);647}648649++PSInputNum;650651if (SkipArg) {652for (Register R : VRegs[Idx])653B.buildUndef(R);654655++Idx;656continue;657}658}659660ArgInfo OrigArg(VRegs[Idx], Arg, Idx);661const unsigned OrigArgIdx = Idx + AttributeList::FirstArgIndex;662setArgFlags(OrigArg, OrigArgIdx, DL, F);663664splitToValueTypes(OrigArg, SplitArgs, DL, CC);665++Idx;666}667668// At least one interpolation mode must be enabled or else the GPU will669// hang.670//671// Check PSInputAddr instead of PSInputEnable. The idea is that if the user672// set PSInputAddr, the user wants to enable some bits after the compilation673// based on run-time states. Since we can't know what the final PSInputEna674// will look like, so we shouldn't do anything here and the user should take675// responsibility for the correct programming.676//677// Otherwise, the following restrictions apply:678// - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.679// - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be680// enabled too.681if (CC == CallingConv::AMDGPU_PS) {682if ((Info->getPSInputAddr() & 0x7F) == 0 ||683((Info->getPSInputAddr() & 0xF) == 0 &&684Info->isPSInputAllocated(11))) {685CCInfo.AllocateReg(AMDGPU::VGPR0);686CCInfo.AllocateReg(AMDGPU::VGPR1);687Info->markPSInputAllocated(0);688Info->markPSInputEnabled(0);689}690691if (Subtarget.isAmdPalOS()) {692// For isAmdPalOS, the user does not enable some bits after compilation693// based on run-time states; the register values being generated here are694// the final ones set in hardware. Therefore we need to apply the695// workaround to PSInputAddr and PSInputEnable together. (The case where696// a bit is set in PSInputAddr but not PSInputEnable is where the frontend697// set up an input arg for a particular interpolation mode, but nothing698// uses that input arg. Really we should have an earlier pass that removes699// such an arg.)700unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();701if ((PsInputBits & 0x7F) == 0 ||702((PsInputBits & 0xF) == 0 &&703(PsInputBits >> 11 & 1)))704Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));705}706}707708const SITargetLowering &TLI = *getTLI<SITargetLowering>();709CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CC, F.isVarArg());710711if (!MBB.empty())712B.setInstr(*MBB.begin());713714if (!IsEntryFunc && !IsGraphics) {715// For the fixed ABI, pass workitem IDs in the last argument register.716TLI.allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);717718if (!Subtarget.enableFlatScratch())719CCInfo.AllocateReg(Info->getScratchRSrcReg());720TLI.allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);721}722723IncomingValueAssigner Assigner(AssignFn);724if (!determineAssignments(Assigner, SplitArgs, CCInfo))725return false;726727FormalArgHandler Handler(B, MRI);728if (!handleAssignments(Handler, SplitArgs, CCInfo, ArgLocs, B))729return false;730731uint64_t StackSize = Assigner.StackSize;732733// Start adding system SGPRs.734if (IsEntryFunc)735TLI.allocateSystemSGPRs(CCInfo, MF, *Info, CC, IsGraphics);736737// When we tail call, we need to check if the callee's arguments will fit on738// the caller's stack. So, whenever we lower formal arguments, we should keep739// track of this information, since we might lower a tail call in this740// function later.741Info->setBytesInStackArgArea(StackSize);742743// Move back to the end of the basic block.744B.setMBB(MBB);745746return true;747}748749bool AMDGPUCallLowering::passSpecialInputs(MachineIRBuilder &MIRBuilder,750CCState &CCInfo,751SmallVectorImpl<std::pair<MCRegister, Register>> &ArgRegs,752CallLoweringInfo &Info) const {753MachineFunction &MF = MIRBuilder.getMF();754755// If there's no call site, this doesn't correspond to a call from the IR and756// doesn't need implicit inputs.757if (!Info.CB)758return true;759760const AMDGPUFunctionArgInfo *CalleeArgInfo761= &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;762763const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();764const AMDGPUFunctionArgInfo &CallerArgInfo = MFI->getArgInfo();765766767// TODO: Unify with private memory register handling. This is complicated by768// the fact that at least in kernels, the input argument is not necessarily769// in the same location as the input.770AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {771AMDGPUFunctionArgInfo::DISPATCH_PTR,772AMDGPUFunctionArgInfo::QUEUE_PTR,773AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,774AMDGPUFunctionArgInfo::DISPATCH_ID,775AMDGPUFunctionArgInfo::WORKGROUP_ID_X,776AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,777AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,778AMDGPUFunctionArgInfo::LDS_KERNEL_ID,779};780781static constexpr StringLiteral ImplicitAttrNames[] = {782"amdgpu-no-dispatch-ptr",783"amdgpu-no-queue-ptr",784"amdgpu-no-implicitarg-ptr",785"amdgpu-no-dispatch-id",786"amdgpu-no-workgroup-id-x",787"amdgpu-no-workgroup-id-y",788"amdgpu-no-workgroup-id-z",789"amdgpu-no-lds-kernel-id",790};791792MachineRegisterInfo &MRI = MF.getRegInfo();793794const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();795const AMDGPULegalizerInfo *LI796= static_cast<const AMDGPULegalizerInfo*>(ST.getLegalizerInfo());797798unsigned I = 0;799for (auto InputID : InputRegs) {800const ArgDescriptor *OutgoingArg;801const TargetRegisterClass *ArgRC;802LLT ArgTy;803804// If the callee does not use the attribute value, skip copying the value.805if (Info.CB->hasFnAttr(ImplicitAttrNames[I++]))806continue;807808std::tie(OutgoingArg, ArgRC, ArgTy) =809CalleeArgInfo->getPreloadedValue(InputID);810if (!OutgoingArg)811continue;812813const ArgDescriptor *IncomingArg;814const TargetRegisterClass *IncomingArgRC;815std::tie(IncomingArg, IncomingArgRC, ArgTy) =816CallerArgInfo.getPreloadedValue(InputID);817assert(IncomingArgRC == ArgRC);818819Register InputReg = MRI.createGenericVirtualRegister(ArgTy);820821if (IncomingArg) {822LI->loadInputValue(InputReg, MIRBuilder, IncomingArg, ArgRC, ArgTy);823} else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {824LI->getImplicitArgPtr(InputReg, MRI, MIRBuilder);825} else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {826std::optional<uint32_t> Id =827AMDGPUMachineFunction::getLDSKernelIdMetadata(MF.getFunction());828if (Id) {829MIRBuilder.buildConstant(InputReg, *Id);830} else {831MIRBuilder.buildUndef(InputReg);832}833} else {834// We may have proven the input wasn't needed, although the ABI is835// requiring it. We just need to allocate the register appropriately.836MIRBuilder.buildUndef(InputReg);837}838839if (OutgoingArg->isRegister()) {840ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);841if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))842report_fatal_error("failed to allocate implicit input argument");843} else {844LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");845return false;846}847}848849// Pack workitem IDs into a single register or pass it as is if already850// packed.851const ArgDescriptor *OutgoingArg;852const TargetRegisterClass *ArgRC;853LLT ArgTy;854855std::tie(OutgoingArg, ArgRC, ArgTy) =856CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);857if (!OutgoingArg)858std::tie(OutgoingArg, ArgRC, ArgTy) =859CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);860if (!OutgoingArg)861std::tie(OutgoingArg, ArgRC, ArgTy) =862CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);863if (!OutgoingArg)864return false;865866auto WorkitemIDX =867CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);868auto WorkitemIDY =869CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);870auto WorkitemIDZ =871CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);872873const ArgDescriptor *IncomingArgX = std::get<0>(WorkitemIDX);874const ArgDescriptor *IncomingArgY = std::get<0>(WorkitemIDY);875const ArgDescriptor *IncomingArgZ = std::get<0>(WorkitemIDZ);876const LLT S32 = LLT::scalar(32);877878const bool NeedWorkItemIDX = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-x");879const bool NeedWorkItemIDY = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-y");880const bool NeedWorkItemIDZ = !Info.CB->hasFnAttr("amdgpu-no-workitem-id-z");881882// If incoming ids are not packed we need to pack them.883// FIXME: Should consider known workgroup size to eliminate known 0 cases.884Register InputReg;885if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&886NeedWorkItemIDX) {887if (ST.getMaxWorkitemID(MF.getFunction(), 0) != 0) {888InputReg = MRI.createGenericVirtualRegister(S32);889LI->loadInputValue(InputReg, MIRBuilder, IncomingArgX,890std::get<1>(WorkitemIDX), std::get<2>(WorkitemIDX));891} else {892InputReg = MIRBuilder.buildConstant(S32, 0).getReg(0);893}894}895896if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&897NeedWorkItemIDY && ST.getMaxWorkitemID(MF.getFunction(), 1) != 0) {898Register Y = MRI.createGenericVirtualRegister(S32);899LI->loadInputValue(Y, MIRBuilder, IncomingArgY, std::get<1>(WorkitemIDY),900std::get<2>(WorkitemIDY));901902Y = MIRBuilder.buildShl(S32, Y, MIRBuilder.buildConstant(S32, 10)).getReg(0);903InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Y).getReg(0) : Y;904}905906if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&907NeedWorkItemIDZ && ST.getMaxWorkitemID(MF.getFunction(), 2) != 0) {908Register Z = MRI.createGenericVirtualRegister(S32);909LI->loadInputValue(Z, MIRBuilder, IncomingArgZ, std::get<1>(WorkitemIDZ),910std::get<2>(WorkitemIDZ));911912Z = MIRBuilder.buildShl(S32, Z, MIRBuilder.buildConstant(S32, 20)).getReg(0);913InputReg = InputReg ? MIRBuilder.buildOr(S32, InputReg, Z).getReg(0) : Z;914}915916if (!InputReg &&917(NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {918InputReg = MRI.createGenericVirtualRegister(S32);919if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {920// We're in a situation where the outgoing function requires the workitem921// ID, but the calling function does not have it (e.g a graphics function922// calling a C calling convention function). This is illegal, but we need923// to produce something.924MIRBuilder.buildUndef(InputReg);925} else {926// Workitem ids are already packed, any of present incoming arguments will927// carry all required fields.928ArgDescriptor IncomingArg = ArgDescriptor::createArg(929IncomingArgX ? *IncomingArgX :930IncomingArgY ? *IncomingArgY : *IncomingArgZ, ~0u);931LI->loadInputValue(InputReg, MIRBuilder, &IncomingArg,932&AMDGPU::VGPR_32RegClass, S32);933}934}935936if (OutgoingArg->isRegister()) {937if (InputReg)938ArgRegs.emplace_back(OutgoingArg->getRegister(), InputReg);939940if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))941report_fatal_error("failed to allocate implicit input argument");942} else {943LLVM_DEBUG(dbgs() << "Unhandled stack passed implicit input argument\n");944return false;945}946947return true;948}949950/// Returns a pair containing the fixed CCAssignFn and the vararg CCAssignFn for951/// CC.952static std::pair<CCAssignFn *, CCAssignFn *>953getAssignFnsForCC(CallingConv::ID CC, const SITargetLowering &TLI) {954return {TLI.CCAssignFnForCall(CC, false), TLI.CCAssignFnForCall(CC, true)};955}956957static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect,958bool IsTailCall, bool isWave32,959CallingConv::ID CC) {960// For calls to amdgpu_cs_chain functions, the address is known to be uniform.961assert((AMDGPU::isChainCC(CC) || !IsIndirect || !IsTailCall) &&962"Indirect calls can't be tail calls, "963"because the address can be divergent");964if (!IsTailCall)965return AMDGPU::G_SI_CALL;966967if (AMDGPU::isChainCC(CC))968return isWave32 ? AMDGPU::SI_CS_CHAIN_TC_W32 : AMDGPU::SI_CS_CHAIN_TC_W64;969970return CC == CallingConv::AMDGPU_Gfx ? AMDGPU::SI_TCRETURN_GFX :971AMDGPU::SI_TCRETURN;972}973974// Add operands to call instruction to track the callee.975static bool addCallTargetOperands(MachineInstrBuilder &CallInst,976MachineIRBuilder &MIRBuilder,977AMDGPUCallLowering::CallLoweringInfo &Info) {978if (Info.Callee.isReg()) {979CallInst.addReg(Info.Callee.getReg());980CallInst.addImm(0);981} else if (Info.Callee.isGlobal() && Info.Callee.getOffset() == 0) {982// The call lowering lightly assumed we can directly encode a call target in983// the instruction, which is not the case. Materialize the address here.984const GlobalValue *GV = Info.Callee.getGlobal();985auto Ptr = MIRBuilder.buildGlobalValue(986LLT::pointer(GV->getAddressSpace(), 64), GV);987CallInst.addReg(Ptr.getReg(0));988CallInst.add(Info.Callee);989} else990return false;991992return true;993}994995bool AMDGPUCallLowering::doCallerAndCalleePassArgsTheSameWay(996CallLoweringInfo &Info, MachineFunction &MF,997SmallVectorImpl<ArgInfo> &InArgs) const {998const Function &CallerF = MF.getFunction();999CallingConv::ID CalleeCC = Info.CallConv;1000CallingConv::ID CallerCC = CallerF.getCallingConv();10011002// If the calling conventions match, then everything must be the same.1003if (CalleeCC == CallerCC)1004return true;10051006const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();10071008// Make sure that the caller and callee preserve all of the same registers.1009auto TRI = ST.getRegisterInfo();10101011const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);1012const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);1013if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))1014return false;10151016// Check if the caller and callee will handle arguments in the same way.1017const SITargetLowering &TLI = *getTLI<SITargetLowering>();1018CCAssignFn *CalleeAssignFnFixed;1019CCAssignFn *CalleeAssignFnVarArg;1020std::tie(CalleeAssignFnFixed, CalleeAssignFnVarArg) =1021getAssignFnsForCC(CalleeCC, TLI);10221023CCAssignFn *CallerAssignFnFixed;1024CCAssignFn *CallerAssignFnVarArg;1025std::tie(CallerAssignFnFixed, CallerAssignFnVarArg) =1026getAssignFnsForCC(CallerCC, TLI);10271028// FIXME: We are not accounting for potential differences in implicitly passed1029// inputs, but only the fixed ABI is supported now anyway.1030IncomingValueAssigner CalleeAssigner(CalleeAssignFnFixed,1031CalleeAssignFnVarArg);1032IncomingValueAssigner CallerAssigner(CallerAssignFnFixed,1033CallerAssignFnVarArg);1034return resultsCompatible(Info, MF, InArgs, CalleeAssigner, CallerAssigner);1035}10361037bool AMDGPUCallLowering::areCalleeOutgoingArgsTailCallable(1038CallLoweringInfo &Info, MachineFunction &MF,1039SmallVectorImpl<ArgInfo> &OutArgs) const {1040// If there are no outgoing arguments, then we are done.1041if (OutArgs.empty())1042return true;10431044const Function &CallerF = MF.getFunction();1045CallingConv::ID CalleeCC = Info.CallConv;1046CallingConv::ID CallerCC = CallerF.getCallingConv();1047const SITargetLowering &TLI = *getTLI<SITargetLowering>();10481049CCAssignFn *AssignFnFixed;1050CCAssignFn *AssignFnVarArg;1051std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);10521053// We have outgoing arguments. Make sure that we can tail call with them.1054SmallVector<CCValAssign, 16> OutLocs;1055CCState OutInfo(CalleeCC, false, MF, OutLocs, CallerF.getContext());1056OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);10571058if (!determineAssignments(Assigner, OutArgs, OutInfo)) {1059LLVM_DEBUG(dbgs() << "... Could not analyze call operands.\n");1060return false;1061}10621063// Make sure that they can fit on the caller's stack.1064const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();1065if (OutInfo.getStackSize() > FuncInfo->getBytesInStackArgArea()) {1066LLVM_DEBUG(dbgs() << "... Cannot fit call operands on caller's stack.\n");1067return false;1068}10691070// Verify that the parameters in callee-saved registers match.1071const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();1072const SIRegisterInfo *TRI = ST.getRegisterInfo();1073const uint32_t *CallerPreservedMask = TRI->getCallPreservedMask(MF, CallerCC);1074MachineRegisterInfo &MRI = MF.getRegInfo();1075return parametersInCSRMatch(MRI, CallerPreservedMask, OutLocs, OutArgs);1076}10771078/// Return true if the calling convention is one that we can guarantee TCO for.1079static bool canGuaranteeTCO(CallingConv::ID CC) {1080return CC == CallingConv::Fast;1081}10821083/// Return true if we might ever do TCO for calls with this calling convention.1084static bool mayTailCallThisCC(CallingConv::ID CC) {1085switch (CC) {1086case CallingConv::C:1087case CallingConv::AMDGPU_Gfx:1088return true;1089default:1090return canGuaranteeTCO(CC);1091}1092}10931094bool AMDGPUCallLowering::isEligibleForTailCallOptimization(1095MachineIRBuilder &B, CallLoweringInfo &Info,1096SmallVectorImpl<ArgInfo> &InArgs, SmallVectorImpl<ArgInfo> &OutArgs) const {1097// Must pass all target-independent checks in order to tail call optimize.1098if (!Info.IsTailCall)1099return false;11001101// Indirect calls can't be tail calls, because the address can be divergent.1102// TODO Check divergence info if the call really is divergent.1103if (Info.Callee.isReg())1104return false;11051106MachineFunction &MF = B.getMF();1107const Function &CallerF = MF.getFunction();1108CallingConv::ID CalleeCC = Info.CallConv;1109CallingConv::ID CallerCC = CallerF.getCallingConv();11101111const SIRegisterInfo *TRI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();1112const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);1113// Kernels aren't callable, and don't have a live in return address so it1114// doesn't make sense to do a tail call with entry functions.1115if (!CallerPreserved)1116return false;11171118if (!mayTailCallThisCC(CalleeCC)) {1119LLVM_DEBUG(dbgs() << "... Calling convention cannot be tail called.\n");1120return false;1121}11221123if (any_of(CallerF.args(), [](const Argument &A) {1124return A.hasByValAttr() || A.hasSwiftErrorAttr();1125})) {1126LLVM_DEBUG(dbgs() << "... Cannot tail call from callers with byval "1127"or swifterror arguments\n");1128return false;1129}11301131// If we have -tailcallopt, then we're done.1132if (MF.getTarget().Options.GuaranteedTailCallOpt)1133return canGuaranteeTCO(CalleeCC) && CalleeCC == CallerF.getCallingConv();11341135// Verify that the incoming and outgoing arguments from the callee are1136// safe to tail call.1137if (!doCallerAndCalleePassArgsTheSameWay(Info, MF, InArgs)) {1138LLVM_DEBUG(1139dbgs()1140<< "... Caller and callee have incompatible calling conventions.\n");1141return false;1142}11431144if (!areCalleeOutgoingArgsTailCallable(Info, MF, OutArgs))1145return false;11461147LLVM_DEBUG(dbgs() << "... Call is eligible for tail call optimization.\n");1148return true;1149}11501151// Insert outgoing implicit arguments for a call, by inserting copies to the1152// implicit argument registers and adding the necessary implicit uses to the1153// call instruction.1154void AMDGPUCallLowering::handleImplicitCallArguments(1155MachineIRBuilder &MIRBuilder, MachineInstrBuilder &CallInst,1156const GCNSubtarget &ST, const SIMachineFunctionInfo &FuncInfo,1157CallingConv::ID CalleeCC,1158ArrayRef<std::pair<MCRegister, Register>> ImplicitArgRegs) const {1159if (!ST.enableFlatScratch()) {1160// Insert copies for the SRD. In the HSA case, this should be an identity1161// copy.1162auto ScratchRSrcReg = MIRBuilder.buildCopy(LLT::fixed_vector(4, 32),1163FuncInfo.getScratchRSrcReg());11641165auto CalleeRSrcReg = AMDGPU::isChainCC(CalleeCC)1166? AMDGPU::SGPR48_SGPR49_SGPR50_SGPR511167: AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3;11681169MIRBuilder.buildCopy(CalleeRSrcReg, ScratchRSrcReg);1170CallInst.addReg(CalleeRSrcReg, RegState::Implicit);1171}11721173for (std::pair<MCRegister, Register> ArgReg : ImplicitArgRegs) {1174MIRBuilder.buildCopy((Register)ArgReg.first, ArgReg.second);1175CallInst.addReg(ArgReg.first, RegState::Implicit);1176}1177}11781179bool AMDGPUCallLowering::lowerTailCall(1180MachineIRBuilder &MIRBuilder, CallLoweringInfo &Info,1181SmallVectorImpl<ArgInfo> &OutArgs) const {1182MachineFunction &MF = MIRBuilder.getMF();1183const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();1184SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();1185const Function &F = MF.getFunction();1186MachineRegisterInfo &MRI = MF.getRegInfo();1187const SITargetLowering &TLI = *getTLI<SITargetLowering>();11881189// True when we're tail calling, but without -tailcallopt.1190bool IsSibCall = !MF.getTarget().Options.GuaranteedTailCallOpt;11911192// Find out which ABI gets to decide where things go.1193CallingConv::ID CalleeCC = Info.CallConv;1194CCAssignFn *AssignFnFixed;1195CCAssignFn *AssignFnVarArg;1196std::tie(AssignFnFixed, AssignFnVarArg) = getAssignFnsForCC(CalleeCC, TLI);11971198MachineInstrBuilder CallSeqStart;1199if (!IsSibCall)1200CallSeqStart = MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP);12011202unsigned Opc =1203getCallOpcode(MF, Info.Callee.isReg(), true, ST.isWave32(), CalleeCC);1204auto MIB = MIRBuilder.buildInstrNoInsert(Opc);1205if (!addCallTargetOperands(MIB, MIRBuilder, Info))1206return false;12071208// Byte offset for the tail call. When we are sibcalling, this will always1209// be 0.1210MIB.addImm(0);12111212// If this is a chain call, we need to pass in the EXEC mask.1213const SIRegisterInfo *TRI = ST.getRegisterInfo();1214if (AMDGPU::isChainCC(Info.CallConv)) {1215ArgInfo ExecArg = Info.OrigArgs[1];1216assert(ExecArg.Regs.size() == 1 && "Too many regs for EXEC");12171218if (!ExecArg.Ty->isIntegerTy(ST.getWavefrontSize()))1219return false;12201221if (auto CI = dyn_cast<ConstantInt>(ExecArg.OrigValue)) {1222MIB.addImm(CI->getSExtValue());1223} else {1224MIB.addReg(ExecArg.Regs[0]);1225unsigned Idx = MIB->getNumOperands() - 1;1226MIB->getOperand(Idx).setReg(constrainOperandRegClass(1227MF, *TRI, MRI, *ST.getInstrInfo(), *ST.getRegBankInfo(), *MIB,1228MIB->getDesc(), MIB->getOperand(Idx), Idx));1229}1230}12311232// Tell the call which registers are clobbered.1233const uint32_t *Mask = TRI->getCallPreservedMask(MF, CalleeCC);1234MIB.addRegMask(Mask);12351236// FPDiff is the byte offset of the call's argument area from the callee's.1237// Stores to callee stack arguments will be placed in FixedStackSlots offset1238// by this amount for a tail call. In a sibling call it must be 0 because the1239// caller will deallocate the entire stack and the callee still expects its1240// arguments to begin at SP+0.1241int FPDiff = 0;12421243// This will be 0 for sibcalls, potentially nonzero for tail calls produced1244// by -tailcallopt. For sibcalls, the memory operands for the call are1245// already available in the caller's incoming argument space.1246unsigned NumBytes = 0;1247if (!IsSibCall) {1248// We aren't sibcalling, so we need to compute FPDiff. We need to do this1249// before handling assignments, because FPDiff must be known for memory1250// arguments.1251unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();1252SmallVector<CCValAssign, 16> OutLocs;1253CCState OutInfo(CalleeCC, false, MF, OutLocs, F.getContext());12541255// FIXME: Not accounting for callee implicit inputs1256OutgoingValueAssigner CalleeAssigner(AssignFnFixed, AssignFnVarArg);1257if (!determineAssignments(CalleeAssigner, OutArgs, OutInfo))1258return false;12591260// The callee will pop the argument stack as a tail call. Thus, we must1261// keep it 16-byte aligned.1262NumBytes = alignTo(OutInfo.getStackSize(), ST.getStackAlignment());12631264// FPDiff will be negative if this tail call requires more space than we1265// would automatically have in our incoming argument space. Positive if we1266// actually shrink the stack.1267FPDiff = NumReusableBytes - NumBytes;12681269// The stack pointer must be 16-byte aligned at all times it's used for a1270// memory operation, which in practice means at *all* times and in1271// particular across call boundaries. Therefore our own arguments started at1272// a 16-byte aligned SP and the delta applied for the tail call should1273// satisfy the same constraint.1274assert(isAligned(ST.getStackAlignment(), FPDiff) &&1275"unaligned stack on tail call");1276}12771278SmallVector<CCValAssign, 16> ArgLocs;1279CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());12801281// We could pass MIB and directly add the implicit uses to the call1282// now. However, as an aesthetic choice, place implicit argument operands1283// after the ordinary user argument registers.1284SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;12851286if (Info.CallConv != CallingConv::AMDGPU_Gfx &&1287!AMDGPU::isChainCC(Info.CallConv)) {1288// With a fixed ABI, allocate fixed registers before user arguments.1289if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))1290return false;1291}12921293OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);12941295if (!determineAssignments(Assigner, OutArgs, CCInfo))1296return false;12971298// Do the actual argument marshalling.1299AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, true, FPDiff);1300if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))1301return false;13021303if (Info.ConvergenceCtrlToken) {1304MIB.addUse(Info.ConvergenceCtrlToken, RegState::Implicit);1305}1306handleImplicitCallArguments(MIRBuilder, MIB, ST, *FuncInfo, CalleeCC,1307ImplicitArgRegs);13081309// If we have -tailcallopt, we need to adjust the stack. We'll do the call1310// sequence start and end here.1311if (!IsSibCall) {1312MIB->getOperand(1).setImm(FPDiff);1313CallSeqStart.addImm(NumBytes).addImm(0);1314// End the call sequence *before* emitting the call. Normally, we would1315// tidy the frame up after the call. However, here, we've laid out the1316// parameters so that when SP is reset, they will be in the correct1317// location.1318MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN).addImm(NumBytes).addImm(0);1319}13201321// Now we can add the actual call instruction to the correct basic block.1322MIRBuilder.insertInstr(MIB);13231324// If Callee is a reg, since it is used by a target specific1325// instruction, it must have a register class matching the1326// constraint of that instruction.13271328// FIXME: We should define regbankselectable call instructions to handle1329// divergent call targets.1330if (MIB->getOperand(0).isReg()) {1331MIB->getOperand(0).setReg(constrainOperandRegClass(1332MF, *TRI, MRI, *ST.getInstrInfo(), *ST.getRegBankInfo(), *MIB,1333MIB->getDesc(), MIB->getOperand(0), 0));1334}13351336MF.getFrameInfo().setHasTailCall();1337Info.LoweredTailCall = true;1338return true;1339}13401341/// Lower a call to the @llvm.amdgcn.cs.chain intrinsic.1342bool AMDGPUCallLowering::lowerChainCall(MachineIRBuilder &MIRBuilder,1343CallLoweringInfo &Info) const {1344ArgInfo Callee = Info.OrigArgs[0];1345ArgInfo SGPRArgs = Info.OrigArgs[2];1346ArgInfo VGPRArgs = Info.OrigArgs[3];1347ArgInfo Flags = Info.OrigArgs[4];13481349assert(cast<ConstantInt>(Flags.OrigValue)->isZero() &&1350"Non-zero flags aren't supported yet.");1351assert(Info.OrigArgs.size() == 5 && "Additional args aren't supported yet.");13521353MachineFunction &MF = MIRBuilder.getMF();1354const Function &F = MF.getFunction();1355const DataLayout &DL = F.getDataLayout();13561357// The function to jump to is actually the first argument, so we'll change the1358// Callee and other info to match that before using our existing helper.1359const Value *CalleeV = Callee.OrigValue->stripPointerCasts();1360if (const Function *F = dyn_cast<Function>(CalleeV)) {1361Info.Callee = MachineOperand::CreateGA(F, 0);1362Info.CallConv = F->getCallingConv();1363} else {1364assert(Callee.Regs.size() == 1 && "Too many regs for the callee");1365Info.Callee = MachineOperand::CreateReg(Callee.Regs[0], false);1366Info.CallConv = CallingConv::AMDGPU_CS_Chain; // amdgpu_cs_chain_preserve1367// behaves the same here.1368}13691370// The function that we're calling cannot be vararg (only the intrinsic is).1371Info.IsVarArg = false;13721373assert(std::all_of(SGPRArgs.Flags.begin(), SGPRArgs.Flags.end(),1374[](ISD::ArgFlagsTy F) { return F.isInReg(); }) &&1375"SGPR arguments should be marked inreg");1376assert(std::none_of(VGPRArgs.Flags.begin(), VGPRArgs.Flags.end(),1377[](ISD::ArgFlagsTy F) { return F.isInReg(); }) &&1378"VGPR arguments should not be marked inreg");13791380SmallVector<ArgInfo, 8> OutArgs;1381splitToValueTypes(SGPRArgs, OutArgs, DL, Info.CallConv);1382splitToValueTypes(VGPRArgs, OutArgs, DL, Info.CallConv);13831384Info.IsMustTailCall = true;1385return lowerTailCall(MIRBuilder, Info, OutArgs);1386}13871388bool AMDGPUCallLowering::lowerCall(MachineIRBuilder &MIRBuilder,1389CallLoweringInfo &Info) const {1390if (Function *F = Info.CB->getCalledFunction())1391if (F->isIntrinsic()) {1392assert(F->getIntrinsicID() == Intrinsic::amdgcn_cs_chain &&1393"Unexpected intrinsic");1394return lowerChainCall(MIRBuilder, Info);1395}13961397if (Info.IsVarArg) {1398LLVM_DEBUG(dbgs() << "Variadic functions not implemented\n");1399return false;1400}14011402MachineFunction &MF = MIRBuilder.getMF();1403const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();1404const SIRegisterInfo *TRI = ST.getRegisterInfo();14051406const Function &F = MF.getFunction();1407MachineRegisterInfo &MRI = MF.getRegInfo();1408const SITargetLowering &TLI = *getTLI<SITargetLowering>();1409const DataLayout &DL = F.getDataLayout();14101411SmallVector<ArgInfo, 8> OutArgs;1412for (auto &OrigArg : Info.OrigArgs)1413splitToValueTypes(OrigArg, OutArgs, DL, Info.CallConv);14141415SmallVector<ArgInfo, 8> InArgs;1416if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy())1417splitToValueTypes(Info.OrigRet, InArgs, DL, Info.CallConv);14181419// If we can lower as a tail call, do that instead.1420bool CanTailCallOpt =1421isEligibleForTailCallOptimization(MIRBuilder, Info, InArgs, OutArgs);14221423// We must emit a tail call if we have musttail.1424if (Info.IsMustTailCall && !CanTailCallOpt) {1425LLVM_DEBUG(dbgs() << "Failed to lower musttail call as tail call\n");1426return false;1427}14281429Info.IsTailCall = CanTailCallOpt;1430if (CanTailCallOpt)1431return lowerTailCall(MIRBuilder, Info, OutArgs);14321433// Find out which ABI gets to decide where things go.1434CCAssignFn *AssignFnFixed;1435CCAssignFn *AssignFnVarArg;1436std::tie(AssignFnFixed, AssignFnVarArg) =1437getAssignFnsForCC(Info.CallConv, TLI);14381439MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKUP)1440.addImm(0)1441.addImm(0);14421443// Create a temporarily-floating call instruction so we can add the implicit1444// uses of arg registers.1445unsigned Opc = getCallOpcode(MF, Info.Callee.isReg(), false, ST.isWave32(),1446Info.CallConv);14471448auto MIB = MIRBuilder.buildInstrNoInsert(Opc);1449MIB.addDef(TRI->getReturnAddressReg(MF));14501451if (!Info.IsConvergent)1452MIB.setMIFlag(MachineInstr::NoConvergent);14531454if (!addCallTargetOperands(MIB, MIRBuilder, Info))1455return false;14561457// Tell the call which registers are clobbered.1458const uint32_t *Mask = TRI->getCallPreservedMask(MF, Info.CallConv);1459MIB.addRegMask(Mask);14601461SmallVector<CCValAssign, 16> ArgLocs;1462CCState CCInfo(Info.CallConv, Info.IsVarArg, MF, ArgLocs, F.getContext());14631464// We could pass MIB and directly add the implicit uses to the call1465// now. However, as an aesthetic choice, place implicit argument operands1466// after the ordinary user argument registers.1467SmallVector<std::pair<MCRegister, Register>, 12> ImplicitArgRegs;14681469if (Info.CallConv != CallingConv::AMDGPU_Gfx) {1470// With a fixed ABI, allocate fixed registers before user arguments.1471if (!passSpecialInputs(MIRBuilder, CCInfo, ImplicitArgRegs, Info))1472return false;1473}14741475// Do the actual argument marshalling.1476SmallVector<Register, 8> PhysRegs;14771478OutgoingValueAssigner Assigner(AssignFnFixed, AssignFnVarArg);1479if (!determineAssignments(Assigner, OutArgs, CCInfo))1480return false;14811482AMDGPUOutgoingArgHandler Handler(MIRBuilder, MRI, MIB, false);1483if (!handleAssignments(Handler, OutArgs, CCInfo, ArgLocs, MIRBuilder))1484return false;14851486const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();14871488if (Info.ConvergenceCtrlToken) {1489MIB.addUse(Info.ConvergenceCtrlToken, RegState::Implicit);1490}1491handleImplicitCallArguments(MIRBuilder, MIB, ST, *MFI, Info.CallConv,1492ImplicitArgRegs);14931494// Get a count of how many bytes are to be pushed on the stack.1495unsigned NumBytes = CCInfo.getStackSize();14961497// If Callee is a reg, since it is used by a target specific1498// instruction, it must have a register class matching the1499// constraint of that instruction.15001501// FIXME: We should define regbankselectable call instructions to handle1502// divergent call targets.1503if (MIB->getOperand(1).isReg()) {1504MIB->getOperand(1).setReg(constrainOperandRegClass(1505MF, *TRI, MRI, *ST.getInstrInfo(),1506*ST.getRegBankInfo(), *MIB, MIB->getDesc(), MIB->getOperand(1),15071));1508}15091510// Now we can add the actual call instruction to the correct position.1511MIRBuilder.insertInstr(MIB);15121513// Finally we can copy the returned value back into its virtual-register. In1514// symmetry with the arguments, the physical register must be an1515// implicit-define of the call instruction.1516if (Info.CanLowerReturn && !Info.OrigRet.Ty->isVoidTy()) {1517CCAssignFn *RetAssignFn = TLI.CCAssignFnForReturn(Info.CallConv,1518Info.IsVarArg);1519IncomingValueAssigner Assigner(RetAssignFn);1520CallReturnHandler Handler(MIRBuilder, MRI, MIB);1521if (!determineAndHandleAssignments(Handler, Assigner, InArgs, MIRBuilder,1522Info.CallConv, Info.IsVarArg))1523return false;1524}15251526uint64_t CalleePopBytes = NumBytes;15271528MIRBuilder.buildInstr(AMDGPU::ADJCALLSTACKDOWN)1529.addImm(0)1530.addImm(CalleePopBytes);15311532if (!Info.CanLowerReturn) {1533insertSRetLoads(MIRBuilder, Info.OrigRet.Ty, Info.OrigRet.Regs,1534Info.DemoteRegister, Info.DemoteStackIndex);1535}15361537return true;1538}153915401541