[llvm] [SelectionDAG] Optimize 32-bit udiv with 33-bit magic constants on 64-bit targets (PR #181288)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Thu Feb 19 09:48:20 PST 2026


================
@@ -151,5 +153,19 @@ UnsignedDivisionByConstantInfo::get(const APInt &D, unsigned LeadingZeros,
     Retval.PostShift -= 1;
   }
   Retval.PreShift = 0;
+
+  // For 32-bit IsAdd case with AllowWidenOptimization, compute widened magic.
+  // This is for optimizing 32-bit division using 64-bit multiplication.
+  // The actual magic constant is 2^32 + Magic (33-bit).
+  // We pre-shift it left by (64 - OriginalShift) to avoid runtime shift.
+  if (Retval.IsAdd && AllowWidenOptimization &&
+      D.getBitWidth() == 32) {
+    unsigned OriginalShift = Retval.PostShift + 33;
+    // Since PostShift >= 1, shift amount is at most 30, so 64 bits suffice.
+    Retval.Magic = (APInt(64, 1).shl(32) + Retval.Magic.zext(64))
+                       .shl(64 - OriginalShift);
+    Retval.Widen = true;
----------------
topperc wrote:

Clear the IsAdd bit and shift amounts. The struct result needs to completely describe the desired result.

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


More information about the llvm-commits mailing list