#include "RISCVFrameLowering.h"
#include "RISCVMachineFunctionInfo.h"
#include "RISCVSubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/MC/MCDwarf.h"
#include <algorithm>
using namespace llvm;
static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const DebugLoc &DL) {
if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
return;
const auto &STI = MF.getSubtarget<RISCVSubtarget>();
Register RAReg = STI.getRegisterInfo()->getRARegister();
std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
if (std::none_of(CSI.begin(), CSI.end(),
[&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
return;
Register SCSPReg = RISCVABI::getSCSPReg();
auto &Ctx = MF.getFunction().getContext();
if (!STI.isRegisterReservedByUser(SCSPReg)) {
Ctx.diagnose(DiagnosticInfoUnsupported{
MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
return;
}
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
if (RVFI->useSaveRestoreLibCalls(MF)) {
Ctx.diagnose(DiagnosticInfoUnsupported{
MF.getFunction(),
"Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
return;
}
const RISCVInstrInfo *TII = STI.getInstrInfo();
bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
int64_t SlotSize = STI.getXLen() / 8;
BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
.addReg(RAReg)
.addReg(SCSPReg)
.addImm(0)
.setMIFlag(MachineInstr::FrameSetup);
BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
.addReg(SCSPReg, RegState::Define)
.addReg(SCSPReg)
.addImm(SlotSize)
.setMIFlag(MachineInstr::FrameSetup);
}
static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const DebugLoc &DL) {
if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
return;
const auto &STI = MF.getSubtarget<RISCVSubtarget>();
Register RAReg = STI.getRegisterInfo()->getRARegister();
std::vector<CalleeSavedInfo> &CSI = MF.getFrameInfo().getCalleeSavedInfo();
if (std::none_of(CSI.begin(), CSI.end(),
[&](CalleeSavedInfo &CSR) { return CSR.getReg() == RAReg; }))
return;
Register SCSPReg = RISCVABI::getSCSPReg();
auto &Ctx = MF.getFunction().getContext();
if (!STI.isRegisterReservedByUser(SCSPReg)) {
Ctx.diagnose(DiagnosticInfoUnsupported{
MF.getFunction(), "x18 not reserved by user for Shadow Call Stack."});
return;
}
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
if (RVFI->useSaveRestoreLibCalls(MF)) {
Ctx.diagnose(DiagnosticInfoUnsupported{
MF.getFunction(),
"Shadow Call Stack cannot be combined with Save/Restore LibCalls."});
return;
}
const RISCVInstrInfo *TII = STI.getInstrInfo();
bool IsRV64 = STI.hasFeature(RISCV::Feature64Bit);
int64_t SlotSize = STI.getXLen() / 8;
BuildMI(MBB, MI, DL, TII->get(IsRV64 ? RISCV::LD : RISCV::LW))
.addReg(RAReg, RegState::Define)
.addReg(SCSPReg)
.addImm(-SlotSize)
.setMIFlag(MachineInstr::FrameDestroy);
BuildMI(MBB, MI, DL, TII->get(RISCV::ADDI))
.addReg(SCSPReg, RegState::Define)
.addReg(SCSPReg)
.addImm(-SlotSize)
.setMIFlag(MachineInstr::FrameDestroy);
}
static int getLibCallID(const MachineFunction &MF,
const std::vector<CalleeSavedInfo> &CSI) {
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
if (CSI.empty() || !RVFI->useSaveRestoreLibCalls(MF))
return -1;
Register MaxReg = RISCV::NoRegister;
for (auto &CS : CSI)
if (CS.getFrameIdx() < 0)
MaxReg = std::max(MaxReg.id(), CS.getReg().id());
if (MaxReg == RISCV::NoRegister)
return -1;
switch (MaxReg) {
default:
llvm_unreachable("Something has gone wrong!");
case RISCV::X27: return 12;
case RISCV::X26: return 11;
case RISCV::X25: return 10;
case RISCV::X24: return 9;
case RISCV::X23: return 8;
case RISCV::X22: return 7;
case RISCV::X21: return 6;
case RISCV::X20: return 5;
case RISCV::X19: return 4;
case RISCV::X18: return 3;
case RISCV::X9: return 2;
case RISCV::X8: return 1;
case RISCV::X1: return 0;
}
}
static const char *
getSpillLibCallName(const MachineFunction &MF,
const std::vector<CalleeSavedInfo> &CSI) {
static const char *const SpillLibCalls[] = {
"__riscv_save_0",
"__riscv_save_1",
"__riscv_save_2",
"__riscv_save_3",
"__riscv_save_4",
"__riscv_save_5",
"__riscv_save_6",
"__riscv_save_7",
"__riscv_save_8",
"__riscv_save_9",
"__riscv_save_10",
"__riscv_save_11",
"__riscv_save_12"
};
int LibCallID = getLibCallID(MF, CSI);
if (LibCallID == -1)
return nullptr;
return SpillLibCalls[LibCallID];
}
static const char *
getRestoreLibCallName(const MachineFunction &MF,
const std::vector<CalleeSavedInfo> &CSI) {
static const char *const RestoreLibCalls[] = {
"__riscv_restore_0",
"__riscv_restore_1",
"__riscv_restore_2",
"__riscv_restore_3",
"__riscv_restore_4",
"__riscv_restore_5",
"__riscv_restore_6",
"__riscv_restore_7",
"__riscv_restore_8",
"__riscv_restore_9",
"__riscv_restore_10",
"__riscv_restore_11",
"__riscv_restore_12"
};
int LibCallID = getLibCallID(MF, CSI);
if (LibCallID == -1)
return nullptr;
return RestoreLibCalls[LibCallID];
}
bool RISCVFrameLowering::hasFP(const MachineFunction &MF) const {
const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
const MachineFrameInfo &MFI = MF.getFrameInfo();
return MF.getTarget().Options.DisableFramePointerElim(MF) ||
RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
MFI.isFrameAddressTaken();
}
bool RISCVFrameLowering::hasBP(const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterInfo *TRI = STI.getRegisterInfo();
return (MFI.hasVarSizedObjects() ||
(!hasReservedCallFrame(MF) && (!MFI.isMaxCallFrameSizeComputed() ||
MFI.getMaxCallFrameSize() != 0))) &&
TRI->hasStackRealignment(MF);
}
void RISCVFrameLowering::determineFrameLayout(MachineFunction &MF) const {
MachineFrameInfo &MFI = MF.getFrameInfo();
auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
uint64_t FrameSize = MFI.getStackSize();
Align StackAlign = getStackAlign();
FrameSize = alignTo(FrameSize, StackAlign);
MFI.setStackSize(FrameSize);
const TargetRegisterInfo *TRI = STI.getRegisterInfo();
if (RVFI->getRVVStackSize() && (!hasFP(MF) || TRI->hasStackRealignment(MF))) {
int ScalarLocalVarSize = FrameSize - RVFI->getCalleeSavedStackSize() -
RVFI->getVarArgsSaveSize();
if (auto RVVPadding =
offsetToAlignment(ScalarLocalVarSize, RVFI->getRVVStackAlign()))
RVFI->setRVVPadding(RVVPadding);
}
}
uint64_t RISCVFrameLowering::getStackSizeWithRVVPadding(
const MachineFunction &MF) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
return alignTo(MFI.getStackSize() + RVFI->getRVVPadding(), getStackAlign());
}
void RISCVFrameLowering::adjustReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, Register DestReg,
Register SrcReg, int64_t Val,
MachineInstr::MIFlag Flag) const {
MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
const RISCVInstrInfo *TII = STI.getInstrInfo();
if (DestReg == SrcReg && Val == 0)
return;
if (isInt<12>(Val)) {
BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
.addReg(SrcReg)
.addImm(Val)
.setMIFlag(Flag);
return;
}
assert(getStackAlign().value() < 2048 && "Stack alignment too large");
int64_t MaxPosAdjStep = 2048 - getStackAlign().value();
if (Val > -4096 && Val <= (2 * MaxPosAdjStep)) {
int64_t FirstAdj = Val < 0 ? -2048 : MaxPosAdjStep;
Val -= FirstAdj;
BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
.addReg(SrcReg)
.addImm(FirstAdj)
.setMIFlag(Flag);
BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), DestReg)
.addReg(DestReg, RegState::Kill)
.addImm(Val)
.setMIFlag(Flag);
return;
}
unsigned Opc = RISCV::ADD;
if (Val < 0) {
Val = -Val;
Opc = RISCV::SUB;
}
Register ScratchReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
TII->movImm(MBB, MBBI, DL, ScratchReg, Val, Flag);
BuildMI(MBB, MBBI, DL, TII->get(Opc), DestReg)
.addReg(SrcReg)
.addReg(ScratchReg, RegState::Kill)
.setMIFlag(Flag);
}
static Register getFPReg(const RISCVSubtarget &STI) { return RISCV::X8; }
static Register getSPReg(const RISCVSubtarget &STI) { return RISCV::X2; }
static SmallVector<CalleeSavedInfo, 8>
getNonLibcallCSI(const MachineFunction &MF,
const std::vector<CalleeSavedInfo> &CSI) {
const MachineFrameInfo &MFI = MF.getFrameInfo();
SmallVector<CalleeSavedInfo, 8> NonLibcallCSI;
for (auto &CS : CSI) {
int FI = CS.getFrameIdx();
if (FI >= 0 && MFI.getStackID(FI) == TargetStackID::Default)
NonLibcallCSI.push_back(CS);
}
return NonLibcallCSI;
}
void RISCVFrameLowering::adjustStackForRVV(MachineFunction &MF,
MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
const DebugLoc &DL, int64_t Amount,
MachineInstr::MIFlag Flag) const {
assert(Amount != 0 && "Did not need to adjust stack pointer for RVV.");
const RISCVInstrInfo *TII = STI.getInstrInfo();
Register SPReg = getSPReg(STI);
unsigned Opc = RISCV::ADD;
if (Amount < 0) {
Amount = -Amount;
Opc = RISCV::SUB;
}
Register FactorRegister =
TII->getVLENFactoredAmount(MF, MBB, MBBI, DL, Amount, Flag);
BuildMI(MBB, MBBI, DL, TII->get(Opc), SPReg)
.addReg(SPReg)
.addReg(FactorRegister, RegState::Kill)
.setMIFlag(Flag);
}
void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
MachineFrameInfo &MFI = MF.getFrameInfo();
auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
const RISCVRegisterInfo *RI = STI.getRegisterInfo();
const RISCVInstrInfo *TII = STI.getInstrInfo();
MachineBasicBlock::iterator MBBI = MBB.begin();
Register FPReg = getFPReg(STI);
Register SPReg = getSPReg(STI);
Register BPReg = RISCVABI::getBPReg();
DebugLoc DL;
if (MF.getFunction().getCallingConv() == CallingConv::GHC)
return;
emitSCSPrologue(MF, MBB, MBBI, DL);
while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
++MBBI;
determineFrameLayout(MF);
if (int LibCallRegs = getLibCallID(MF, MFI.getCalleeSavedInfo()) + 1) {
unsigned LibCallFrameSize = alignTo((STI.getXLen() / 8) * LibCallRegs, 16);
RVFI->setLibCallStackSize(LibCallFrameSize);
}
uint64_t StackSize = getStackSizeWithRVVPadding(MF);
uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
uint64_t RVVStackSize = RVFI->getRVVStackSize();
if (RealStackSize == 0 && !MFI.adjustsStack() && RVVStackSize == 0)
return;
if (STI.isRegisterReservedByUser(SPReg))
MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
MF.getFunction(), "Stack pointer required, but has been reserved."});
uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
if (FirstSPAdjustAmount) {
StackSize = FirstSPAdjustAmount;
RealStackSize = FirstSPAdjustAmount;
}
adjustReg(MBB, MBBI, DL, SPReg, SPReg, -StackSize, MachineInstr::FrameSetup);
unsigned CFIIndex = MF.addFrameInst(
MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex)
.setMIFlag(MachineInstr::FrameSetup);
const auto &CSI = MFI.getCalleeSavedInfo();
std::advance(MBBI, getNonLibcallCSI(MF, CSI).size());
for (const auto &Entry : CSI) {
int FrameIdx = Entry.getFrameIdx();
int64_t Offset;
if (FrameIdx < 0)
Offset = FrameIdx * (int64_t) STI.getXLen() / 8;
else
Offset = MFI.getObjectOffset(Entry.getFrameIdx()) -
RVFI->getLibCallStackSize();
Register Reg = Entry.getReg();
unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
nullptr, RI->getDwarfRegNum(Reg, true), Offset));
BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex)
.setMIFlag(MachineInstr::FrameSetup);
}
if (hasFP(MF)) {
if (STI.isRegisterReservedByUser(FPReg))
MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
MF.getFunction(), "Frame pointer required, but has been reserved."});
adjustReg(MBB, MBBI, DL, FPReg, SPReg,
RealStackSize - RVFI->getVarArgsSaveSize(),
MachineInstr::FrameSetup);
unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
nullptr, RI->getDwarfRegNum(FPReg, true), RVFI->getVarArgsSaveSize()));
BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex)
.setMIFlag(MachineInstr::FrameSetup);
}
if (FirstSPAdjustAmount) {
uint64_t SecondSPAdjustAmount =
getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
assert(SecondSPAdjustAmount > 0 &&
"SecondSPAdjustAmount should be greater than zero");
adjustReg(MBB, MBBI, DL, SPReg, SPReg, -SecondSPAdjustAmount,
MachineInstr::FrameSetup);
if (!hasFP(MF)) {
unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
nullptr, getStackSizeWithRVVPadding(MF)));
BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
.addCFIIndex(CFIIndex)
.setMIFlag(MachineInstr::FrameSetup);
}
}
if (RVVStackSize)
adjustStackForRVV(MF, MBB, MBBI, DL, -RVVStackSize,
MachineInstr::FrameSetup);
if (hasFP(MF)) {
const RISCVRegisterInfo *RI = STI.getRegisterInfo();
if (RI->hasStackRealignment(MF)) {
Align MaxAlignment = MFI.getMaxAlign();
const RISCVInstrInfo *TII = STI.getInstrInfo();
if (isInt<12>(-(int)MaxAlignment.value())) {
BuildMI(MBB, MBBI, DL, TII->get(RISCV::ANDI), SPReg)
.addReg(SPReg)
.addImm(-(int)MaxAlignment.value())
.setMIFlag(MachineInstr::FrameSetup);
} else {
unsigned ShiftAmount = Log2(MaxAlignment);
Register VR =
MF.getRegInfo().createVirtualRegister(&RISCV::GPRRegClass);
BuildMI(MBB, MBBI, DL, TII->get(RISCV::SRLI), VR)
.addReg(SPReg)
.addImm(ShiftAmount)
.setMIFlag(MachineInstr::FrameSetup);
BuildMI(MBB, MBBI, DL, TII->get(RISCV::SLLI), SPReg)
.addReg(VR)
.addImm(ShiftAmount)
.setMIFlag(MachineInstr::FrameSetup);
}
if (hasBP(MF)) {
BuildMI(MBB, MBBI, DL, TII->get(RISCV::ADDI), BPReg)
.addReg(SPReg)
.addImm(0)
.setMIFlag(MachineInstr::FrameSetup);
}
}
}
}
void RISCVFrameLowering::emitEpilogue(MachineFunction &MF,
MachineBasicBlock &MBB) const {
const RISCVRegisterInfo *RI = STI.getRegisterInfo();
MachineFrameInfo &MFI = MF.getFrameInfo();
auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
Register FPReg = getFPReg(STI);
Register SPReg = getSPReg(STI);
if (MF.getFunction().getCallingConv() == CallingConv::GHC)
return;
MachineBasicBlock::iterator MBBI = MBB.end();
DebugLoc DL;
if (!MBB.empty()) {
MBBI = MBB.getLastNonDebugInstr();
if (MBBI != MBB.end())
DL = MBBI->getDebugLoc();
MBBI = MBB.getFirstTerminator();
while (MBBI != MBB.begin() &&
std::prev(MBBI)->getFlag(MachineInstr::FrameDestroy))
--MBBI;
}
const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
auto LastFrameDestroy = MBBI;
if (!CSI.empty())
LastFrameDestroy = std::prev(MBBI, CSI.size());
uint64_t StackSize = getStackSizeWithRVVPadding(MF);
uint64_t RealStackSize = StackSize + RVFI->getLibCallStackSize();
uint64_t FPOffset = RealStackSize - RVFI->getVarArgsSaveSize();
uint64_t RVVStackSize = RVFI->getRVVStackSize();
if (RI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
!hasReservedCallFrame(MF)) {
assert(hasFP(MF) && "frame pointer should not have been eliminated");
adjustReg(MBB, LastFrameDestroy, DL, SPReg, FPReg, -FPOffset,
MachineInstr::FrameDestroy);
} else {
if (RVVStackSize)
adjustStackForRVV(MF, MBB, LastFrameDestroy, DL, RVVStackSize,
MachineInstr::FrameDestroy);
}
uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
if (FirstSPAdjustAmount) {
uint64_t SecondSPAdjustAmount =
getStackSizeWithRVVPadding(MF) - FirstSPAdjustAmount;
assert(SecondSPAdjustAmount > 0 &&
"SecondSPAdjustAmount should be greater than zero");
adjustReg(MBB, LastFrameDestroy, DL, SPReg, SPReg, SecondSPAdjustAmount,
MachineInstr::FrameDestroy);
}
if (FirstSPAdjustAmount)
StackSize = FirstSPAdjustAmount;
adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackSize, MachineInstr::FrameDestroy);
emitSCSEpilogue(MF, MBB, MBBI, DL);
}
StackOffset
RISCVFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Register &FrameReg) const {
const MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
const auto &CSI = getNonLibcallCSI(MF, MFI.getCalleeSavedInfo());
int MinCSFI = 0;
int MaxCSFI = -1;
StackOffset Offset;
auto StackID = MFI.getStackID(FI);
assert((StackID == TargetStackID::Default ||
StackID == TargetStackID::ScalableVector) &&
"Unexpected stack ID for the frame object.");
if (StackID == TargetStackID::Default) {
Offset =
StackOffset::getFixed(MFI.getObjectOffset(FI) - getOffsetOfLocalArea() +
MFI.getOffsetAdjustment());
} else if (StackID == TargetStackID::ScalableVector) {
Offset = StackOffset::getScalable(MFI.getObjectOffset(FI));
}
uint64_t FirstSPAdjustAmount = getFirstSPAdjustAmount(MF);
if (CSI.size()) {
MinCSFI = CSI[0].getFrameIdx();
MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
}
if (FI >= MinCSFI && FI <= MaxCSFI) {
FrameReg = RISCV::X2;
if (FirstSPAdjustAmount)
Offset += StackOffset::getFixed(FirstSPAdjustAmount);
else
Offset += StackOffset::getFixed(getStackSizeWithRVVPadding(MF));
return Offset;
}
if (RI->hasStackRealignment(MF) && !MFI.isFixedObjectIndex(FI)) {
if (hasBP(MF)) {
FrameReg = RISCVABI::getBPReg();
} else {
assert(!MFI.hasVarSizedObjects());
FrameReg = RISCV::X2;
}
} else {
FrameReg = RI->getFrameRegister(MF);
}
if (FrameReg == getFPReg(STI)) {
Offset += StackOffset::getFixed(RVFI->getVarArgsSaveSize());
if (FI >= 0)
Offset -= StackOffset::getFixed(RVFI->getLibCallStackSize());
if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
assert(!RI->hasStackRealignment(MF) &&
"Can't index across variable sized realign");
assert(MFI.getStackSize() == getStackSizeWithRVVPadding(MF) &&
"Inconsistent stack layout");
Offset -= StackOffset::getFixed(MFI.getStackSize());
}
return Offset;
}
assert(FrameReg == RISCVABI::getBPReg() || !MFI.hasVarSizedObjects());
if (MFI.getStackID(FI) == TargetStackID::Default) {
if (MFI.isFixedObjectIndex(FI)) {
assert(!RI->hasStackRealignment(MF) &&
"Can't index across variable sized realign");
Offset += StackOffset::get(getStackSizeWithRVVPadding(MF) +
RVFI->getLibCallStackSize(),
RVFI->getRVVStackSize());
} else {
Offset += StackOffset::getFixed(MFI.getStackSize());
}
} else if (MFI.getStackID(FI) == TargetStackID::ScalableVector) {
int ScalarLocalVarSize =
MFI.getStackSize() - RVFI->getCalleeSavedStackSize() -
RVFI->getVarArgsSaveSize() + RVFI->getRVVPadding();
Offset += StackOffset::get(ScalarLocalVarSize, RVFI->getRVVStackSize());
}
return Offset;
}
void RISCVFrameLowering::determineCalleeSaves(MachineFunction &MF,
BitVector &SavedRegs,
RegScavenger *RS) const {
TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
if (hasFP(MF)) {
SavedRegs.set(RISCV::X1);
SavedRegs.set(RISCV::X8);
}
if (hasBP(MF))
SavedRegs.set(RISCVABI::getBPReg());
MachineFrameInfo &MFI = MF.getFrameInfo();
if (MF.getFunction().hasFnAttribute("interrupt") && MFI.hasCalls()) {
static const MCPhysReg CSRegs[] = { RISCV::X1,
RISCV::X5, RISCV::X6, RISCV::X7,
RISCV::X10, RISCV::X11,
RISCV::X12, RISCV::X13, RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17,
RISCV::X28, RISCV::X29, RISCV::X30, RISCV::X31, 0
};
for (unsigned i = 0; CSRegs[i]; ++i)
SavedRegs.set(CSRegs[i]);
if (MF.getSubtarget<RISCVSubtarget>().hasStdExtF()) {
const MCPhysReg * Regs = MF.getRegInfo().getCalleeSavedRegs();
for (unsigned i = 0; Regs[i]; ++i)
if (RISCV::FPR16RegClass.contains(Regs[i]) ||
RISCV::FPR32RegClass.contains(Regs[i]) ||
RISCV::FPR64RegClass.contains(Regs[i]))
SavedRegs.set(Regs[i]);
}
}
}
std::pair<int64_t, Align>
RISCVFrameLowering::assignRVVStackObjectOffsets(MachineFunction &MF) const {
MachineFrameInfo &MFI = MF.getFrameInfo();
SmallVector<int, 8> ObjectsToAllocate;
for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
unsigned StackID = MFI.getStackID(I);
if (StackID != TargetStackID::ScalableVector)
continue;
if (MFI.isDeadObjectIndex(I))
continue;
ObjectsToAllocate.push_back(I);
}
Align RVVStackAlign(16);
const auto &ST = MF.getSubtarget<RISCVSubtarget>();
if (!ST.hasVInstructions()) {
assert(ObjectsToAllocate.empty() &&
"Can't allocate scalable-vector objects without V instructions");
return std::make_pair(0, RVVStackAlign);
}
int64_t Offset = 0;
for (int FI : ObjectsToAllocate) {
int64_t ObjectSize = MFI.getObjectSize(FI);
auto ObjectAlign = std::max(Align(8), MFI.getObjectAlign(FI));
if (ObjectSize < 8)
ObjectSize = 8;
Offset = alignTo(Offset + ObjectSize, ObjectAlign);
MFI.setObjectOffset(FI, -Offset);
RVVStackAlign = std::max(RVVStackAlign, ObjectAlign);
}
uint64_t StackSize = Offset;
if (auto AlignmentPadding = offsetToAlignment(StackSize, RVVStackAlign)) {
StackSize += AlignmentPadding;
for (int FI : ObjectsToAllocate)
MFI.setObjectOffset(FI, MFI.getObjectOffset(FI) - AlignmentPadding);
}
return std::make_pair(StackSize, RVVStackAlign);
}
static unsigned getScavSlotsNumForRVV(MachineFunction &MF) {
static constexpr unsigned ScavSlotsNumRVVSpillScalableObject = 2;
static constexpr unsigned ScavSlotsNumRVVSpillNonScalableObject = 1;
static constexpr unsigned ScavSlotsADDIScalableObject = 1;
static constexpr unsigned MaxScavSlotsNumKnown =
std::max({ScavSlotsADDIScalableObject, ScavSlotsNumRVVSpillScalableObject,
ScavSlotsNumRVVSpillNonScalableObject});
unsigned MaxScavSlotsNum = 0;
if (!MF.getSubtarget<RISCVSubtarget>().hasVInstructions())
return false;
for (const MachineBasicBlock &MBB : MF)
for (const MachineInstr &MI : MBB) {
bool IsRVVSpill = RISCV::isRVVSpill(MI);
for (auto &MO : MI.operands()) {
if (!MO.isFI())
continue;
bool IsScalableVectorID = MF.getFrameInfo().getStackID(MO.getIndex()) ==
TargetStackID::ScalableVector;
if (IsRVVSpill) {
MaxScavSlotsNum = std::max(
MaxScavSlotsNum, IsScalableVectorID
? ScavSlotsNumRVVSpillScalableObject
: ScavSlotsNumRVVSpillNonScalableObject);
} else if (MI.getOpcode() == RISCV::ADDI && IsScalableVectorID) {
MaxScavSlotsNum =
std::max(MaxScavSlotsNum, ScavSlotsADDIScalableObject);
}
}
if (MaxScavSlotsNum == MaxScavSlotsNumKnown)
return MaxScavSlotsNumKnown;
}
return MaxScavSlotsNum;
}
void RISCVFrameLowering::processFunctionBeforeFrameFinalized(
MachineFunction &MF, RegScavenger *RS) const {
const RISCVRegisterInfo *RegInfo =
MF.getSubtarget<RISCVSubtarget>().getRegisterInfo();
MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterClass *RC = &RISCV::GPRRegClass;
auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
int64_t RVVStackSize;
Align RVVStackAlign;
std::tie(RVVStackSize, RVVStackAlign) = assignRVVStackObjectOffsets(MF);
RVFI->setRVVStackSize(RVVStackSize);
RVFI->setRVVStackAlign(RVVStackAlign);
MFI.ensureMaxAlignment(RVVStackAlign);
unsigned ScavSlotsNum = 0;
if (!isInt<11>(MFI.estimateStackSize(MF)))
ScavSlotsNum = 1;
ScavSlotsNum = std::max(ScavSlotsNum, getScavSlotsNumForRVV(MF));
for (unsigned i = 0; i < ScavSlotsNum; i++) {
RS->addScavengingFrameIndex(MFI.CreateStackObject(
RegInfo->getSpillSize(*RC), RegInfo->getSpillAlign(*RC), false));
}
if (MFI.getCalleeSavedInfo().empty() || RVFI->useSaveRestoreLibCalls(MF)) {
RVFI->setCalleeSavedStackSize(0);
return;
}
unsigned Size = 0;
for (const auto &Info : MFI.getCalleeSavedInfo()) {
int FrameIdx = Info.getFrameIdx();
if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
continue;
Size += MFI.getObjectSize(FrameIdx);
}
RVFI->setCalleeSavedStackSize(Size);
}
static bool hasRVVFrameObject(const MachineFunction &MF) {
return MF.getSubtarget<RISCVSubtarget>().hasVInstructions();
}
bool RISCVFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
return !MF.getFrameInfo().hasVarSizedObjects() &&
!(hasFP(MF) && hasRVVFrameObject(MF));
}
MachineBasicBlock::iterator RISCVFrameLowering::eliminateCallFramePseudoInstr(
MachineFunction &MF, MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI) const {
Register SPReg = RISCV::X2;
DebugLoc DL = MI->getDebugLoc();
if (!hasReservedCallFrame(MF)) {
int64_t Amount = MI->getOperand(0).getImm();
if (Amount != 0) {
Amount = alignSPAdjust(Amount);
if (MI->getOpcode() == RISCV::ADJCALLSTACKDOWN)
Amount = -Amount;
adjustReg(MBB, MI, DL, SPReg, SPReg, Amount, MachineInstr::NoFlags);
}
}
return MBB.erase(MI);
}
uint64_t
RISCVFrameLowering::getFirstSPAdjustAmount(const MachineFunction &MF) const {
const auto *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
const MachineFrameInfo &MFI = MF.getFrameInfo();
const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
uint64_t StackSize = getStackSizeWithRVVPadding(MF);
if (RVFI->getLibCallStackSize())
return 0;
if (!isInt<12>(StackSize) && (CSI.size() > 0)) {
return 2048 - getStackAlign().value();
}
return 0;
}
bool RISCVFrameLowering::spillCalleeSavedRegisters(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
if (CSI.empty())
return true;
MachineFunction *MF = MBB.getParent();
const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
DebugLoc DL;
if (MI != MBB.end() && !MI->isDebugInstr())
DL = MI->getDebugLoc();
const char *SpillLibCall = getSpillLibCallName(*MF, CSI);
if (SpillLibCall) {
BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoCALLReg), RISCV::X5)
.addExternalSymbol(SpillLibCall, RISCVII::MO_CALL)
.setMIFlag(MachineInstr::FrameSetup);
for (auto &CS : CSI)
MBB.addLiveIn(CS.getReg());
}
const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
for (auto &CS : NonLibcallCSI) {
Register Reg = CS.getReg();
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
TII.storeRegToStackSlot(MBB, MI, Reg, !MBB.isLiveIn(Reg), CS.getFrameIdx(),
RC, TRI);
}
return true;
}
bool RISCVFrameLowering::restoreCalleeSavedRegisters(
MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
if (CSI.empty())
return true;
MachineFunction *MF = MBB.getParent();
const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
DebugLoc DL;
if (MI != MBB.end() && !MI->isDebugInstr())
DL = MI->getDebugLoc();
const auto &NonLibcallCSI = getNonLibcallCSI(*MF, CSI);
for (auto &CS : NonLibcallCSI) {
Register Reg = CS.getReg();
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
TII.loadRegFromStackSlot(MBB, MI, Reg, CS.getFrameIdx(), RC, TRI);
assert(MI != MBB.begin() && "loadRegFromStackSlot didn't insert any code!");
}
const char *RestoreLibCall = getRestoreLibCallName(*MF, CSI);
if (RestoreLibCall) {
MachineBasicBlock::iterator NewMI =
BuildMI(MBB, MI, DL, TII.get(RISCV::PseudoTAIL))
.addExternalSymbol(RestoreLibCall, RISCVII::MO_CALL)
.setMIFlag(MachineInstr::FrameDestroy);
if (MI != MBB.end() && MI->getOpcode() == RISCV::PseudoRET) {
NewMI->copyImplicitOps(*MF, *MI);
MI->eraseFromParent();
}
}
return true;
}
bool RISCVFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
if (MF.getFunction().hasOptNone())
return false;
return true;
}
bool RISCVFrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
const MachineFunction *MF = MBB.getParent();
const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
if (!RVFI->useSaveRestoreLibCalls(*MF))
return true;
RegScavenger RS;
RS.enterBasicBlock(*TmpMBB);
return !RS.isRegUsed(RISCV::X5);
}
bool RISCVFrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
const MachineFunction *MF = MBB.getParent();
MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
const auto *RVFI = MF->getInfo<RISCVMachineFunctionInfo>();
if (!RVFI->useSaveRestoreLibCalls(*MF))
return true;
if (MBB.succ_size() > 1)
return false;
MachineBasicBlock *SuccMBB =
MBB.succ_empty() ? TmpMBB->getFallThrough() : *MBB.succ_begin();
if (!SuccMBB)
return true;
return SuccMBB->isReturnBlock() && SuccMBB->size() == 1;
}
bool RISCVFrameLowering::isSupportedStackID(TargetStackID::Value ID) const {
switch (ID) {
case TargetStackID::Default:
case TargetStackID::ScalableVector:
return true;
case TargetStackID::NoAlloc:
case TargetStackID::SGPRSpill:
case TargetStackID::WasmLocal:
return false;
}
llvm_unreachable("Invalid TargetStackID::Value");
}
TargetStackID::Value RISCVFrameLowering::getStackIDForScalableVectors() const {
return TargetStackID::ScalableVector;
}