@@ -21,6 +21,30 @@ using namespace PatternMatch;
2121
2222#define DEBUG_TYPE " instcombine"
2323
24+ bool canTryToConstantAddTwoShiftAmounts (Value *Sh0, Value *ShAmt0, Value *Sh1,
25+ Value *ShAmt1) {
26+ // We have two shift amounts from two different shifts. The types of those
27+ // shift amounts may not match. If that's the case let's bailout now..
28+ if (ShAmt0->getType () != ShAmt1->getType ())
29+ return false ;
30+
31+ // As input, we have the following pattern:
32+ // Sh0 (Sh1 X, Q), K
33+ // We want to rewrite that as:
34+ // Sh x, (Q+K) iff (Q+K) u< bitwidth(x)
35+ // While we know that originally (Q+K) would not overflow
36+ // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
37+ // shift amounts. so it may now overflow in smaller bitwidth.
38+ // To ensure that does not happen, we need to ensure that the total maximal
39+ // shift amount is still representable in that smaller bit width.
40+ unsigned MaximalPossibleTotalShiftAmount =
41+ (Sh0->getType ()->getScalarSizeInBits () - 1 ) +
42+ (Sh1->getType ()->getScalarSizeInBits () - 1 );
43+ APInt MaximalRepresentableShiftAmount =
44+ APInt::getAllOnesValue (ShAmt0->getType ()->getScalarSizeInBits ());
45+ return MaximalRepresentableShiftAmount.uge (MaximalPossibleTotalShiftAmount);
46+ }
47+
2448// Given pattern:
2549// (x shiftopcode Q) shiftopcode K
2650// we should rewrite it as
@@ -57,26 +81,8 @@ Value *InstCombinerImpl::reassociateShiftAmtsOfTwoSameDirectionShifts(
5781 if (!match (Sh1, m_Shift (m_Value (X), m_ZExtOrSelf (m_Value (ShAmt1)))))
5882 return nullptr ;
5983
60- // We have two shift amounts from two different shifts. The types of those
61- // shift amounts may not match. If that's the case let's bailout now..
62- if (ShAmt0->getType () != ShAmt1->getType ())
63- return nullptr ;
64-
65- // As input, we have the following pattern:
66- // Sh0 (Sh1 X, Q), K
67- // We want to rewrite that as:
68- // Sh x, (Q+K) iff (Q+K) u< bitwidth(x)
69- // While we know that originally (Q+K) would not overflow
70- // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
71- // shift amounts. so it may now overflow in smaller bitwidth.
72- // To ensure that does not happen, we need to ensure that the total maximal
73- // shift amount is still representable in that smaller bit width.
74- unsigned MaximalPossibleTotalShiftAmount =
75- (Sh0->getType ()->getScalarSizeInBits () - 1 ) +
76- (Sh1->getType ()->getScalarSizeInBits () - 1 );
77- APInt MaximalRepresentableShiftAmount =
78- APInt::getAllOnesValue (ShAmt0->getType ()->getScalarSizeInBits ());
79- if (MaximalRepresentableShiftAmount.ult (MaximalPossibleTotalShiftAmount))
84+ // Verify that it would be safe to try to add those two shift amounts.
85+ if (!canTryToConstantAddTwoShiftAmounts (Sh0, ShAmt0, Sh1, ShAmt1))
8086 return nullptr ;
8187
8288 // We are only looking for signbit extraction if we have two right shifts.
0 commit comments