1 //===-- KnownBits.cpp - Stores known zeros/ones ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a class for representing known zeros and ones used by
10 // computeKnownBits.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/KnownBits.h"
15 #include <cassert>
16 
17 using namespace llvm;
18 
19 static KnownBits computeForAddCarry(
20     const KnownBits &LHS, const KnownBits &RHS,
21     bool CarryZero, bool CarryOne) {
22   assert(!(CarryZero && CarryOne) &&
23          "Carry can't be zero and one at the same time");
24 
25   APInt PossibleSumZero = LHS.getMaxValue() + RHS.getMaxValue() + !CarryZero;
26   APInt PossibleSumOne = LHS.getMinValue() + RHS.getMinValue() + CarryOne;
27 
28   // Compute known bits of the carry.
29   APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero);
30   APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One;
31 
32   // Compute set of known bits (where all three relevant bits are known).
33   APInt LHSKnownUnion = LHS.Zero | LHS.One;
34   APInt RHSKnownUnion = RHS.Zero | RHS.One;
35   APInt CarryKnownUnion = std::move(CarryKnownZero) | CarryKnownOne;
36   APInt Known = std::move(LHSKnownUnion) & RHSKnownUnion & CarryKnownUnion;
37 
38   assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
39          "known bits of sum differ");
40 
41   // Compute known bits of the result.
42   KnownBits KnownOut;
43   KnownOut.Zero = ~std::move(PossibleSumZero) & Known;
44   KnownOut.One = std::move(PossibleSumOne) & Known;
45   return KnownOut;
46 }
47 
48 KnownBits KnownBits::computeForAddCarry(
49     const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry) {
50   assert(Carry.getBitWidth() == 1 && "Carry must be 1-bit");
51   return ::computeForAddCarry(
52       LHS, RHS, Carry.Zero.getBoolValue(), Carry.One.getBoolValue());
53 }
54 
55 KnownBits KnownBits::computeForAddSub(bool Add, bool NSW,
56                                       const KnownBits &LHS, KnownBits RHS) {
57   KnownBits KnownOut;
58   if (Add) {
59     // Sum = LHS + RHS + 0
60     KnownOut = ::computeForAddCarry(
61         LHS, RHS, /*CarryZero*/true, /*CarryOne*/false);
62   } else {
63     // Sum = LHS + ~RHS + 1
64     std::swap(RHS.Zero, RHS.One);
65     KnownOut = ::computeForAddCarry(
66         LHS, RHS, /*CarryZero*/false, /*CarryOne*/true);
67   }
68 
69   // Are we still trying to solve for the sign bit?
70   if (!KnownOut.isNegative() && !KnownOut.isNonNegative()) {
71     if (NSW) {
72       // Adding two non-negative numbers, or subtracting a negative number from
73       // a non-negative one, can't wrap into negative.
74       if (LHS.isNonNegative() && RHS.isNonNegative())
75         KnownOut.makeNonNegative();
76       // Adding two negative numbers, or subtracting a non-negative number from
77       // a negative one, can't wrap into non-negative.
78       else if (LHS.isNegative() && RHS.isNegative())
79         KnownOut.makeNegative();
80     }
81   }
82 
83   return KnownOut;
84 }
85 
86 KnownBits KnownBits::makeGE(const APInt &Val) const {
87   // Count the number of leading bit positions where our underlying value is
88   // known to be less than or equal to Val.
89   unsigned N = (Zero | Val).countLeadingOnes();
90 
91   // For each of those bit positions, if Val has a 1 in that bit then our
92   // underlying value must also have a 1.
93   APInt MaskedVal(Val);
94   MaskedVal.clearLowBits(getBitWidth() - N);
95   return KnownBits(Zero, One | MaskedVal);
96 }
97 
98 KnownBits KnownBits::umax(const KnownBits &LHS, const KnownBits &RHS) {
99   // If we can prove that LHS >= RHS then use LHS as the result. Likewise for
100   // RHS. Ideally our caller would already have spotted these cases and
101   // optimized away the umax operation, but we handle them here for
102   // completeness.
103   if (LHS.getMinValue().uge(RHS.getMaxValue()))
104     return LHS;
105   if (RHS.getMinValue().uge(LHS.getMaxValue()))
106     return RHS;
107 
108   // If the result of the umax is LHS then it must be greater than or equal to
109   // the minimum possible value of RHS. Likewise for RHS. Any known bits that
110   // are common to these two values are also known in the result.
111   KnownBits L = LHS.makeGE(RHS.getMinValue());
112   KnownBits R = RHS.makeGE(LHS.getMinValue());
113   return KnownBits::commonBits(L, R);
114 }
115 
116 KnownBits KnownBits::umin(const KnownBits &LHS, const KnownBits &RHS) {
117   // Flip the range of values: [0, 0xFFFFFFFF] <-> [0xFFFFFFFF, 0]
118   auto Flip = [](const KnownBits &Val) { return KnownBits(Val.One, Val.Zero); };
119   return Flip(umax(Flip(LHS), Flip(RHS)));
120 }
121 
122 KnownBits KnownBits::smax(const KnownBits &LHS, const KnownBits &RHS) {
123   // Flip the range of values: [-0x80000000, 0x7FFFFFFF] <-> [0, 0xFFFFFFFF]
124   auto Flip = [](const KnownBits &Val) {
125     unsigned SignBitPosition = Val.getBitWidth() - 1;
126     APInt Zero = Val.Zero;
127     APInt One = Val.One;
128     Zero.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
129     One.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
130     return KnownBits(Zero, One);
131   };
132   return Flip(umax(Flip(LHS), Flip(RHS)));
133 }
134 
135 KnownBits KnownBits::smin(const KnownBits &LHS, const KnownBits &RHS) {
136   // Flip the range of values: [-0x80000000, 0x7FFFFFFF] <-> [0xFFFFFFFF, 0]
137   auto Flip = [](const KnownBits &Val) {
138     unsigned SignBitPosition = Val.getBitWidth() - 1;
139     APInt Zero = Val.One;
140     APInt One = Val.Zero;
141     Zero.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
142     One.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
143     return KnownBits(Zero, One);
144   };
145   return Flip(umax(Flip(LHS), Flip(RHS)));
146 }
147 
148 KnownBits KnownBits::shl(const KnownBits &LHS, const KnownBits &RHS) {
149   unsigned BitWidth = LHS.getBitWidth();
150   KnownBits Known(BitWidth);
151 
152   // If the shift amount is a valid constant then transform LHS directly.
153   if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
154     unsigned Shift = RHS.getConstant().getZExtValue();
155     Known = LHS;
156     Known.Zero <<= Shift;
157     Known.One <<= Shift;
158     // Low bits are known zero.
159     Known.Zero.setLowBits(Shift);
160     return Known;
161   }
162 
163   // No matter the shift amount, the trailing zeros will stay zero.
164   unsigned MinTrailingZeros = LHS.countMinTrailingZeros();
165 
166   // Minimum shift amount low bits are known zero.
167   if (RHS.getMinValue().ult(BitWidth)) {
168     MinTrailingZeros += RHS.getMinValue().getZExtValue();
169     MinTrailingZeros = std::min(MinTrailingZeros, BitWidth);
170   }
171 
172   Known.Zero.setLowBits(MinTrailingZeros);
173   return Known;
174 }
175 
176 KnownBits KnownBits::lshr(const KnownBits &LHS, const KnownBits &RHS) {
177   unsigned BitWidth = LHS.getBitWidth();
178   KnownBits Known(BitWidth);
179 
180   if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
181     unsigned Shift = RHS.getConstant().getZExtValue();
182     Known = LHS;
183     Known.Zero.lshrInPlace(Shift);
184     Known.One.lshrInPlace(Shift);
185     // High bits are known zero.
186     Known.Zero.setHighBits(Shift);
187     return Known;
188   }
189 
190   // No matter the shift amount, the leading zeros will stay zero.
191   unsigned MinLeadingZeros = LHS.countMinLeadingZeros();
192 
193   // Minimum shift amount high bits are known zero.
194   if (RHS.getMinValue().ult(BitWidth)) {
195     MinLeadingZeros += RHS.getMinValue().getZExtValue();
196     MinLeadingZeros = std::min(MinLeadingZeros, BitWidth);
197   }
198 
199   Known.Zero.setHighBits(MinLeadingZeros);
200   return Known;
201 }
202 
203 KnownBits KnownBits::ashr(const KnownBits &LHS, const KnownBits &RHS) {
204   unsigned BitWidth = LHS.getBitWidth();
205   KnownBits Known(BitWidth);
206 
207   if (RHS.isConstant() && RHS.getConstant().ult(BitWidth)) {
208     unsigned Shift = RHS.getConstant().getZExtValue();
209     Known = LHS;
210     Known.Zero.ashrInPlace(Shift);
211     Known.One.ashrInPlace(Shift);
212     return Known;
213   }
214 
215   // No matter the shift amount, the leading sign bits will stay.
216   unsigned MinLeadingZeros = LHS.countMinLeadingZeros();
217   unsigned MinLeadingOnes = LHS.countMinLeadingOnes();
218 
219   // Minimum shift amount high bits are known sign bits.
220   if (RHS.getMinValue().ult(BitWidth)) {
221     if (MinLeadingZeros) {
222       MinLeadingZeros += RHS.getMinValue().getZExtValue();
223       MinLeadingZeros = std::min(MinLeadingZeros, BitWidth);
224     }
225     if (MinLeadingOnes) {
226       MinLeadingOnes += RHS.getMinValue().getZExtValue();
227       MinLeadingOnes = std::min(MinLeadingOnes, BitWidth);
228     }
229   }
230 
231   Known.Zero.setHighBits(MinLeadingZeros);
232   Known.One.setHighBits(MinLeadingOnes);
233   return Known;
234 }
235 
236 KnownBits KnownBits::abs(bool IntMinIsPoison) const {
237   // If the source's MSB is zero then we know the rest of the bits already.
238   if (isNonNegative())
239     return *this;
240 
241   // Absolute value preserves trailing zero count.
242   KnownBits KnownAbs(getBitWidth());
243   KnownAbs.Zero.setLowBits(countMinTrailingZeros());
244 
245   // We only know that the absolute values's MSB will be zero if INT_MIN is
246   // poison, or there is a set bit that isn't the sign bit (otherwise it could
247   // be INT_MIN).
248   if (IntMinIsPoison || (!One.isNullValue() && !One.isMinSignedValue()))
249     KnownAbs.Zero.setSignBit();
250 
251   // FIXME: Handle known negative input?
252   // FIXME: Calculate the negated Known bits and combine them?
253   return KnownAbs;
254 }
255 
256 KnownBits KnownBits::computeForMul(const KnownBits &LHS, const KnownBits &RHS) {
257   unsigned BitWidth = LHS.getBitWidth();
258 
259   assert(!LHS.hasConflict() && !RHS.hasConflict());
260   // Compute a conservative estimate for high known-0 bits.
261   unsigned LeadZ =
262       std::max(LHS.countMinLeadingZeros() + RHS.countMinLeadingZeros(),
263                BitWidth) -
264       BitWidth;
265   LeadZ = std::min(LeadZ, BitWidth);
266 
267   // The result of the bottom bits of an integer multiply can be
268   // inferred by looking at the bottom bits of both operands and
269   // multiplying them together.
270   // We can infer at least the minimum number of known trailing bits
271   // of both operands. Depending on number of trailing zeros, we can
272   // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
273   // a and b are divisible by m and n respectively.
274   // We then calculate how many of those bits are inferrable and set
275   // the output. For example, the i8 mul:
276   //  a = XXXX1100 (12)
277   //  b = XXXX1110 (14)
278   // We know the bottom 3 bits are zero since the first can be divided by
279   // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
280   // Applying the multiplication to the trimmed arguments gets:
281   //    XX11 (3)
282   //    X111 (7)
283   // -------
284   //    XX11
285   //   XX11
286   //  XX11
287   // XX11
288   // -------
289   // XXXXX01
290   // Which allows us to infer the 2 LSBs. Since we're multiplying the result
291   // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
292   // The proof for this can be described as:
293   // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
294   //      (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
295   //                    umin(countTrailingZeros(C2), C6) +
296   //                    umin(C5 - umin(countTrailingZeros(C1), C5),
297   //                         C6 - umin(countTrailingZeros(C2), C6)))) - 1)
298   // %aa = shl i8 %a, C5
299   // %bb = shl i8 %b, C6
300   // %aaa = or i8 %aa, C1
301   // %bbb = or i8 %bb, C2
302   // %mul = mul i8 %aaa, %bbb
303   // %mask = and i8 %mul, C7
304   //   =>
305   // %mask = i8 ((C1*C2)&C7)
306   // Where C5, C6 describe the known bits of %a, %b
307   // C1, C2 describe the known bottom bits of %a, %b.
308   // C7 describes the mask of the known bits of the result.
309   const APInt &Bottom0 = LHS.One;
310   const APInt &Bottom1 = RHS.One;
311 
312   // How many times we'd be able to divide each argument by 2 (shr by 1).
313   // This gives us the number of trailing zeros on the multiplication result.
314   unsigned TrailBitsKnown0 = (LHS.Zero | LHS.One).countTrailingOnes();
315   unsigned TrailBitsKnown1 = (RHS.Zero | RHS.One).countTrailingOnes();
316   unsigned TrailZero0 = LHS.countMinTrailingZeros();
317   unsigned TrailZero1 = RHS.countMinTrailingZeros();
318   unsigned TrailZ = TrailZero0 + TrailZero1;
319 
320   // Figure out the fewest known-bits operand.
321   unsigned SmallestOperand =
322       std::min(TrailBitsKnown0 - TrailZero0, TrailBitsKnown1 - TrailZero1);
323   unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
324 
325   APInt BottomKnown =
326       Bottom0.getLoBits(TrailBitsKnown0) * Bottom1.getLoBits(TrailBitsKnown1);
327 
328   KnownBits Res(BitWidth);
329   Res.Zero.setHighBits(LeadZ);
330   Res.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
331   Res.One = BottomKnown.getLoBits(ResultBitsKnown);
332   return Res;
333 }
334 
335 KnownBits KnownBits::udiv(const KnownBits &LHS, const KnownBits &RHS) {
336   unsigned BitWidth = LHS.getBitWidth();
337   assert(!LHS.hasConflict() && !RHS.hasConflict());
338   KnownBits Known(BitWidth);
339 
340   // For the purposes of computing leading zeros we can conservatively
341   // treat a udiv as a logical right shift by the power of 2 known to
342   // be less than the denominator.
343   unsigned LeadZ = LHS.countMinLeadingZeros();
344   unsigned RHSMaxLeadingZeros = RHS.countMaxLeadingZeros();
345 
346   if (RHSMaxLeadingZeros != BitWidth)
347     LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
348 
349   Known.Zero.setHighBits(LeadZ);
350   return Known;
351 }
352 
353 KnownBits KnownBits::urem(const KnownBits &LHS, const KnownBits &RHS) {
354   unsigned BitWidth = LHS.getBitWidth();
355   assert(!LHS.hasConflict() && !RHS.hasConflict());
356   KnownBits Known(BitWidth);
357 
358   if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
359     // The upper bits are all zero, the lower ones are unchanged.
360     APInt LowBits = RHS.getConstant() - 1;
361     Known.Zero = LHS.Zero | ~LowBits;
362     Known.One = LHS.One & LowBits;
363     return Known;
364   }
365 
366   // Since the result is less than or equal to either operand, any leading
367   // zero bits in either operand must also exist in the result.
368   uint32_t Leaders =
369       std::max(LHS.countMinLeadingZeros(), RHS.countMinLeadingZeros());
370   Known.Zero.setHighBits(Leaders);
371   return Known;
372 }
373 
374 KnownBits KnownBits::srem(const KnownBits &LHS, const KnownBits &RHS) {
375   unsigned BitWidth = LHS.getBitWidth();
376   assert(!LHS.hasConflict() && !RHS.hasConflict());
377   KnownBits Known(BitWidth);
378 
379   if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
380     // The low bits of the first operand are unchanged by the srem.
381     APInt LowBits = RHS.getConstant() - 1;
382     Known.Zero = LHS.Zero & LowBits;
383     Known.One = LHS.One & LowBits;
384 
385     // If the first operand is non-negative or has all low bits zero, then
386     // the upper bits are all zero.
387     if (LHS.isNonNegative() || LowBits.isSubsetOf(LHS.Zero))
388       Known.Zero |= ~LowBits;
389 
390     // If the first operand is negative and not all low bits are zero, then
391     // the upper bits are all one.
392     if (LHS.isNegative() && LowBits.intersects(LHS.One))
393       Known.One |= ~LowBits;
394     return Known;
395   }
396 
397   // The sign bit is the LHS's sign bit, except when the result of the
398   // remainder is zero. If it's known zero, our sign bit is also zero.
399   if (LHS.isNonNegative())
400     Known.makeNonNegative();
401   return Known;
402 }
403 
404 KnownBits &KnownBits::operator&=(const KnownBits &RHS) {
405   // Result bit is 0 if either operand bit is 0.
406   Zero |= RHS.Zero;
407   // Result bit is 1 if both operand bits are 1.
408   One &= RHS.One;
409   return *this;
410 }
411 
412 KnownBits &KnownBits::operator|=(const KnownBits &RHS) {
413   // Result bit is 0 if both operand bits are 0.
414   Zero &= RHS.Zero;
415   // Result bit is 1 if either operand bit is 1.
416   One |= RHS.One;
417   return *this;
418 }
419 
420 KnownBits &KnownBits::operator^=(const KnownBits &RHS) {
421   // Result bit is 0 if both operand bits are 0 or both are 1.
422   APInt Z = (Zero & RHS.Zero) | (One & RHS.One);
423   // Result bit is 1 if one operand bit is 0 and the other is 1.
424   One = (Zero & RHS.One) | (One & RHS.Zero);
425   Zero = std::move(Z);
426   return *this;
427 }
428