[llvm] [APint] Add fast path for APInt::urem if RHS is power of 2 (PR #189245)
Max Graey via llvm-commits
llvm-commits at lists.llvm.org
Sun Mar 29 06:25:03 PDT 2026
https://github.com/MaxGraey created https://github.com/llvm/llvm-project/pull/189245
None
>From a1cb047f0eec2681595fc7ba25e10b9bbc8e54ca Mon Sep 17 00:00:00 2001
From: MaxGraey <maxgraey at gmail.com>
Date: Sun, 29 Mar 2026 16:23:58 +0300
Subject: [PATCH] add fast path for APInt::urem if RHS is power of 2
---
llvm/lib/Support/APInt.cpp | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/llvm/lib/Support/APInt.cpp b/llvm/lib/Support/APInt.cpp
index 0a9cda5299fc8..55c7e4f004132 100644
--- a/llvm/lib/Support/APInt.cpp
+++ b/llvm/lib/Support/APInt.cpp
@@ -1705,6 +1705,9 @@ APInt APInt::urem(const APInt &RHS) const {
if (lhsWords == 1)
// All high words are zero, just use native remainder
return APInt(BitWidth, U.pVal[0] % RHS.U.pVal[0]);
+ if (RHS.isPowerOf2())
+ // X % 2^w ===> X & (2^w - 1)
+ return trunc(RHS.logBase2());
// We have to compute it the hard way. Invoke the Knuth divide algorithm.
APInt Remainder(BitWidth, 0);
@@ -1737,6 +1740,9 @@ uint64_t APInt::urem(uint64_t RHS) const {
if (lhsWords == 1)
// All high words are zero, just use native remainder
return U.pVal[0] % RHS;
+ if (llvm::isPowerOf2_64(RHS))
+ // X % 2^w ===> X & (2^w - 1)
+ return getZExtValue() & (RHS - 1);
// We have to compute it the hard way. Invoke the Knuth divide algorithm.
uint64_t Remainder;
More information about the llvm-commits
mailing list