From 6eeb03b5a28d048701313c9ec4edf4fbbbc842bb Mon Sep 17 00:00:00 2001 From: Sam Elliott Date: Fri, 13 Feb 2026 14:26:24 -0800 Subject: [PATCH] [RISCV][NFC] Fix UBSan issue in ISel (#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. Co-authored-by: Sampath Vutkoori --- llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp | 2 ++ llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp b/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp index 9435c7767de1..7d61ea633213 100644 --- a/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp +++ b/llvm/lib/Target/RISCV/RISCVISelDAGToDAG.cpp @@ -4067,6 +4067,8 @@ bool RISCVDAGToDAGISel::selectNegImm(SDValue N, SDValue &Val) { int64_t Imm = cast(N)->getSExtValue(); if (isInt<32>(Imm)) return false; + if (Imm == INT64_MIN) + return false; for (const SDNode *U : N->users()) { switch (U->getOpcode()) { diff --git a/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll b/llvm/test/CodeGen/RISCV/add-imm64-to-sub.ll index 3c02efbfe02f..a69b13e0ca45 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 +}