[llvm] [RISCV] Convert LWU to LW if possible in RISCVOptWInstrs (PR #144703)

Alex Bradbury via llvm-commits llvm-commits at lists.llvm.org
Sun Jul 20 07:19:05 PDT 2025


asb wrote:

I've implemented the refactoring suggested by @topperc in #149710. I'll merge in the changes and rework this once that lands. As noted in that PR, the logic changes for this patch become more minimal after that change:
```
--- a/llvm/lib/Target/RISCV/RISCVOptWInstrs.cpp
+++ b/llvm/lib/Target/RISCV/RISCVOptWInstrs.cpp
@@ -736,7 +736,8 @@ bool RISCVOptWInstrs::canonicalizeWSuffixes(MachineFunction &MF,
     for (MachineInstr &MI : MBB) {
       std::optional<unsigned> WOpc;
       std::optional<unsigned> NonWOpc;
-      switch (MI.getOpcode()) {
+      unsigned OrigOpc = MI.getOpcode();
+      switch (OrigOpc) {
       default:
         continue;
       case RISCV::ADDW:
@@ -786,7 +787,8 @@ bool RISCVOptWInstrs::canonicalizeWSuffixes(MachineFunction &MF,
         MadeChange = true;
         continue;
       }
-      if (ShouldPreferW && WOpc.has_value() && hasAllWUsers(MI, ST, MRI)) {
+      if ((ShouldPreferW || OrigOpc == RISCV::LWU) && WOpc.has_value() &&
+          hasAllWUsers(MI, ST, MRI)) {
         LLVM_DEBUG(dbgs() << "Replacing " << MI);
         MI.setDesc(TII.get(WOpc.value()));
         MI.clearFlag(MachineInstr::MIFlag::NoSWrap);
```

(The above retains the same behaviour as the current implementation of this PR - always converting LWU to LW if possible. It could be made to always convert LD to LW as happens with ST.preferWInst, but it's not clear it's beneficial to and I'm wary of introducing additional load narrowing. Specifically, I don't feel confident enough about this always being a semantically correct change - for instance if the LD would have caused an exception but the LW wouldn't have).

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


More information about the llvm-commits mailing list