[llvm] [RISCV][TII] Add and use new hook to optimize/canonicalize instructions after MachineCopyPropagation (PR #137973)

Alex Bradbury via llvm-commits llvm-commits at lists.llvm.org
Wed Apr 30 09:30:33 PDT 2025


================
@@ -3850,6 +3865,209 @@ MachineInstr *RISCVInstrInfo::commuteInstructionImpl(MachineInstr &MI,
   return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
 }
 
+bool RISCVInstrInfo::optimizeInstruction(MachineInstr &MI) const {
+  switch (MI.getOpcode()) {
+  default:
+    break;
+  case RISCV::OR:
+  case RISCV::XOR:
+      // Normalize:
+      // [x]or rd, zero, rs => [x]or rd, rs, zero
+      if (MI.getOperand(1).getReg() == RISCV::X0) {
+        MachineOperand MO1 = MI.getOperand(1);
+        MI.removeOperand(1);
+        MI.addOperand(MO1);
+      }
+      // [x]or rd, rs, zero => addi rd, rs, 0
+      if (MI.getOperand(2).getReg() == RISCV::X0) {
+        MI.getOperand(2).ChangeToImmediate(0);
+        MI.setDesc(get(RISCV::ADDI));
+        return true;
+      }
+      // xor rd, rs, rs => li rd, rs, 0
+      if (MI.getOpcode() == RISCV::XOR && MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
+        MI.getOperand(2).ChangeToImmediate(0);
+        MI.setDesc(get(RISCV::ADDI));
+        return true;
+      }
+      break;
+  case RISCV::ADDW:
+      // Normalize:
+      // addw rd, zero, rs => addw rd, rs, zero
+      if (MI.getOperand(1).getReg() == RISCV::X0) {
+        MachineOperand MO1 = MI.getOperand(1);
+        MI.removeOperand(1);
+        MI.addOperand(MO1);
+      }
+      // addw rd, rs, zero => addiw rd, rs, 0
+      if (MI.getOperand(2).getReg() == RISCV::X0) {
+        MI.getOperand(2).ChangeToImmediate(0);
+        MI.setDesc(get(RISCV::ADDIW));
+        return true;
+      }
+      break;
+  case RISCV::SUB:
+  case RISCV::PACK:
+  case RISCV::PACKW:
+      // sub rd, rs, zero => addi rd, rs, 0
+      // pack[w] rd, rs, zero => addi rd, rs, zero
----------------
asb wrote:

As always, thank you for your close attention to detail and sorry that I've had to rely on it! I'm not quite sure how I ended up writing these pack patterns - I've removed for now.

https://github.com/llvm/llvm-project/pull/137973


More information about the llvm-commits mailing list