[llvm] [GlobalISel] Add G_ADD for computeNumSignBits (PR #159202)

Yatao Wang via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 2 11:07:06 PDT 2025


================
@@ -1959,6 +1959,41 @@ unsigned GISelValueTracking::computeNumSignBits(Register R,
 
     break;
   }
+  case TargetOpcode::G_ADD: {
+    Register Src2 = MI.getOperand(2).getReg();
+    unsigned Src2NumSignBits =
+        computeNumSignBits(Src2, DemandedElts, Depth + 1);
+    if (Src2NumSignBits == 1)
+      return 1; // Early out.
+
+    Register Src1 = MI.getOperand(1).getReg();
+    unsigned Src1NumSignBits =
+        computeNumSignBits(Src1, DemandedElts, Depth + 1);
+    if (Src1NumSignBits == 1)
+      return 1; // Early Out.
+
+    // Special case decrementing a value (ADD X, -1):
+    KnownBits Known2 = getKnownBits(Src2, DemandedElts, Depth);
+    if (Known2.isAllOnes()) {
+      KnownBits Known1 = getKnownBits(Src1, DemandedElts, Depth);
+      // If the input is known to be 0 or 1, the output is 0/-1, which is all
+      // sign bits set.
+      if ((Known1.Zero | 1).isAllOnes())
+        return TyBits;
+
+      // If the input is known to be positive (the sign bit is known clear),
+      // the output of the NEG has the same number of sign bits as the input.
----------------
ningxinr wrote:

Now that I think about it, you are right. -4 should have one more sign bit than +4.

But how did SelectionDAG get it right then? Has it been wrong the entire time? o.O

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


More information about the llvm-commits mailing list