[llvm] [DemandedBits] Support non-constant shift amounts (PR #148880)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Tue Aug 5 09:27:21 PDT 2025


================
@@ -76,6 +76,19 @@ void DemandedBits::determineLiveOperandBits(
           computeKnownBits(V2, Known2, DL, &AC, UserI, &DT);
         }
       };
+  auto GetShiftedRange = [&](uint64_t Min, uint64_t Max, bool ShiftLeft) {
+    auto ShiftF = [ShiftLeft](const APInt &Mask, unsigned ShiftAmnt) {
+      return ShiftLeft ? Mask.shl(ShiftAmnt) : Mask.lshr(ShiftAmnt);
+    };
+    AB = APInt::getZero(BitWidth);
+    uint64_t LoopRange = Max - Min;
+    APInt Mask = AOut;
+    for (unsigned ShiftAmnt = 1; ShiftAmnt <= LoopRange; ShiftAmnt <<= 1) {
----------------
topperc wrote:

I mean the shift amount from the instruction itself. computeKnownBits may tell us that the lsb(s) of the shift amount are known to be zero or one. This loop is trying to evaluate all possible shift amounts, but we don't exclude cases that would be impossible based on known values of the lsb(s).

Something like this does exist in the code from KnownBits::shl.

```
  // Find the common bits from all possible shifts.                              
  unsigned ShiftAmtZeroMask = RHS.Zero.zextOrTrunc(32).getZExtValue();           
  unsigned ShiftAmtOneMask = RHS.One.zextOrTrunc(32).getZExtValue();             
  Known.Zero.setAllBits();                                                       
  Known.One.setAllBits();                                                        
  for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount;           
       ++ShiftAmt) {                                                             
    // Skip if the shift amount is impossible.                                   
    if ((ShiftAmtZeroMask & ShiftAmt) != 0 ||                                    
        (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)                                
      continue;                                                                  
    Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt));                    
    if (Known.isUnknown())                                                       
      break;                                                                     
  }
```

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


More information about the llvm-commits mailing list