[llvm] [ConstantRange] Improve `shlWithNoWrap` (PR #101800)

via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 3 10:12:07 PDT 2024


================
@@ -1624,12 +1624,43 @@ ConstantRange ConstantRange::shlWithNoWrap(const ConstantRange &Other,
     return getEmpty();
 
   ConstantRange Result = shl(Other);
+  if (!NoWrapKind)
+    return Result;
 
-  if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap)
-    Result = Result.intersectWith(sshl_sat(Other), RangeType);
+  KnownBits Known = toKnownBits();
+
+  if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap) {
+    ConstantRange ShAmtRange = Other;
+    if (isAllNonNegative())
+      ShAmtRange = ShAmtRange.intersectWith(
+          ConstantRange(APInt::getZero(getBitWidth()),
+                        APInt(getBitWidth(), Known.countMaxLeadingZeros())),
+          Unsigned);
+    else if (isAllNegative())
+      ShAmtRange = ShAmtRange.intersectWith(
+          ConstantRange(APInt::getZero(getBitWidth()),
+                        APInt(getBitWidth(), Known.countMaxLeadingOnes())),
+          Unsigned);
----------------
goldsteinn wrote:

Maybe simpler:
```
std::optional<APInt> Clamp;
if (isAllNonNegative())
  Clamp = Known.CountMaxLeadingZeros();
else if(isAllNegative())
  Clamp = Known.countMaxLeadingOnes();
if(Clamp)
  ShAmtRange = ShAmtRange.intersectWith(..., APInt(getBitWidth(), *Clamp));
```

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


More information about the llvm-commits mailing list