[PATCH] D140636: [Support] Fix what I think is an off by 1 bug in UnsignedDivisionByConstantInfo.

Craig Topper via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Fri Dec 23 13:55:04 PST 2022


craig.topper created this revision.
craig.topper added reviewers: bkramer, efriedma, regehr, RKSimon, spatel.
Herald added subscribers: StephenFan, hiraditya.
Herald added a project: All.
craig.topper requested review of this revision.
Herald added a project: LLVM.

The code in Hacker's Delight says
nc = -1 - (-d)%d;

But we have
`NC = AllOnes - (AllOnes-D)%D`

The Hacker's Delight code is written for the LeadingZeros==0 case.
`AllOnes - D` is not the same as `-d` from Hacker's Delight.

This patch changes the code to
`NC = AllOnes - (AllOnes+1-D)%D`

This will increment AllOnes to 0 in the LeadingZeros==0 case. This
will make it equivalent to -D. I believe this is also correct for
LeadingZeros>0.

I've been unable to find a case that changes with the new code.
I've checked all divisors for i8 and i16 udiv and the resulting
code is the same. i32 is a much larger search space to check.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D140636

Files:
  llvm/lib/Support/DivisionByConstantInfo.cpp


Index: llvm/lib/Support/DivisionByConstantInfo.cpp
===================================================================
--- llvm/lib/Support/DivisionByConstantInfo.cpp
+++ llvm/lib/Support/DivisionByConstantInfo.cpp
@@ -74,7 +74,7 @@
   APInt SignedMin = APInt::getSignedMinValue(D.getBitWidth());
   APInt SignedMax = APInt::getSignedMaxValue(D.getBitWidth());
 
-  APInt NC = AllOnes - (AllOnes - D).urem(D);
+  APInt NC = AllOnes - (AllOnes + 1 - D).urem(D);
   unsigned P = D.getBitWidth() - 1; // initialize P
   APInt Q1, R1, Q2, R2;
   // initialize Q1 = 2P/NC; R1 = rem(2P,NC)


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D140636.485154.patch
Type: text/x-patch
Size: 584 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221223/bfe6261d/attachment.bin>


More information about the llvm-commits mailing list