[llvm] [RISCV] Add a check in lowerSELECT after foldBinOpIntoSelectIfProfitable (PR #97391)

via llvm-commits llvm-commits at lists.llvm.org
Tue Jul 2 00:20:18 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-risc-v

Author: None (Yunzezhu94)

<details>
<summary>Changes</summary>

In certain case foldBinOpIntoSelectIfProfitable may return a constant node, the node will be lowered in lowerSELECT and lead to crash. This patch fix the bug by adding an extra check before lowerSELECT.

Issue: https://github.com/llvm/llvm-project/issues/97390

---
Full diff: https://github.com/llvm/llvm-project/pull/97391.diff


2 Files Affected:

- (modified) llvm/lib/Target/RISCV/RISCVISelLowering.cpp (+4-1) 
- (modified) llvm/test/CodeGen/RISCV/fold-binop-into-select.ll (+12) 


``````````diff
diff --git a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
index ee45f730dc450..5b3ad99ce3711 100644
--- a/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVISelLowering.cpp
@@ -7664,7 +7664,10 @@ SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
       if (SDValue NewSel = foldBinOpIntoSelectIfProfitable(*Op->use_begin(),
                                                            DAG, Subtarget)) {
         DAG.ReplaceAllUsesWith(BinOp, &NewSel);
-        return lowerSELECT(NewSel, DAG);
+        if (NewSel.getOpcode() == ISD::SELECT)
+          return lowerSELECT(NewSel, DAG);
+        else
+          return NewSel;
       }
     }
   }
diff --git a/llvm/test/CodeGen/RISCV/fold-binop-into-select.ll b/llvm/test/CodeGen/RISCV/fold-binop-into-select.ll
index 1512db87b9311..8b9bafbbf4476 100644
--- a/llvm/test/CodeGen/RISCV/fold-binop-into-select.ll
+++ b/llvm/test/CodeGen/RISCV/fold-binop-into-select.ll
@@ -58,3 +58,15 @@ entry:
   %res = sub i64 2, %select_
   ret i64 %res
 }
+
+define i64 @fold_binop_into_select_return_constant(i1 %c) {
+; CHECK-LABEL: fold_binop_into_select_return_constant:
+; CHECK:       # %bb.0: # %entry
+; CHECK-NEXT:    li a0, 0
+; CHECK-NEXT:    ret
+entry:
+  %select1 = select i1 %c, i32 4, i32 8
+  %select2 = sext i32 %select1 to i64
+  %div1 = sdiv i64 %select2, -5141143369814759789
+  ret i64 %div1
+}

``````````

</details>


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


More information about the llvm-commits mailing list