[llvm] [RISCV][NFC] Fix UBSan issue in ISel (PR #181422)

Sam Elliott via llvm-commits llvm-commits at lists.llvm.org
Fri Feb 13 13:16:58 PST 2026


https://github.com/lenary created https://github.com/llvm/llvm-project/pull/181422

If `int Imm` is `INT64_MIN`, then negating this value overflows, which
is undefined behaviour. This adds this case to the tests, and avoids
this case.


>From 1d6a3a9bd86a01014510d0d0c0d6eac3a450a8d3 Mon Sep 17 00:00:00 2001
From: Sam Elliott <aelliott at qti.qualcomm.com>
Date: Fri, 13 Feb 2026 13:11:40 -0800
Subject: [PATCH 1/2] Add test

---
 llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll b/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll
index 3c02efbfe02f9..a69b13e0ca450 100644
--- a/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll
+++ b/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll
@@ -74,3 +74,21 @@ define i64 @add_multiuse_const(i64 %x, i64 %y) {
   %xor = xor i64 %a, %b
   ret i64 %xor
 }
+
+
+define i64 @add_i64_min(i64 %x) {
+; NOZBS-LABEL: add_i64_min:
+; NOZBS:       # %bb.0:
+; NOZBS-NEXT:    li a1, -1
+; NOZBS-NEXT:    slli a1, a1, 63
+; NOZBS-NEXT:    add a0, a0, a1
+; NOZBS-NEXT:    ret
+;
+; ZBS-LABEL: add_i64_min:
+; ZBS:       # %bb.0:
+; ZBS-NEXT:    bseti a1, zero, 63
+; ZBS-NEXT:    add a0, a0, a1
+; ZBS-NEXT:    ret
+  %a = add i64 %x, -9223372036854775808
+  ret i64 %a
+}

>From 81b74316d93680fa40ec7d2e05d59c8ac7ee5f28 Mon Sep 17 00:00:00 2001
From: Sam Elliott <aelliott at qti.qualcomm.com>
Date: Fri, 13 Feb 2026 13:12:15 -0800
Subject: [PATCH 2/2] [RISCV][NFC] Fix UBSan Issue in ISel

If `int Imm` is `INT64_MIN`, then negating this value overflows, which
is undefined behaviour. This adds this case to the tests, and avoids
this case.

Co-authored-by: Sampath Vutkoori <svutkoor at qti.qualcomm.com>
---
 llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp b/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
index db65d6ac1a5df..922475259fede 100644
--- a/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
+++ b/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp
@@ -4047,6 +4047,8 @@ bool RISCVDAGToDAGISel::selectNegImm(SDValue N, SDValue &Val) {
   int64_t Imm = cast<ConstantSDNode>(N)->getSExtValue();
   if (isInt<32>(Imm))
     return false;
+  if (Imm == INT64_MIN)
+    return false;
 
   for (const SDNode *U : N->users()) {
     switch (U->getOpcode()) {



More information about the llvm-commits mailing list