42#define DEBUG_TYPE "riscv-load-store-opt"
43#define RISCV_LOAD_STORE_OPT_NAME "RISC-V Load / Store Optimizer"
45STATISTIC(NumLD2LW,
"Number of LD instructions split back to LW");
46STATISTIC(NumSD2SW,
"Number of SD instructions split back to SW");
57 MachineFunctionProperties getRequiredProperties()
const override {
58 return MachineFunctionProperties().setNoVRegs();
61 void getAnalysisUsage(AnalysisUsage &AU)
const override {
71class RISCVLoadStoreOptImpl {
97 bool fixInvalidRegPairOp(MachineBasicBlock &
MBB,
100 void splitLdSdIntoTwo(MachineBasicBlock &
MBB,
104 const RISCVInstrInfo *TII;
105 const RISCVRegisterInfo *TRI;
106 const RISCVSubtarget *STI =
nullptr;
107 LiveRegUnits ModifiedRegUnits, UsedRegUnits;
115char RISCVLoadStoreOptLegacy::ID = 0;
119bool RISCVLoadStoreOptImpl::runOnMachineFunction(
122 bool MadeChange =
false;
124 TII = STI->getInstrInfo();
125 TRI = STI->getRegisterInfo();
127 ModifiedRegUnits.init(*
TRI);
128 UsedRegUnits.init(*
TRI);
130 if (STI->useMIPSLoadStorePairs() || STI->hasVendorXqcilsm()) {
136 if (
TII->isPairableLdStInstOpc(
MBBI->getOpcode()) &&
137 tryToPairLdStInst(
MBBI))
145 if (!STI->is64Bit() && STI->hasStdExtZilsd()) {
146 for (
auto &
MBB : MF) {
148 if (fixInvalidRegPairOp(
MBB,
MBBI)) {
163bool RISCVLoadStoreOptImpl::tryToPairLdStInst(
168 if (
MI.hasOrderedMemoryRef())
171 if (!
TII->isLdStSafeToPair(
MI,
TRI))
175 if (!STI->
is64Bit() && STI->hasVendorXqcilsm()) {
176 if (tryConvertToXqcilsmMultiLdSt(
MBBI))
185 MBBI = mergePairedInsns(
MBBI, Paired, MergeForward);
194 return MMOAlign >= RequiredAlignment;
201bool RISCVLoadStoreOptImpl::tryConvertToXqcilsmMultiLdSt(
203 MachineInstr &FirstMI = *FirstIt;
206 if (STI->
is64Bit() || !STI->hasVendorXqcilsm())
210 if (
Opc != RISCV::LW &&
Opc != RISCV::SW)
220 const MachineOperand &BaseOp = FirstMI.
getOperand(1);
221 const MachineOperand &OffOp = FirstMI.
getOperand(2);
226 int64_t BaseOff = OffOp.
getImm();
232 bool IsLoad = (
Opc == RISCV::LW);
236 if (StartReg == RISCV::X0)
238 if (StartReg ==
Base)
243 SmallVector<MachineInstr *, 8> Group;
248 int64_t ExpectedOff = BaseOff + 4;
250 enum class StoreMode {
Unknown, Setwmi, Swmi };
251 StoreMode SMode = StoreMode::Unknown;
254 MachineInstr &
MI = *It;
256 if (!
TII->isPairableLdStInstOpc(
MI.getOpcode()))
258 if (
MI.getOpcode() !=
Opc)
260 if (!
TII->isLdStSafeToPair(
MI,
TRI))
262 if (!
MI.hasOneMemOperand())
267 const MachineOperand &BaseMIOp =
MI.getOperand(1);
268 const MachineOperand &OffsetMIOp =
MI.getOperand(2);
274 if (
Off != ExpectedOff)
280 if (
Reg != StartReg + Index)
287 if (SMode == StoreMode::Unknown) {
289 SMode = StoreMode::Setwmi;
290 else if (
Reg == StartReg + 1)
291 SMode = StoreMode::Swmi;
294 }
else if (SMode == StoreMode::Setwmi) {
298 if (
Reg != StartReg + Index)
313 if (Len < 3 || Len > 31)
318 bool AddImplicitRegs =
true;
321 NewOpc = RISCV::QC_LWMI;
322 StartRegState = RegState::Define;
324 assert(SMode != StoreMode::Unknown &&
325 "Group should be large enough to know the store mode");
326 if (SMode == StoreMode::Setwmi) {
327 NewOpc = RISCV::QC_SETWMI;
329 bool StartKill =
false;
330 for (MachineInstr *
MI : Group)
331 StartKill |=
MI->getOperand(0).isKill();
333 AddImplicitRegs =
false;
336 if (StartReg == RISCV::X0)
338 NewOpc = RISCV::QC_SWMI;
339 StartRegState =
getKillRegState(Group.front()->getOperand(0).isKill());
344 bool BaseKill =
false;
345 for (MachineInstr *
MI : Group)
346 BaseKill |=
MI->getOperand(1).isKill();
352 MachineInstrBuilder MIB =
BuildMI(*MF,
DL,
TII->get(NewOpc));
353 MIB.
addReg(StartReg, StartRegState)
361 if (AddImplicitRegs) {
363 for (
unsigned i = 1; i <
Len; ++i) {
367 State = RegState::ImplicitDefine;
369 State = RegState::Implicit |
376 MachineBasicBlock *
MBB = FirstIt->getParent();
378 for (MachineInstr *
MI : Group)
379 MI->removeFromParent();
386bool RISCVLoadStoreOptImpl::tryConvertToXqcilsmLdStPair(
390 if ((
Opc != RISCV::LW &&
Opc != RISCV::SW) || Second->getOpcode() !=
Opc)
393 const auto &FirstOp1 =
First->getOperand(1);
394 const auto &SecondOp1 = Second->getOperand(1);
395 const auto &FirstOp2 =
First->getOperand(2);
396 const auto &SecondOp2 = Second->getOperand(2);
399 if (!FirstOp1.isReg() || !SecondOp1.isReg() || !FirstOp2.isImm() ||
404 Register Base2 = SecondOp1.getReg();
409 if (!
First->hasOneMemOperand() || !Second->hasOneMemOperand())
415 const auto &FirstOp0 =
First->getOperand(0);
416 const auto &SecondOp0 = Second->getOperand(0);
418 int64_t Off1 = FirstOp2.getImm();
419 int64_t Off2 = SecondOp2.getImm();
420 assert(Off1 < Off2 &&
"Expected instructions to be ordered by offset");
425 Register StartReg = FirstOp0.getReg();
426 Register NextReg = SecondOp0.getReg();
431 bool AddNextReg =
true;
433 if (
Opc == RISCV::LW) {
435 if (StartReg == RISCV::X0)
439 if (StartReg == Base1 || NextReg == Base1)
443 if (NextReg != StartReg + 1)
446 XqciOpc = RISCV::QC_LWMI;
447 StartRegState = RegState::Define;
448 NextRegState = RegState::ImplicitDefine;
450 assert(
Opc == RISCV::SW &&
"Expected a SW instruction");
451 if (StartReg == NextReg) {
452 XqciOpc = RISCV::QC_SETWMI;
453 StartRegState =
getKillRegState(FirstOp0.isKill() || SecondOp0.isKill());
455 }
else if (NextReg == StartReg + 1 && StartReg != RISCV::X0) {
456 XqciOpc = RISCV::QC_SWMI;
458 NextRegState = RegState::Implicit |
getKillRegState(SecondOp0.isKill());
465 First->getDebugLoc() ?
First->getDebugLoc() : Second->getDebugLoc();
466 MachineInstrBuilder MIB =
BuildMI(*MF,
DL,
TII->get(XqciOpc));
467 MIB.
addReg(StartReg, StartRegState)
474 MIB.
addReg(NextReg, NextRegState);
477 First->removeFromParent();
478 Second->removeFromParent();
483bool RISCVLoadStoreOptImpl::tryConvertToMIPSLdStPair(
489 Align RequiredAlignment;
490 switch (
First->getOpcode()) {
494 PairOpc = RISCV::MIPS_SWP;
495 RequiredAlignment =
Align(8);
498 PairOpc = RISCV::MIPS_LWP;
499 RequiredAlignment =
Align(8);
502 PairOpc = RISCV::MIPS_SDP;
503 RequiredAlignment =
Align(16);
506 PairOpc = RISCV::MIPS_LDP;
507 RequiredAlignment =
Align(16);
511 if (!
First->hasOneMemOperand())
521 MachineInstrBuilder MIB =
BuildMI(
522 *MF,
First->getDebugLoc() ?
First->getDebugLoc() : Second->getDebugLoc(),
525 .
add(Second->getOperand(0))
532 First->removeFromParent();
533 Second->removeFromParent();
543bool RISCVLoadStoreOptImpl::tryConvertToLdStPair(
548 if (!STI->
is64Bit() && STI->hasVendorXqcilsm())
549 return tryConvertToXqcilsmLdStPair(MF,
First, Second);
552 return tryConvertToMIPSLdStPair(MF,
First, Second);
573 bool &MergeForward) {
576 MachineInstr &FirstMI = *
I;
585 MergeForward =
false;
589 ModifiedRegUnits.
clear();
590 UsedRegUnits.
clear();
593 SmallVector<MachineInstr *, 4> MemInsns;
595 for (
unsigned Count = 0;
602 if (!
MI.isTransient())
607 Register MIBaseReg =
MI.getOperand(1).getReg();
608 int64_t MIOffset =
MI.getOperand(2).getImm();
610 if (BaseReg == MIBaseReg) {
611 if ((
Offset != MIOffset + OffsetStride) &&
612 (
Offset + OffsetStride != MIOffset)) {
622 TRI->isSuperOrSubRegisterEq(
Reg,
MI.getOperand(0).getReg())) {
630 if (!ModifiedRegUnits.
available(BaseReg))
637 if (ModifiedRegUnits.
available(
MI.getOperand(0).getReg()) &&
639 !UsedRegUnits.
available(
MI.getOperand(0).getReg())) &&
642 MergeForward =
false;
674 if (!ModifiedRegUnits.
available(BaseReg))
678 if (
MI.mayLoadOrStore())
704 int Offset =
I->getOperand(2).getImm();
705 int PairedOffset = Paired->getOperand(2).getImm();
706 bool InsertAfter = (
Offset < PairedOffset) ^ MergeForward;
709 Paired->getOperand(1).setIsKill(
false);
712 if (
I->getOperand(0).isUse()) {
716 MachineOperand &PairedRegOp = Paired->getOperand(0);
717 if (PairedRegOp.
isKill()) {
718 for (
auto It = std::next(
I); It != Paired; ++It) {
719 if (It->readsRegister(PairedRegOp.
getReg(),
TRI)) {
729 for (MachineInstr &
MI :
make_range(std::next(
I), std::next(Paired)))
738 MachineInstr *ToInsert = DeletionPoint->removeFromParent();
739 MachineBasicBlock &
MBB = *InsertionPoint->getParent();
744 Second = InsertionPoint;
748 First = InsertionPoint;
752 if (tryConvertToLdStPair(
First, Second)) {
755 }
else if (!STI->
is64Bit() && STI->hasVendorXqcilsm()) {
759 MachineInstr *MovedMI = Moved->removeFromParent();
771bool RISCVLoadStoreOptImpl::isValidZilsdRegPair(
Register First,
779 if (
First == RISCV::X0)
780 return Second == RISCV::X0;
783 unsigned FirstNum =
TRI->getEncodingValue(
First);
784 unsigned SecondNum =
TRI->getEncodingValue(Second);
787 return (FirstNum % 2 == 0) && (SecondNum == FirstNum + 1);
790void RISCVLoadStoreOptImpl::splitLdSdIntoTwo(MachineBasicBlock &
MBB,
793 MachineInstr *
MI = &*
MBBI;
796 const MachineOperand &FirstOp =
MI->getOperand(0);
797 const MachineOperand &SecondOp =
MI->getOperand(1);
798 const MachineOperand &BaseOp =
MI->getOperand(2);
804 const MachineOperand &
OffsetOp =
MI->getOperand(3);
812 unsigned Opc = IsLoad ? RISCV::LW : RISCV::SW;
813 MachineInstrBuilder MIB1, MIB2;
826 if (FirstReg == BaseReg) {
848 FirstReg != SecondReg &&
849 "First register and second register is impossible to be same register");
865 MIB2.
addImm(BaseOffset + 4);
886bool RISCVLoadStoreOptImpl::fixInvalidRegPairOp(
888 MachineInstr *
MI = &*
MBBI;
889 unsigned Opcode =
MI->getOpcode();
892 if (Opcode != RISCV::PseudoLD_RV32_OPT && Opcode != RISCV::PseudoSD_RV32_OPT)
895 bool IsLoad = Opcode == RISCV::PseudoLD_RV32_OPT;
897 const MachineOperand &FirstOp =
MI->getOperand(0);
898 const MachineOperand &SecondOp =
MI->getOperand(1);
902 if (!isValidZilsdRegPair(FirstReg, SecondReg)) {
904 splitLdSdIntoTwo(
MBB,
MBBI, IsLoad);
909 const MachineOperand &BaseOp =
MI->getOperand(2);
913 const MachineOperand &
OffsetOp =
MI->getOperand(3);
915 unsigned RealOpc = IsLoad ? RISCV::LD_RV32 : RISCV::SD_RV32;
918 MCRegister RegPair =
TRI->getMatchingSuperReg(FirstReg, RISCV::sub_gpr_even,
919 &RISCV::GPRPairRegClass);
935 LLVM_DEBUG(
dbgs() <<
"Converted pseudo to real instruction: " << *MIB
946 return new RISCVLoadStoreOptLegacy();
949bool RISCVLoadStoreOptLegacy::runOnMachineFunction(
MachineFunction &MF) {
952 RISCVLoadStoreOptImpl Impl;
953 return Impl.runOnMachineFunction(MF, [&]() {
954 return &getAnalysis<AAResultsWrapperPass>().getAAResults();
961 RISCVLoadStoreOptImpl Impl;
962 bool Changed = Impl.runOnMachineFunction(MF, [&]() {
static bool mayAlias(MachineInstr &MIa, SmallVectorImpl< MachineInstr * > &MemInsns, AliasAnalysis *AA)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
#define RISCV_LOAD_STORE_OPT_NAME
static bool isMemOpAligned(MachineInstr &MI, Align RequiredAlignment)
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
FunctionPass class - This class is used to implement most global optimizations.
static void accumulateUsedDefed(const MachineInstr &MI, LiveRegUnits &ModifiedRegUnits, LiveRegUnits &UsedRegUnits, const TargetRegisterInfo *TRI)
For a machine instruction MI, adds all register units used in UsedRegUnits and defined or clobbered i...
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void clear()
Clears the set.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & cloneMergedMemRefs(ArrayRef< const MachineInstr * > OtherMIs) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addBlockAddress(const BlockAddress *BA, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
LLVM_ABI bool mayAlias(BatchAAResults *AA, const MachineInstr &Other, bool UseTBAA) const
Returns true if this instruction's memory access aliases the memory access of Other.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const RISCVOptions & getCLOpts() const
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
An efficient, type-erasing, non-owning reference to a callable.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Unknown
Not known to have no common set bits.
RegState
Flags to represent properties of register accesses.
constexpr RegState getKillRegState(bool B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr RegState getDeadRegState(bool B)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionPass * createRISCVLoadStoreOptLegacyPass()
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
This struct is a compact representation of a valid (non-zero power of two) alignment.