25#define DEBUG_TYPE "riscv-merge-base-offset"
26#define RISCV_MERGE_BASE_OFFSET_NAME "RISC-V Merge Base Offset"
66char RISCVMergeBaseOffsetOpt::ID = 0;
90 auto HiOpc =
Hi.getOpcode();
91 if (HiOpc != RISCV::LUI && HiOpc != RISCV::AUIPC &&
92 HiOpc != RISCV::PseudoMovAddr && HiOpc != RISCV::QC_E_LI)
106 if (HiOpc == RISCV::PseudoMovAddr || HiOpc == RISCV::QC_E_LI) {
111 Register HiDestReg =
Hi.getOperand(0).getReg();
112 if (!MRI->hasOneUse(HiDestReg))
115 Lo = &*MRI->use_instr_begin(HiDestReg);
116 if (
Lo->getOpcode() != RISCV::ADDI)
120 if (HiOpc != RISCV::QC_E_LI) {
122 if (HiOpc == RISCV::LUI || HiOpc == RISCV::PseudoMovAddr) {
128 assert(HiOpc == RISCV::AUIPC);
136 LLVM_DEBUG(dbgs() <<
" Found lowered global address: "
137 << *HiOp1.getGlobal() <<
"\n");
139 LLVM_DEBUG(dbgs() <<
" Found lowered basic address: "
140 << *HiOp1.getBlockAddress() <<
"\n");
142 LLVM_DEBUG(dbgs() <<
" Found lowered constant pool: " << HiOp1.getIndex()
159 auto HiOpc =
Hi.getOpcode();
160 if (HiOpc == RISCV::AUIPC &&
Hi.getOperand(1).isGlobal()) {
161 const GlobalValue *GV =
Hi.getOperand(1).getGlobal();
171 for (MachineOperand &MO : MRI->
use_operands(
Lo.getOperand(0).getReg())) {
172 MachineInstr &DbgMI = *MO.getParent();
182 if (
Hi.getOpcode() != RISCV::AUIPC &&
Hi.getOpcode() != RISCV::QC_E_LI)
185 Register LoOp0Reg =
Lo.getOperand(0).getReg();
189 Tail.eraseFromParent();
191 <<
" " <<
Hi <<
" " <<
Lo;);
215bool RISCVMergeBaseOffsetOpt::foldLargeOffset(MachineInstr &
Hi,
217 MachineInstr &TailAdd,
219 assert((TailAdd.
getOpcode() == RISCV::ADD) &&
"Expected ADD instruction!");
229 auto OffsetTailOpc = OffsetTail.
getOpcode();
230 if (OffsetTailOpc == RISCV::ADDI || OffsetTailOpc == RISCV::ADDIW) {
233 MachineOperand &AddiImmOp = OffsetTail.
getOperand(2);
240 int64_t OffLo = AddiImmOp.
getImm();
243 if (AddiReg == RISCV::X0) {
245 if (!foldOffset(
Hi,
Lo, TailAdd, OffLo))
251 MachineInstr &OffsetLui = *MRI->
getVRegDef(AddiReg);
252 MachineOperand &LuiImmOp = OffsetLui.
getOperand(1);
253 if (OffsetLui.
getOpcode() != RISCV::LUI ||
260 if (!ST->
is64Bit() || OffsetTailOpc == RISCV::ADDIW)
266 <<
" " << OffsetLui);
272 }
else if (OffsetTailOpc == RISCV::LUI) {
296bool RISCVMergeBaseOffsetOpt::foldShiftedOffset(MachineInstr &
Hi,
298 MachineInstr &TailShXAdd,
301 TailShXAdd.
getOpcode() == RISCV::SH2ADD ||
302 TailShXAdd.
getOpcode() == RISCV::SH3ADD) &&
303 "Expected SHXADD instruction!");
315 MachineInstr &OffsetTail = *MRI->
getVRegDef(Rs1);
316 if (OffsetTail.
getOpcode() != RISCV::ADDI)
329 case RISCV::SH1ADD: ShAmt = 1;
break;
330 case RISCV::SH2ADD: ShAmt = 2;
break;
331 case RISCV::SH3ADD: ShAmt = 3;
break;
343bool RISCVMergeBaseOffsetOpt::detectAndFoldOffset(MachineInstr &
Hi,
355 switch (
Tail.getOpcode()) {
357 LLVM_DEBUG(
dbgs() <<
"Don't know how to get offset from this instr: "
361 case RISCV::QC_E_ADDI:
362 case RISCV::QC_E_ADDAI: {
365 if (
Tail.getOpcode() == RISCV::ADDI) {
370 if (TailTail.
getOpcode() == RISCV::ADDI) {
375 Tail.eraseFromParent();
393 return foldLargeOffset(
Hi,
Lo, Tail, DestReg);
400 return foldShiftedOffset(
Hi,
Lo, Tail, DestReg);
429bool RISCVMergeBaseOffsetOpt::foldIntoMemoryOps(MachineInstr &
Hi,
448 std::optional<int64_t> CommonOffset;
449 DenseMap<const MachineInstr *, SmallVector<unsigned>>
450 InlineAsmMemoryOpIndexesMap;
452 switch (
UseMI.getOpcode()) {
479 if (
UseMI.getOperand(1).isFI())
485 "Expected base address use");
488 if (CommonOffset &&
Offset != CommonOffset)
493 case RISCV::PseudoCCLD:
494 case RISCV::PseudoCCLW:
495 case RISCV::PseudoCCLWU:
496 case RISCV::PseudoCCLH:
497 case RISCV::PseudoCCLHU:
498 case RISCV::PseudoCCLB:
499 case RISCV::PseudoCCLBU: {
502 if (
UseMI.getOperand(2).isFI())
509 if (
UseMI.getOperand(6).isReg() &&
513 "Expected base address use");
516 if (CommonOffset &&
Offset != CommonOffset)
521 case RISCV::INLINEASM:
522 case RISCV::INLINEASM_BR: {
523 SmallVector<unsigned> InlineAsmMemoryOpIndexes;
527 const MachineOperand &FlagsMO =
UseMI.getOperand(
I);
529 if (!FlagsMO.
isImm())
539 for (
unsigned J = 0; J <
NumOps; ++J) {
540 const MachineOperand &MO =
UseMI.getOperand(
I + 1 + J);
549 if (
Flags.getMemoryConstraintID() == InlineAsm::ConstraintCode::A)
552 const MachineOperand &AddrMO =
UseMI.getOperand(
I + 1);
556 const MachineOperand &OffsetMO =
UseMI.getOperand(
I + 2);
557 if (!OffsetMO.
isImm())
562 if (CommonOffset &&
Offset != CommonOffset)
567 InlineAsmMemoryOpIndexesMap.
insert(
568 std::make_pair(&
UseMI, InlineAsmMemoryOpIndexes));
581 int64_t NewOffset =
Hi.getOperand(1).getOffset() + *CommonOffset;
593 Hi.getOperand(1).setOffset(NewOffset);
594 MachineOperand &ImmOp =
595 Hi.getOpcode() == RISCV::QC_E_LI ?
Lo.getOperand(1) :
Lo.getOperand(2);
596 auto HiOpc =
Hi.getOpcode();
598 if (HiOpc == RISCV::PseudoMovAddr) {
600 Hi.setDesc(
TII->get(RISCV::LUI));
604 if (HiOpc != RISCV::AUIPC)
608 for (MachineInstr &
UseMI :
610 if (
UseMI.getOpcode() == RISCV::INLINEASM ||
611 UseMI.getOpcode() == RISCV::INLINEASM_BR) {
612 auto &InlineAsmMemoryOpIndexes = InlineAsmMemoryOpIndexesMap[&
UseMI];
613 for (
unsigned I : InlineAsmMemoryOpIndexes) {
614 MachineOperand &MO =
UseMI.getOperand(
I + 1);
619 switch (
UseMI.getOpcode()) {
620 case RISCV::INLINEASM:
621 case RISCV::INLINEASM_BR:
623 case RISCV::PseudoCCLD:
624 case RISCV::PseudoCCLW:
625 case RISCV::PseudoCCLWU:
626 case RISCV::PseudoCCLH:
627 case RISCV::PseudoCCLHU:
628 case RISCV::PseudoCCLB:
629 case RISCV::PseudoCCLBU:
661 MachineOperand &MO =
UseMI.getOperand(ImmIdx);
662 if (
Hi.getOpcode() == RISCV::QC_E_LI) {
676 Lo.eraseFromParent();
684bool RISCVMergeBaseOffsetOpt::foldShxaddIntoScaledMemory(MachineInstr &
Hi,
686 if (!ST->hasVendorXqcisls() || ST->
is64Bit())
689 if (
Hi.getOpcode() != RISCV::QC_E_LI)
711 case RISCV::QC_SHLADD:
738 NewOpc = RISCV::QC_LRB;
741 NewOpc = RISCV::QC_LRBU;
744 NewOpc = RISCV::QC_LRH;
747 NewOpc = RISCV::QC_LRHU;
750 NewOpc = RISCV::QC_LRW;
753 NewOpc = RISCV::QC_SRB;
756 NewOpc = RISCV::QC_SRH;
759 NewOpc = RISCV::QC_SRW;
775 Hi.getOperand(1).setOffset(NewOffset);
796bool RISCVMergeBaseOffsetOpt::runOnMachineFunction(
MachineFunction &Fn) {
802 bool MadeChange =
false;
804 for (MachineBasicBlock &
MBB : Fn) {
806 for (MachineInstr &
Hi :
MBB) {
807 MachineInstr *
Lo =
nullptr;
808 if (!detectFoldable(
Hi,
Lo))
810 MadeChange |= detectAndFoldOffset(
Hi, *
Lo);
811 MadeChange |= foldIntoMemoryOps(
Hi, *
Lo);
812 MadeChange |= foldShxaddIntoScaledMemory(
Hi, *
Lo);
821 return new RISCVMergeBaseOffsetOpt();
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)
static void overwriteMachineOperandInPlace(MachineOperand &MO, const MachineOperand &ImmOp)
#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:
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
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
LLVM_ABI const MachineOperand & getDebugExpressionOp() const
Return the operand for the complex address expression referenced by this DBG_VALUE instruction.
LLVM_ABI const DIExpression * getDebugExpression() const
Return the complex address expression referenced by this DBG_VALUE instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
bool isDebugValue() const
unsigned getDebugOperandIndex(const MachineOperand *Op) const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
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.
void setMetadata(const MDNode *MD)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
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.
LLVM_ABI void ChangeToCPI(unsigned Idx, int Offset, unsigned TargetFlags=0)
ChangeToCPI - Replace this operand with a new constant pool index operand.
MCSymbol * getMCSymbol() const
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ 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,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
LLVM_ABI void markUsesInDebugValueAsUndef(Register Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
use_instr_iterator use_instr_begin(Register RegNo) const
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
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)
Represent a constant reference to a string, i.e.
bool isSized() 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.
@ 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)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.