24#define DEBUG_TYPE "riscv-merge-base-offset"
25#define RISCV_MERGE_BASE_OFFSET_NAME "RISC-V Merge Base Offset"
65char RISCVMergeBaseOffsetOpt::ID = 0;
89 auto HiOpc =
Hi.getOpcode();
90 if (HiOpc != RISCV::LUI && HiOpc != RISCV::AUIPC &&
91 HiOpc != RISCV::PseudoMovAddr && HiOpc != RISCV::QC_E_LI)
105 if (HiOpc == RISCV::PseudoMovAddr || HiOpc == RISCV::QC_E_LI) {
110 Register HiDestReg =
Hi.getOperand(0).getReg();
111 if (!
MRI->hasOneUse(HiDestReg))
114 Lo = &*
MRI->use_instr_begin(HiDestReg);
115 if (
Lo->getOpcode() != RISCV::ADDI)
119 if (HiOpc != RISCV::QC_E_LI) {
121 if (HiOpc == RISCV::LUI || HiOpc == RISCV::PseudoMovAddr) {
127 assert(HiOpc == RISCV::AUIPC);
135 LLVM_DEBUG(dbgs() <<
" Found lowered global address: "
136 << *HiOp1.getGlobal() <<
"\n");
138 LLVM_DEBUG(dbgs() <<
" Found lowered basic address: "
139 << *HiOp1.getBlockAddress() <<
"\n");
141 LLVM_DEBUG(dbgs() <<
" Found lowered constant pool: " << HiOp1.getIndex()
158 auto HiOpc =
Hi.getOpcode();
159 if (HiOpc == RISCV::AUIPC &&
Hi.getOperand(1).isGlobal()) {
160 const GlobalValue *GV =
Hi.getOperand(1).getGlobal();
169 if (
Hi.getOpcode() != RISCV::AUIPC &&
Hi.getOpcode() != RISCV::QC_E_LI)
172 Register LoOp0Reg =
Lo.getOperand(0).getReg();
174 MRI->constrainRegClass(LoOp0Reg,
MRI->getRegClass(TailOp0Reg));
175 MRI->replaceRegWith(TailOp0Reg, LoOp0Reg);
176 Tail.eraseFromParent();
178 <<
" " <<
Hi <<
" " <<
Lo;);
202bool RISCVMergeBaseOffsetOpt::foldLargeOffset(MachineInstr &
Hi,
204 MachineInstr &TailAdd,
206 assert((TailAdd.
getOpcode() == RISCV::ADD) &&
"Expected ADD instruction!");
215 MachineInstr &OffsetTail = *
MRI->getVRegDef(
Reg);
216 auto OffsetTailOpc = OffsetTail.
getOpcode();
217 if (OffsetTailOpc == RISCV::ADDI || OffsetTailOpc == RISCV::ADDIW) {
220 MachineOperand &AddiImmOp = OffsetTail.
getOperand(2);
224 int64_t OffLo = AddiImmOp.
getImm();
227 if (AddiReg == RISCV::X0) {
229 if (!foldOffset(
Hi,
Lo, TailAdd, OffLo))
235 MachineInstr &OffsetLui = *
MRI->getVRegDef(AddiReg);
236 MachineOperand &LuiImmOp = OffsetLui.
getOperand(1);
237 if (OffsetLui.
getOpcode() != RISCV::LUI ||
244 if (!ST->
is64Bit() || OffsetTailOpc == RISCV::ADDIW)
250 <<
" " << OffsetLui);
256 }
else if (OffsetTailOpc == RISCV::LUI) {
280bool RISCVMergeBaseOffsetOpt::foldShiftedOffset(MachineInstr &
Hi,
282 MachineInstr &TailShXAdd,
285 TailShXAdd.
getOpcode() == RISCV::SH2ADD ||
286 TailShXAdd.
getOpcode() == RISCV::SH3ADD) &&
287 "Expected SHXADD instruction!");
299 MachineInstr &OffsetTail = *
MRI->getVRegDef(Rs1);
300 if (OffsetTail.
getOpcode() != RISCV::ADDI)
313 case RISCV::SH1ADD: ShAmt = 1;
break;
314 case RISCV::SH2ADD: ShAmt = 2;
break;
315 case RISCV::SH3ADD: ShAmt = 3;
break;
327bool RISCVMergeBaseOffsetOpt::detectAndFoldOffset(MachineInstr &
Hi,
334 if (!
MRI->hasOneUse(DestReg))
338 MachineInstr &
Tail = *
MRI->use_instr_begin(DestReg);
339 switch (
Tail.getOpcode()) {
341 LLVM_DEBUG(
dbgs() <<
"Don't know how to get offset from this instr:"
345 case RISCV::QC_E_ADDI:
346 case RISCV::QC_E_ADDAI: {
349 if (
Tail.getOpcode() == RISCV::ADDI) {
352 if (
MRI->hasOneUse(TailDestReg)) {
353 MachineInstr &TailTail = *
MRI->use_instr_begin(TailDestReg);
354 if (TailTail.
getOpcode() == RISCV::ADDI) {
359 Tail.eraseFromParent();
377 return foldLargeOffset(
Hi,
Lo,
Tail, DestReg);
384 return foldShiftedOffset(
Hi,
Lo,
Tail, DestReg);
390bool RISCVMergeBaseOffsetOpt::foldIntoMemoryOps(MachineInstr &
Hi,
409 std::optional<int64_t> CommonOffset;
410 DenseMap<const MachineInstr *, SmallVector<unsigned>>
411 InlineAsmMemoryOpIndexesMap;
412 for (
const MachineInstr &
UseMI :
MRI->use_instructions(DestReg)) {
413 switch (
UseMI.getOpcode()) {
440 if (
UseMI.getOperand(1).isFI())
446 "Expected base address use");
449 if (CommonOffset &&
Offset != CommonOffset)
454 case RISCV::INLINEASM:
455 case RISCV::INLINEASM_BR: {
456 SmallVector<unsigned> InlineAsmMemoryOpIndexes;
460 const MachineOperand &FlagsMO =
UseMI.getOperand(
I);
462 if (!FlagsMO.
isImm())
472 for (
unsigned J = 0; J <
NumOps; ++J) {
473 const MachineOperand &MO =
UseMI.getOperand(
I + 1 + J);
482 if (
Flags.getMemoryConstraintID() == InlineAsm::ConstraintCode::A)
485 const MachineOperand &AddrMO =
UseMI.getOperand(
I + 1);
489 const MachineOperand &OffsetMO =
UseMI.getOperand(
I + 2);
490 if (!OffsetMO.
isImm())
495 if (CommonOffset &&
Offset != CommonOffset)
500 InlineAsmMemoryOpIndexesMap.
insert(
501 std::make_pair(&
UseMI, InlineAsmMemoryOpIndexes));
511 int64_t NewOffset =
Hi.getOperand(1).getOffset() + *CommonOffset;
519 Hi.getOperand(1).setOffset(NewOffset);
520 MachineOperand &ImmOp =
521 Hi.getOpcode() == RISCV::QC_E_LI ?
Lo.getOperand(1) :
Lo.getOperand(2);
522 auto HiOpc =
Hi.getOpcode();
524 if (HiOpc == RISCV::PseudoMovAddr) {
526 Hi.setDesc(
TII->get(RISCV::LUI));
530 if (HiOpc != RISCV::AUIPC)
534 for (MachineInstr &
UseMI :
536 if (
UseMI.getOpcode() == RISCV::INLINEASM ||
537 UseMI.getOpcode() == RISCV::INLINEASM_BR) {
538 auto &InlineAsmMemoryOpIndexes = InlineAsmMemoryOpIndexesMap[&
UseMI];
539 for (
unsigned I : InlineAsmMemoryOpIndexes) {
540 MachineOperand &MO =
UseMI.getOperand(
I + 1);
560 if (
Hi.getOpcode() == RISCV::QC_E_LI) {
561 UseMI.getOperand(2).ChangeToImmediate(0);
563 UseMI.removeOperand(2);
564 UseMI.addOperand(ImmOp);
574 MRI->replaceRegWith(
Lo.getOperand(0).getReg(),
Hi.getOperand(0).getReg());
575 Lo.eraseFromParent();
583bool RISCVMergeBaseOffsetOpt::foldShxaddIntoScaledMemory(MachineInstr &
Hi,
585 if (!ST->hasVendorXqcisls() || ST->
is64Bit())
588 if (
Hi.getOpcode() != RISCV::QC_E_LI)
592 if (!
BaseReg.isVirtual() || !
MRI->hasOneUse(BaseReg))
595 MachineInstr &ShxAdd = *
MRI->use_instr_begin(BaseReg);
610 case RISCV::QC_SHLADD:
628 if (!ScaledReg.
isVirtual() || !
MRI->hasOneUse(ScaledReg))
631 MachineInstr &TailMem = *
MRI->use_instr_begin(ScaledReg);
637 NewOpc = RISCV::QC_LRB;
640 NewOpc = RISCV::QC_LRBU;
643 NewOpc = RISCV::QC_LRH;
646 NewOpc = RISCV::QC_LRHU;
649 NewOpc = RISCV::QC_LRW;
652 NewOpc = RISCV::QC_SRB;
655 NewOpc = RISCV::QC_SRH;
658 NewOpc = RISCV::QC_SRW;
674 Hi.getOperand(1).setOffset(NewOffset);
681 MRI->constrainRegClass(IndexReg, &RISCV::GPRNoX0RegClass);
695bool RISCVMergeBaseOffsetOpt::runOnMachineFunction(MachineFunction &Fn) {
701 bool MadeChange =
false;
703 for (MachineBasicBlock &
MBB : Fn) {
705 for (MachineInstr &
Hi :
MBB) {
706 MachineInstr *
Lo =
nullptr;
707 if (!detectFoldable(
Hi,
Lo))
709 MadeChange |= detectAndFoldOffset(
Hi, *
Lo);
710 MadeChange |= foldIntoMemoryOps(
Hi, *
Lo);
711 MadeChange |= foldShxaddIntoScaledMemory(
Hi, *
Lo);
720 return new RISCVMergeBaseOffsetOpt();
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const HexagonInstrInfo * TII
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
#define RISCV_MERGE_BASE_OFFSET_NAME
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
FunctionPass class - This class is used to implement most global optimizations.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Type * getValueType() const
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
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.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Register getReg(unsigned Idx) const
Get the register for the operand index.
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 & add(const MachineOperand &MO) const
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
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
LLVM_ABI void ChangeToMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
ChangeToMCSymbol - Replace this operand with a new MC symbol operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
LLVM_ABI void ChangeToBA(const BlockAddress *BA, int64_t Offset, unsigned TargetFlags=0)
ChangeToBA - Replace this operand with a new block address operand.
const BlockAddress * getBlockAddress() const
void setOffset(int64_t Offset)
unsigned getTargetFlags() const
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
MCSymbol * getMCSymbol() const
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const RISCVInstrInfo * getInstrInfo() const override
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
void push_back(const T &Elt)
StringRef - Represent a constant reference to a string, i.e.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
constexpr RegState getKillRegState(bool B)
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
FunctionPass * createRISCVMergeBaseOffsetOptPass()
Returns an instance of the Merge Base Offset Optimization pass.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.