LLVM 22.0.0git
KnownBits.cpp
Go to the documentation of this file.
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
15#include "llvm/Support/Debug.h"
17#include <cassert>
18
19using namespace llvm;
20
21KnownBits KnownBits::flipSignBit(const KnownBits &Val) {
22 unsigned SignBitPosition = Val.getBitWidth() - 1;
23 APInt Zero = Val.Zero;
24 APInt One = Val.One;
25 Zero.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
26 One.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
27 return KnownBits(Zero, One);
28}
29
31 bool CarryZero, bool CarryOne) {
32
33 APInt PossibleSumZero = LHS.getMaxValue() + RHS.getMaxValue() + !CarryZero;
34 APInt PossibleSumOne = LHS.getMinValue() + RHS.getMinValue() + CarryOne;
35
36 // Compute known bits of the carry.
37 APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero);
38 APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One;
39
40 // Compute set of known bits (where all three relevant bits are known).
41 APInt LHSKnownUnion = LHS.Zero | LHS.One;
42 APInt RHSKnownUnion = RHS.Zero | RHS.One;
43 APInt CarryKnownUnion = std::move(CarryKnownZero) | CarryKnownOne;
44 APInt Known = std::move(LHSKnownUnion) & RHSKnownUnion & CarryKnownUnion;
45
46 // Compute known bits of the result.
47 KnownBits KnownOut;
48 KnownOut.Zero = ~std::move(PossibleSumZero) & Known;
49 KnownOut.One = std::move(PossibleSumOne) & Known;
50 return KnownOut;
51}
52
54 const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry) {
55 assert(Carry.getBitWidth() == 1 && "Carry must be 1-bit");
56 return ::computeForAddCarry(
57 LHS, RHS, Carry.Zero.getBoolValue(), Carry.One.getBoolValue());
58}
59
60KnownBits KnownBits::computeForAddSub(bool Add, bool NSW, bool NUW,
61 const KnownBits &LHS,
62 const KnownBits &RHS) {
63 unsigned BitWidth = LHS.getBitWidth();
64 KnownBits KnownOut(BitWidth);
65 // This can be a relatively expensive helper, so optimistically save some
66 // work.
67 if (LHS.isUnknown() && RHS.isUnknown())
68 return KnownOut;
69
70 if (!LHS.isUnknown() && !RHS.isUnknown()) {
71 if (Add) {
72 // Sum = LHS + RHS + 0
73 KnownOut = ::computeForAddCarry(LHS, RHS, /*CarryZero=*/true,
74 /*CarryOne=*/false);
75 } else {
76 // Sum = LHS + ~RHS + 1
77 KnownBits NotRHS = RHS;
78 std::swap(NotRHS.Zero, NotRHS.One);
79 KnownOut = ::computeForAddCarry(LHS, NotRHS, /*CarryZero=*/false,
80 /*CarryOne=*/true);
81 }
82 }
83
84 // Handle add/sub given nsw and/or nuw.
85 if (NUW) {
86 if (Add) {
87 // (add nuw X, Y)
88 APInt MinVal = LHS.getMinValue().uadd_sat(RHS.getMinValue());
89 // None of the adds can end up overflowing, so min consecutive highbits
90 // in minimum possible of X + Y must all remain set.
91 if (NSW) {
92 unsigned NumBits = MinVal.trunc(BitWidth - 1).countl_one();
93 // If we have NSW as well, we also know we can't overflow the signbit so
94 // can start counting from 1 bit back.
95 KnownOut.One.setBits(BitWidth - 1 - NumBits, BitWidth - 1);
96 }
97 KnownOut.One.setHighBits(MinVal.countl_one());
98 } else {
99 // (sub nuw X, Y)
100 APInt MaxVal = LHS.getMaxValue().usub_sat(RHS.getMinValue());
101 // None of the subs can overflow at any point, so any common high bits
102 // will subtract away and result in zeros.
103 if (NSW) {
104 // If we have NSW as well, we also know we can't overflow the signbit so
105 // can start counting from 1 bit back.
106 unsigned NumBits = MaxVal.trunc(BitWidth - 1).countl_zero();
107 KnownOut.Zero.setBits(BitWidth - 1 - NumBits, BitWidth - 1);
108 }
109 KnownOut.Zero.setHighBits(MaxVal.countl_zero());
110 }
111 }
112
113 if (NSW) {
114 APInt MinVal;
115 APInt MaxVal;
116 if (Add) {
117 // (add nsw X, Y)
118 MinVal = LHS.getSignedMinValue().sadd_sat(RHS.getSignedMinValue());
119 MaxVal = LHS.getSignedMaxValue().sadd_sat(RHS.getSignedMaxValue());
120 } else {
121 // (sub nsw X, Y)
122 MinVal = LHS.getSignedMinValue().ssub_sat(RHS.getSignedMaxValue());
123 MaxVal = LHS.getSignedMaxValue().ssub_sat(RHS.getSignedMinValue());
124 }
125 if (MinVal.isNonNegative()) {
126 // If min is non-negative, result will always be non-neg (can't overflow
127 // around).
128 unsigned NumBits = MinVal.trunc(BitWidth - 1).countl_one();
129 KnownOut.One.setBits(BitWidth - 1 - NumBits, BitWidth - 1);
130 KnownOut.Zero.setSignBit();
131 }
132 if (MaxVal.isNegative()) {
133 // If max is negative, result will always be neg (can't overflow around).
134 unsigned NumBits = MaxVal.trunc(BitWidth - 1).countl_zero();
135 KnownOut.Zero.setBits(BitWidth - 1 - NumBits, BitWidth - 1);
136 KnownOut.One.setSignBit();
137 }
138 }
139
140 // Just return 0 if the nsw/nuw is violated and we have poison.
141 if (KnownOut.hasConflict())
142 KnownOut.setAllZero();
143 return KnownOut;
144}
145
146KnownBits KnownBits::computeForSubBorrow(const KnownBits &LHS, KnownBits RHS,
147 const KnownBits &Borrow) {
148 assert(Borrow.getBitWidth() == 1 && "Borrow must be 1-bit");
149
150 // LHS - RHS = LHS + ~RHS + 1
151 // Carry 1 - Borrow in ::computeForAddCarry
152 std::swap(RHS.Zero, RHS.One);
153 return ::computeForAddCarry(LHS, RHS,
154 /*CarryZero=*/Borrow.One.getBoolValue(),
155 /*CarryOne=*/Borrow.Zero.getBoolValue());
156}
157
158KnownBits KnownBits::sextInReg(unsigned SrcBitWidth) const {
159 unsigned BitWidth = getBitWidth();
160 assert(0 < SrcBitWidth && SrcBitWidth <= BitWidth &&
161 "Illegal sext-in-register");
162
163 if (SrcBitWidth == BitWidth)
164 return *this;
165
166 unsigned ExtBits = BitWidth - SrcBitWidth;
167 KnownBits Result;
168 Result.One = One << ExtBits;
169 Result.Zero = Zero << ExtBits;
170 Result.One.ashrInPlace(ExtBits);
171 Result.Zero.ashrInPlace(ExtBits);
172 return Result;
173}
174
175KnownBits KnownBits::makeGE(const APInt &Val) const {
176 // Count the number of leading bit positions where our underlying value is
177 // known to be less than or equal to Val.
178 unsigned N = (Zero | Val).countl_one();
179
180 // For each of those bit positions, if Val has a 1 in that bit then our
181 // underlying value must also have a 1.
182 APInt MaskedVal(Val);
183 MaskedVal.clearLowBits(getBitWidth() - N);
184 return KnownBits(Zero, One | MaskedVal);
185}
186
187KnownBits KnownBits::umax(const KnownBits &LHS, const KnownBits &RHS) {
188 // If we can prove that LHS >= RHS then use LHS as the result. Likewise for
189 // RHS. Ideally our caller would already have spotted these cases and
190 // optimized away the umax operation, but we handle them here for
191 // completeness.
192 if (LHS.getMinValue().uge(RHS.getMaxValue()))
193 return LHS;
194 if (RHS.getMinValue().uge(LHS.getMaxValue()))
195 return RHS;
196
197 // If the result of the umax is LHS then it must be greater than or equal to
198 // the minimum possible value of RHS. Likewise for RHS. Any known bits that
199 // are common to these two values are also known in the result.
200 KnownBits L = LHS.makeGE(RHS.getMinValue());
201 KnownBits R = RHS.makeGE(LHS.getMinValue());
202 return L.intersectWith(R);
203}
204
205KnownBits KnownBits::umin(const KnownBits &LHS, const KnownBits &RHS) {
206 // Flip the range of values: [0, 0xFFFFFFFF] <-> [0xFFFFFFFF, 0]
207 auto Flip = [](const KnownBits &Val) { return KnownBits(Val.One, Val.Zero); };
208 return Flip(umax(Flip(LHS), Flip(RHS)));
209}
210
211KnownBits KnownBits::smax(const KnownBits &LHS, const KnownBits &RHS) {
212 return flipSignBit(umax(flipSignBit(LHS), flipSignBit(RHS)));
213}
214
215KnownBits KnownBits::smin(const KnownBits &LHS, const KnownBits &RHS) {
216 // Flip the range of values: [-0x80000000, 0x7FFFFFFF] <-> [0xFFFFFFFF, 0]
217 auto Flip = [](const KnownBits &Val) {
218 unsigned SignBitPosition = Val.getBitWidth() - 1;
219 APInt Zero = Val.One;
220 APInt One = Val.Zero;
221 Zero.setBitVal(SignBitPosition, Val.Zero[SignBitPosition]);
222 One.setBitVal(SignBitPosition, Val.One[SignBitPosition]);
223 return KnownBits(Zero, One);
224 };
225 return Flip(umax(Flip(LHS), Flip(RHS)));
226}
227
228KnownBits KnownBits::abdu(const KnownBits &LHS, const KnownBits &RHS) {
229 // If we know which argument is larger, return (sub LHS, RHS) or
230 // (sub RHS, LHS) directly.
231 if (LHS.getMinValue().uge(RHS.getMaxValue()))
232 return computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/false, LHS,
233 RHS);
234 if (RHS.getMinValue().uge(LHS.getMaxValue()))
235 return computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/false, RHS,
236 LHS);
237
238 // By construction, the subtraction in abdu never has unsigned overflow.
239 // Find the common bits between (sub nuw LHS, RHS) and (sub nuw RHS, LHS).
240 KnownBits Diff0 =
241 computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/true, LHS, RHS);
242 KnownBits Diff1 =
243 computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/true, RHS, LHS);
244 return Diff0.intersectWith(Diff1);
245}
246
247KnownBits KnownBits::abds(KnownBits LHS, KnownBits RHS) {
248 // If we know which argument is larger, return (sub LHS, RHS) or
249 // (sub RHS, LHS) directly.
250 if (LHS.getSignedMinValue().sge(RHS.getSignedMaxValue()))
251 return computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/false, LHS,
252 RHS);
253 if (RHS.getSignedMinValue().sge(LHS.getSignedMaxValue()))
254 return computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/false, RHS,
255 LHS);
256
257 // Shift both arguments from the signed range to the unsigned range, e.g. from
258 // [-0x80, 0x7F] to [0, 0xFF]. This allows us to use "sub nuw" below just like
259 // abdu does.
260 // Note that we can't just use "sub nsw" instead because abds has signed
261 // inputs but an unsigned result, which makes the overflow conditions
262 // different.
263 unsigned SignBitPosition = LHS.getBitWidth() - 1;
264 for (auto Arg : {&LHS, &RHS}) {
265 bool Tmp = Arg->Zero[SignBitPosition];
266 Arg->Zero.setBitVal(SignBitPosition, Arg->One[SignBitPosition]);
267 Arg->One.setBitVal(SignBitPosition, Tmp);
268 }
269
270 // Find the common bits between (sub nuw LHS, RHS) and (sub nuw RHS, LHS).
271 KnownBits Diff0 =
272 computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/true, LHS, RHS);
273 KnownBits Diff1 =
274 computeForAddSub(/*Add=*/false, /*NSW=*/false, /*NUW=*/true, RHS, LHS);
275 return Diff0.intersectWith(Diff1);
276}
277
278static unsigned getMaxShiftAmount(const APInt &MaxValue, unsigned BitWidth) {
280 return MaxValue.extractBitsAsZExtValue(Log2_32(BitWidth), 0);
281 // This is only an approximate upper bound.
282 return MaxValue.getLimitedValue(BitWidth - 1);
283}
284
285KnownBits KnownBits::shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW,
286 bool NSW, bool ShAmtNonZero) {
287 unsigned BitWidth = LHS.getBitWidth();
288 auto ShiftByConst = [&](const KnownBits &LHS, unsigned ShiftAmt) {
289 KnownBits Known;
290 bool ShiftedOutZero, ShiftedOutOne;
291 Known.Zero = LHS.Zero.ushl_ov(ShiftAmt, ShiftedOutZero);
292 Known.Zero.setLowBits(ShiftAmt);
293 Known.One = LHS.One.ushl_ov(ShiftAmt, ShiftedOutOne);
294
295 // All cases returning poison have been handled by MaxShiftAmount already.
296 if (NSW) {
297 if (NUW && ShiftAmt != 0)
298 // NUW means we can assume anything shifted out was a zero.
299 ShiftedOutZero = true;
300
301 if (ShiftedOutZero)
302 Known.makeNonNegative();
303 else if (ShiftedOutOne)
304 Known.makeNegative();
305 }
306 return Known;
307 };
308
309 // Fast path for a common case when LHS is completely unknown.
310 KnownBits Known(BitWidth);
311 unsigned MinShiftAmount = RHS.getMinValue().getLimitedValue(BitWidth);
312 if (MinShiftAmount == 0 && ShAmtNonZero)
313 MinShiftAmount = 1;
314 if (LHS.isUnknown()) {
315 Known.Zero.setLowBits(MinShiftAmount);
316 if (NUW && NSW && MinShiftAmount != 0)
317 Known.makeNonNegative();
318 return Known;
319 }
320
321 // Determine maximum shift amount, taking NUW/NSW flags into account.
322 APInt MaxValue = RHS.getMaxValue();
323 unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth);
324 if (NUW && NSW)
325 MaxShiftAmount = std::min(MaxShiftAmount, LHS.countMaxLeadingZeros() - 1);
326 if (NUW)
327 MaxShiftAmount = std::min(MaxShiftAmount, LHS.countMaxLeadingZeros());
328 if (NSW)
329 MaxShiftAmount = std::min(
330 MaxShiftAmount,
331 std::max(LHS.countMaxLeadingZeros(), LHS.countMaxLeadingOnes()) - 1);
332
333 // Fast path for common case where the shift amount is unknown.
334 if (MinShiftAmount == 0 && MaxShiftAmount == BitWidth - 1 &&
336 Known.Zero.setLowBits(LHS.countMinTrailingZeros());
337 if (LHS.isAllOnes())
338 Known.One.setSignBit();
339 if (NSW) {
340 if (LHS.isNonNegative())
341 Known.makeNonNegative();
342 if (LHS.isNegative())
343 Known.makeNegative();
344 }
345 return Known;
346 }
347
348 // Find the common bits from all possible shifts.
349 unsigned ShiftAmtZeroMask = RHS.Zero.zextOrTrunc(32).getZExtValue();
350 unsigned ShiftAmtOneMask = RHS.One.zextOrTrunc(32).getZExtValue();
351 Known.setAllConflict();
352 for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount;
353 ++ShiftAmt) {
354 // Skip if the shift amount is impossible.
355 if ((ShiftAmtZeroMask & ShiftAmt) != 0 ||
356 (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
357 continue;
358 Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt));
359 if (Known.isUnknown())
360 break;
361 }
362
363 // All shift amounts may result in poison.
364 if (Known.hasConflict())
365 Known.setAllZero();
366 return Known;
367}
368
369KnownBits KnownBits::lshr(const KnownBits &LHS, const KnownBits &RHS,
370 bool ShAmtNonZero, bool Exact) {
371 unsigned BitWidth = LHS.getBitWidth();
372 auto ShiftByConst = [&](const KnownBits &LHS, unsigned ShiftAmt) {
373 KnownBits Known = LHS;
374 Known >>= ShiftAmt;
375 // High bits are known zero.
376 Known.Zero.setHighBits(ShiftAmt);
377 return Known;
378 };
379
380 // Fast path for a common case when LHS is completely unknown.
381 KnownBits Known(BitWidth);
382 unsigned MinShiftAmount = RHS.getMinValue().getLimitedValue(BitWidth);
383 if (MinShiftAmount == 0 && ShAmtNonZero)
384 MinShiftAmount = 1;
385 if (LHS.isUnknown()) {
386 Known.Zero.setHighBits(MinShiftAmount);
387 return Known;
388 }
389
390 // Find the common bits from all possible shifts.
391 APInt MaxValue = RHS.getMaxValue();
392 unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth);
393
394 // If exact, bound MaxShiftAmount to first known 1 in LHS.
395 if (Exact) {
396 unsigned FirstOne = LHS.countMaxTrailingZeros();
397 if (FirstOne < MinShiftAmount) {
398 // Always poison. Return zero because we don't like returning conflict.
399 Known.setAllZero();
400 return Known;
401 }
402 MaxShiftAmount = std::min(MaxShiftAmount, FirstOne);
403 }
404
405 unsigned ShiftAmtZeroMask = RHS.Zero.zextOrTrunc(32).getZExtValue();
406 unsigned ShiftAmtOneMask = RHS.One.zextOrTrunc(32).getZExtValue();
407 Known.setAllConflict();
408 for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount;
409 ++ShiftAmt) {
410 // Skip if the shift amount is impossible.
411 if ((ShiftAmtZeroMask & ShiftAmt) != 0 ||
412 (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
413 continue;
414 Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt));
415 if (Known.isUnknown())
416 break;
417 }
418
419 // All shift amounts may result in poison.
420 if (Known.hasConflict())
421 Known.setAllZero();
422 return Known;
423}
424
425KnownBits KnownBits::ashr(const KnownBits &LHS, const KnownBits &RHS,
426 bool ShAmtNonZero, bool Exact) {
427 unsigned BitWidth = LHS.getBitWidth();
428 auto ShiftByConst = [&](const KnownBits &LHS, unsigned ShiftAmt) {
429 KnownBits Known = LHS;
430 Known.Zero.ashrInPlace(ShiftAmt);
431 Known.One.ashrInPlace(ShiftAmt);
432 return Known;
433 };
434
435 // Fast path for a common case when LHS is completely unknown.
436 KnownBits Known(BitWidth);
437 unsigned MinShiftAmount = RHS.getMinValue().getLimitedValue(BitWidth);
438 if (MinShiftAmount == 0 && ShAmtNonZero)
439 MinShiftAmount = 1;
440 if (LHS.isUnknown()) {
441 if (MinShiftAmount == BitWidth) {
442 // Always poison. Return zero because we don't like returning conflict.
443 Known.setAllZero();
444 return Known;
445 }
446 return Known;
447 }
448
449 // Find the common bits from all possible shifts.
450 APInt MaxValue = RHS.getMaxValue();
451 unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth);
452
453 // If exact, bound MaxShiftAmount to first known 1 in LHS.
454 if (Exact) {
455 unsigned FirstOne = LHS.countMaxTrailingZeros();
456 if (FirstOne < MinShiftAmount) {
457 // Always poison. Return zero because we don't like returning conflict.
458 Known.setAllZero();
459 return Known;
460 }
461 MaxShiftAmount = std::min(MaxShiftAmount, FirstOne);
462 }
463
464 unsigned ShiftAmtZeroMask = RHS.Zero.zextOrTrunc(32).getZExtValue();
465 unsigned ShiftAmtOneMask = RHS.One.zextOrTrunc(32).getZExtValue();
466 Known.setAllConflict();
467 for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount;
468 ++ShiftAmt) {
469 // Skip if the shift amount is impossible.
470 if ((ShiftAmtZeroMask & ShiftAmt) != 0 ||
471 (ShiftAmtOneMask | ShiftAmt) != ShiftAmt)
472 continue;
473 Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt));
474 if (Known.isUnknown())
475 break;
476 }
477
478 // All shift amounts may result in poison.
479 if (Known.hasConflict())
480 Known.setAllZero();
481 return Known;
482}
483
484std::optional<bool> KnownBits::eq(const KnownBits &LHS, const KnownBits &RHS) {
485 if (LHS.isConstant() && RHS.isConstant())
486 return std::optional<bool>(LHS.getConstant() == RHS.getConstant());
487 if (LHS.One.intersects(RHS.Zero) || RHS.One.intersects(LHS.Zero))
488 return std::optional<bool>(false);
489 return std::nullopt;
490}
491
492std::optional<bool> KnownBits::ne(const KnownBits &LHS, const KnownBits &RHS) {
493 if (std::optional<bool> KnownEQ = eq(LHS, RHS))
494 return std::optional<bool>(!*KnownEQ);
495 return std::nullopt;
496}
497
498std::optional<bool> KnownBits::ugt(const KnownBits &LHS, const KnownBits &RHS) {
499 // LHS >u RHS -> false if umax(LHS) <= umax(RHS)
500 if (LHS.getMaxValue().ule(RHS.getMinValue()))
501 return std::optional<bool>(false);
502 // LHS >u RHS -> true if umin(LHS) > umax(RHS)
503 if (LHS.getMinValue().ugt(RHS.getMaxValue()))
504 return std::optional<bool>(true);
505 return std::nullopt;
506}
507
508std::optional<bool> KnownBits::uge(const KnownBits &LHS, const KnownBits &RHS) {
509 if (std::optional<bool> IsUGT = ugt(RHS, LHS))
510 return std::optional<bool>(!*IsUGT);
511 return std::nullopt;
512}
513
514std::optional<bool> KnownBits::ult(const KnownBits &LHS, const KnownBits &RHS) {
515 return ugt(RHS, LHS);
516}
517
518std::optional<bool> KnownBits::ule(const KnownBits &LHS, const KnownBits &RHS) {
519 return uge(RHS, LHS);
520}
521
522std::optional<bool> KnownBits::sgt(const KnownBits &LHS, const KnownBits &RHS) {
523 // LHS >s RHS -> false if smax(LHS) <= smax(RHS)
524 if (LHS.getSignedMaxValue().sle(RHS.getSignedMinValue()))
525 return std::optional<bool>(false);
526 // LHS >s RHS -> true if smin(LHS) > smax(RHS)
527 if (LHS.getSignedMinValue().sgt(RHS.getSignedMaxValue()))
528 return std::optional<bool>(true);
529 return std::nullopt;
530}
531
532std::optional<bool> KnownBits::sge(const KnownBits &LHS, const KnownBits &RHS) {
533 if (std::optional<bool> KnownSGT = sgt(RHS, LHS))
534 return std::optional<bool>(!*KnownSGT);
535 return std::nullopt;
536}
537
538std::optional<bool> KnownBits::slt(const KnownBits &LHS, const KnownBits &RHS) {
539 return sgt(RHS, LHS);
540}
541
542std::optional<bool> KnownBits::sle(const KnownBits &LHS, const KnownBits &RHS) {
543 return sge(RHS, LHS);
544}
545
546KnownBits KnownBits::abs(bool IntMinIsPoison) const {
547 // If the source's MSB is zero then we know the rest of the bits already.
548 if (isNonNegative())
549 return *this;
550
551 // Absolute value preserves trailing zero count.
552 KnownBits KnownAbs(getBitWidth());
553
554 // If the input is negative, then abs(x) == -x.
555 if (isNegative()) {
556 KnownBits Tmp = *this;
557 // Special case for IntMinIsPoison. We know the sign bit is set and we know
558 // all the rest of the bits except one to be zero. Since we have
559 // IntMinIsPoison, that final bit MUST be a one, as otherwise the input is
560 // INT_MIN.
561 if (IntMinIsPoison && (Zero.popcount() + 2) == getBitWidth())
563
564 KnownAbs = computeForAddSub(
565 /*Add*/ false, IntMinIsPoison, /*NUW=*/false,
567
568 // One more special case for IntMinIsPoison. If we don't know any ones other
569 // than the signbit, we know for certain that all the unknowns can't be
570 // zero. So if we know high zero bits, but have unknown low bits, we know
571 // for certain those high-zero bits will end up as one. This is because,
572 // the low bits can't be all zeros, so the +1 in (~x + 1) cannot carry up
573 // to the high bits. If we know a known INT_MIN input skip this. The result
574 // is poison anyways.
575 if (IntMinIsPoison && Tmp.countMinPopulation() == 1 &&
576 Tmp.countMaxPopulation() != 1) {
577 Tmp.One.clearSignBit();
578 Tmp.Zero.setSignBit();
579 KnownAbs.One.setBits(getBitWidth() - Tmp.countMinLeadingZeros(),
580 getBitWidth() - 1);
581 }
582
583 } else {
584 unsigned MaxTZ = countMaxTrailingZeros();
585 unsigned MinTZ = countMinTrailingZeros();
586
587 KnownAbs.Zero.setLowBits(MinTZ);
588 // If we know the lowest set 1, then preserve it.
589 if (MaxTZ == MinTZ && MaxTZ < getBitWidth())
590 KnownAbs.One.setBit(MaxTZ);
591
592 // We only know that the absolute values's MSB will be zero if INT_MIN is
593 // poison, or there is a set bit that isn't the sign bit (otherwise it could
594 // be INT_MIN).
595 if (IntMinIsPoison || (!One.isZero() && !One.isMinSignedValue())) {
596 KnownAbs.One.clearSignBit();
597 KnownAbs.Zero.setSignBit();
598 }
599 }
600
601 return KnownAbs;
602}
603
604KnownBits KnownBits::reduceAdd(unsigned NumElts) const {
605 if (NumElts == 0)
606 return KnownBits(getBitWidth());
607
608 unsigned BitWidth = getBitWidth();
609 KnownBits Result(BitWidth);
610
611 if (isConstant())
612 // If all elements are the same constant, we can simply compute it
613 return KnownBits::makeConstant(NumElts * getConstant());
614
615 // The main idea is as follows.
616 //
617 // If KnownBits for each element has L leading zeros then
618 // X_i < 2^(W - L) for every i from [1, N].
619 //
620 // ADD X_i <= ADD max(X_i) = N * max(X_i)
621 // < N * 2^(W - L)
622 // < 2^(W - L + ceil(log2(N)))
623 //
624 // As the result, we can conclude that
625 //
626 // L' = L - ceil(log2(N))
627 //
628 // Similar logic can be applied to leading ones.
629 unsigned LostBits = Log2_32_Ceil(NumElts);
630
631 if (isNonNegative()) {
632 unsigned LeadingZeros = countMinLeadingZeros();
633 LeadingZeros = LeadingZeros > LostBits ? LeadingZeros - LostBits : 0;
634 Result.Zero.setHighBits(LeadingZeros);
635 } else if (isNegative()) {
636 unsigned LeadingOnes = countMinLeadingOnes();
637 LeadingOnes = LeadingOnes > LostBits ? LeadingOnes - LostBits : 0;
638 Result.One.setHighBits(LeadingOnes);
639 }
640
641 return Result;
642}
643
645 const KnownBits &LHS,
646 const KnownBits &RHS) {
647 // We don't see NSW even for sadd/ssub as we want to check if the result has
648 // signed overflow.
649 unsigned BitWidth = LHS.getBitWidth();
650
651 std::optional<bool> Overflow;
652 // Even if we can't entirely rule out overflow, we may be able to rule out
653 // overflow in one direction. This allows us to potentially keep some of the
654 // add/sub bits. I.e if we can't overflow in the positive direction we won't
655 // clamp to INT_MAX so we can keep low 0s from the add/sub result.
656 bool MayNegClamp = true;
657 bool MayPosClamp = true;
658 if (Signed) {
659 // Easy cases we can rule out any overflow.
660 if (Add && ((LHS.isNegative() && RHS.isNonNegative()) ||
661 (LHS.isNonNegative() && RHS.isNegative())))
662 Overflow = false;
663 else if (!Add && (((LHS.isNegative() && RHS.isNegative()) ||
664 (LHS.isNonNegative() && RHS.isNonNegative()))))
665 Overflow = false;
666 else {
667 // Check if we may overflow. If we can't rule out overflow then check if
668 // we can rule out a direction at least.
669 KnownBits UnsignedLHS = LHS;
670 KnownBits UnsignedRHS = RHS;
671 // Get version of LHS/RHS with clearer signbit. This allows us to detect
672 // how the addition/subtraction might overflow into the signbit. Then
673 // using the actual known signbits of LHS/RHS, we can figure out which
674 // overflows are/aren't possible.
675 UnsignedLHS.One.clearSignBit();
676 UnsignedLHS.Zero.setSignBit();
677 UnsignedRHS.One.clearSignBit();
678 UnsignedRHS.Zero.setSignBit();
679 KnownBits Res =
680 KnownBits::computeForAddSub(Add, /*NSW=*/false,
681 /*NUW=*/false, UnsignedLHS, UnsignedRHS);
682 if (Add) {
683 if (Res.isNegative()) {
684 // Only overflow scenario is Pos + Pos.
685 MayNegClamp = false;
686 // Pos + Pos will overflow with extra signbit.
687 if (LHS.isNonNegative() && RHS.isNonNegative())
688 Overflow = true;
689 } else if (Res.isNonNegative()) {
690 // Only overflow scenario is Neg + Neg
691 MayPosClamp = false;
692 // Neg + Neg will overflow without extra signbit.
693 if (LHS.isNegative() && RHS.isNegative())
694 Overflow = true;
695 }
696 // We will never clamp to the opposite sign of N-bit result.
697 if (LHS.isNegative() || RHS.isNegative())
698 MayPosClamp = false;
699 if (LHS.isNonNegative() || RHS.isNonNegative())
700 MayNegClamp = false;
701 } else {
702 if (Res.isNegative()) {
703 // Only overflow scenario is Neg - Pos.
704 MayPosClamp = false;
705 // Neg - Pos will overflow with extra signbit.
706 if (LHS.isNegative() && RHS.isNonNegative())
707 Overflow = true;
708 } else if (Res.isNonNegative()) {
709 // Only overflow scenario is Pos - Neg.
710 MayNegClamp = false;
711 // Pos - Neg will overflow without extra signbit.
712 if (LHS.isNonNegative() && RHS.isNegative())
713 Overflow = true;
714 }
715 // We will never clamp to the opposite sign of N-bit result.
716 if (LHS.isNegative() || RHS.isNonNegative())
717 MayPosClamp = false;
718 if (LHS.isNonNegative() || RHS.isNegative())
719 MayNegClamp = false;
720 }
721 }
722 // If we have ruled out all clamping, we will never overflow.
723 if (!MayNegClamp && !MayPosClamp)
724 Overflow = false;
725 } else if (Add) {
726 // uadd.sat
727 bool Of;
728 (void)LHS.getMaxValue().uadd_ov(RHS.getMaxValue(), Of);
729 if (!Of) {
730 Overflow = false;
731 } else {
732 (void)LHS.getMinValue().uadd_ov(RHS.getMinValue(), Of);
733 if (Of)
734 Overflow = true;
735 }
736 } else {
737 // usub.sat
738 bool Of;
739 (void)LHS.getMinValue().usub_ov(RHS.getMaxValue(), Of);
740 if (!Of) {
741 Overflow = false;
742 } else {
743 (void)LHS.getMaxValue().usub_ov(RHS.getMinValue(), Of);
744 if (Of)
745 Overflow = true;
746 }
747 }
748
750 /*NUW=*/!Signed, LHS, RHS);
751
752 if (Overflow) {
753 // We know whether or not we overflowed.
754 if (!(*Overflow)) {
755 // No overflow.
756 return Res;
757 }
758
759 // We overflowed
760 APInt C;
761 if (Signed) {
762 // sadd.sat / ssub.sat
763 assert(!LHS.isSignUnknown() &&
764 "We somehow know overflow without knowing input sign");
765 C = LHS.isNegative() ? APInt::getSignedMinValue(BitWidth)
767 } else if (Add) {
768 // uadd.sat
770 } else {
771 // uadd.sat
773 }
774
775 Res.One = C;
776 Res.Zero = ~C;
777 return Res;
778 }
779
780 // We don't know if we overflowed.
781 if (Signed) {
782 // sadd.sat/ssub.sat
783 // We can keep our information about the sign bits.
784 if (MayPosClamp)
785 Res.Zero.clearLowBits(BitWidth - 1);
786 if (MayNegClamp)
787 Res.One.clearLowBits(BitWidth - 1);
788 } else if (Add) {
789 // uadd.sat
790 // We need to clear all the known zeros as we can only use the leading ones.
791 Res.Zero.clearAllBits();
792 } else {
793 // usub.sat
794 // We need to clear all the known ones as we can only use the leading zero.
795 Res.One.clearAllBits();
796 }
797
798 return Res;
799}
800
801KnownBits KnownBits::sadd_sat(const KnownBits &LHS, const KnownBits &RHS) {
802 return computeForSatAddSub(/*Add*/ true, /*Signed*/ true, LHS, RHS);
803}
804KnownBits KnownBits::ssub_sat(const KnownBits &LHS, const KnownBits &RHS) {
805 return computeForSatAddSub(/*Add*/ false, /*Signed*/ true, LHS, RHS);
806}
807KnownBits KnownBits::uadd_sat(const KnownBits &LHS, const KnownBits &RHS) {
808 return computeForSatAddSub(/*Add*/ true, /*Signed*/ false, LHS, RHS);
809}
810KnownBits KnownBits::usub_sat(const KnownBits &LHS, const KnownBits &RHS) {
811 return computeForSatAddSub(/*Add*/ false, /*Signed*/ false, LHS, RHS);
812}
813
815 unsigned BitWidth = LHS.getBitWidth();
816 LHS = LHS.zext(BitWidth + 1);
817 RHS = RHS.zext(BitWidth + 1);
818 LHS =
819 computeForAddCarry(LHS, RHS, /*CarryZero*/ !IsCeil, /*CarryOne*/ IsCeil);
820 LHS = LHS.extractBits(BitWidth, 1);
821 return LHS;
822}
823
824KnownBits KnownBits::avgFloorS(const KnownBits &LHS, const KnownBits &RHS) {
825 return flipSignBit(avgFloorU(flipSignBit(LHS), flipSignBit(RHS)));
826}
827
828KnownBits KnownBits::avgFloorU(const KnownBits &LHS, const KnownBits &RHS) {
829 return avgComputeU(LHS, RHS, /*IsCeil=*/false);
830}
831
832KnownBits KnownBits::avgCeilS(const KnownBits &LHS, const KnownBits &RHS) {
833 return flipSignBit(avgCeilU(flipSignBit(LHS), flipSignBit(RHS)));
834}
835
836KnownBits KnownBits::avgCeilU(const KnownBits &LHS, const KnownBits &RHS) {
837 return avgComputeU(LHS, RHS, /*IsCeil=*/true);
838}
839
840KnownBits KnownBits::mul(const KnownBits &LHS, const KnownBits &RHS,
841 bool NoUndefSelfMultiply) {
842 unsigned BitWidth = LHS.getBitWidth();
843 assert(BitWidth == RHS.getBitWidth() && "Operand mismatch");
844 assert((!NoUndefSelfMultiply || LHS == RHS) &&
845 "Self multiplication knownbits mismatch");
846
847 // Compute the high known-0 bits by multiplying the unsigned max of each side.
848 // Conservatively, M active bits * N active bits results in M + N bits in the
849 // result. But if we know a value is a power-of-2 for example, then this
850 // computes one more leading zero.
851 // TODO: This could be generalized to number of sign bits (negative numbers).
852 APInt UMaxLHS = LHS.getMaxValue();
853 APInt UMaxRHS = RHS.getMaxValue();
854
855 // For leading zeros in the result to be valid, the unsigned max product must
856 // fit in the bitwidth (it must not overflow).
857 bool HasOverflow;
858 APInt UMaxResult = UMaxLHS.umul_ov(UMaxRHS, HasOverflow);
859 unsigned LeadZ = HasOverflow ? 0 : UMaxResult.countl_zero();
860
861 // The result of the bottom bits of an integer multiply can be
862 // inferred by looking at the bottom bits of both operands and
863 // multiplying them together.
864 // We can infer at least the minimum number of known trailing bits
865 // of both operands. Depending on number of trailing zeros, we can
866 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
867 // a and b are divisible by m and n respectively.
868 // We then calculate how many of those bits are inferrable and set
869 // the output. For example, the i8 mul:
870 // a = XXXX1100 (12)
871 // b = XXXX1110 (14)
872 // We know the bottom 3 bits are zero since the first can be divided by
873 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
874 // Applying the multiplication to the trimmed arguments gets:
875 // XX11 (3)
876 // X111 (7)
877 // -------
878 // XX11
879 // XX11
880 // XX11
881 // XX11
882 // -------
883 // XXXXX01
884 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
885 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
886 // The proof for this can be described as:
887 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
888 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
889 // umin(countTrailingZeros(C2), C6) +
890 // umin(C5 - umin(countTrailingZeros(C1), C5),
891 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
892 // %aa = shl i8 %a, C5
893 // %bb = shl i8 %b, C6
894 // %aaa = or i8 %aa, C1
895 // %bbb = or i8 %bb, C2
896 // %mul = mul i8 %aaa, %bbb
897 // %mask = and i8 %mul, C7
898 // =>
899 // %mask = i8 ((C1*C2)&C7)
900 // Where C5, C6 describe the known bits of %a, %b
901 // C1, C2 describe the known bottom bits of %a, %b.
902 // C7 describes the mask of the known bits of the result.
903 const APInt &Bottom0 = LHS.One;
904 const APInt &Bottom1 = RHS.One;
905
906 // How many times we'd be able to divide each argument by 2 (shr by 1).
907 // This gives us the number of trailing zeros on the multiplication result.
908 unsigned TrailBitsKnown0 = (LHS.Zero | LHS.One).countr_one();
909 unsigned TrailBitsKnown1 = (RHS.Zero | RHS.One).countr_one();
910 unsigned TrailZero0 = LHS.countMinTrailingZeros();
911 unsigned TrailZero1 = RHS.countMinTrailingZeros();
912 unsigned TrailZ = TrailZero0 + TrailZero1;
913
914 // Figure out the fewest known-bits operand.
915 unsigned SmallestOperand =
916 std::min(TrailBitsKnown0 - TrailZero0, TrailBitsKnown1 - TrailZero1);
917 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
918
919 APInt BottomKnown =
920 Bottom0.getLoBits(TrailBitsKnown0) * Bottom1.getLoBits(TrailBitsKnown1);
921
922 KnownBits Res(BitWidth);
923 Res.Zero.setHighBits(LeadZ);
924 Res.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
925 Res.One = BottomKnown.getLoBits(ResultBitsKnown);
926
927 if (NoUndefSelfMultiply) {
928 // If X has at least TZ trailing zeroes, then bit (2 * TZ + 1) must be zero.
929 unsigned TwoTZP1 = 2 * TrailZero0 + 1;
930 if (TwoTZP1 < BitWidth)
931 Res.Zero.setBit(TwoTZP1);
932
933 // If X has exactly TZ trailing zeros, then bit (2 * TZ + 2) must also be
934 // zero.
935 if (TrailZero0 < BitWidth && LHS.One[TrailZero0]) {
936 unsigned TwoTZP2 = TwoTZP1 + 1;
937 if (TwoTZP2 < BitWidth)
938 Res.Zero.setBit(TwoTZP2);
939 }
940 }
941
942 return Res;
943}
944
945KnownBits KnownBits::mulhs(const KnownBits &LHS, const KnownBits &RHS) {
946 unsigned BitWidth = LHS.getBitWidth();
947 assert(BitWidth == RHS.getBitWidth() && "Operand mismatch");
948 KnownBits WideLHS = LHS.sext(2 * BitWidth);
949 KnownBits WideRHS = RHS.sext(2 * BitWidth);
950 return mul(WideLHS, WideRHS).extractBits(BitWidth, BitWidth);
951}
952
953KnownBits KnownBits::mulhu(const KnownBits &LHS, const KnownBits &RHS) {
954 unsigned BitWidth = LHS.getBitWidth();
955 assert(BitWidth == RHS.getBitWidth() && "Operand mismatch");
956 KnownBits WideLHS = LHS.zext(2 * BitWidth);
957 KnownBits WideRHS = RHS.zext(2 * BitWidth);
958 return mul(WideLHS, WideRHS).extractBits(BitWidth, BitWidth);
959}
960
962 const KnownBits &RHS, bool Exact) {
963
964 if (!Exact)
965 return Known;
966
967 // If LHS is Odd, the result is Odd no matter what.
968 // Odd / Odd -> Odd
969 // Odd / Even -> Impossible (because its exact division)
970 if (LHS.One[0])
971 Known.One.setBit(0);
972
973 int MinTZ =
974 (int)LHS.countMinTrailingZeros() - (int)RHS.countMaxTrailingZeros();
975 int MaxTZ =
976 (int)LHS.countMaxTrailingZeros() - (int)RHS.countMinTrailingZeros();
977 if (MinTZ >= 0) {
978 // Result has at least MinTZ trailing zeros.
979 Known.Zero.setLowBits(MinTZ);
980 if (MinTZ == MaxTZ) {
981 // Result has exactly MinTZ trailing zeros.
982 Known.One.setBit(MinTZ);
983 }
984 } else if (MaxTZ < 0) {
985 // Poison Result
986 Known.setAllZero();
987 }
988
989 // In the KnownBits exhaustive tests, we have poison inputs for exact values
990 // a LOT. If we have a conflict, just return all zeros.
991 if (Known.hasConflict())
992 Known.setAllZero();
993
994 return Known;
995}
996
997KnownBits KnownBits::sdiv(const KnownBits &LHS, const KnownBits &RHS,
998 bool Exact) {
999 // Equivalent of `udiv`. We must have caught this before it was folded.
1000 if (LHS.isNonNegative() && RHS.isNonNegative())
1001 return udiv(LHS, RHS, Exact);
1002
1003 unsigned BitWidth = LHS.getBitWidth();
1004 KnownBits Known(BitWidth);
1005
1006 if (LHS.isZero() || RHS.isZero()) {
1007 // Result is either known Zero or UB. Return Zero either way.
1008 // Checking this earlier saves us a lot of special cases later on.
1009 Known.setAllZero();
1010 return Known;
1011 }
1012
1013 std::optional<APInt> Res;
1014 if (LHS.isNegative() && RHS.isNegative()) {
1015 // Result non-negative.
1016 APInt Denom = RHS.getSignedMaxValue();
1017 APInt Num = LHS.getSignedMinValue();
1018 // INT_MIN/-1 would be a poison result (impossible). Estimate the division
1019 // as signed max (we will only set sign bit in the result).
1020 Res = (Num.isMinSignedValue() && Denom.isAllOnes())
1022 : Num.sdiv(Denom);
1023 } else if (LHS.isNegative() && RHS.isNonNegative()) {
1024 // Result is negative if Exact OR -LHS u>= RHS.
1025 if (Exact || (-LHS.getSignedMaxValue()).uge(RHS.getSignedMaxValue())) {
1026 APInt Denom = RHS.getSignedMinValue();
1027 APInt Num = LHS.getSignedMinValue();
1028 Res = Denom.isZero() ? Num : Num.sdiv(Denom);
1029 }
1030 } else if (LHS.isStrictlyPositive() && RHS.isNegative()) {
1031 // Result is negative if Exact OR LHS u>= -RHS.
1032 if (Exact || LHS.getSignedMinValue().uge(-RHS.getSignedMinValue())) {
1033 APInt Denom = RHS.getSignedMaxValue();
1034 APInt Num = LHS.getSignedMaxValue();
1035 Res = Num.sdiv(Denom);
1036 }
1037 }
1038
1039 if (Res) {
1040 if (Res->isNonNegative()) {
1041 unsigned LeadZ = Res->countLeadingZeros();
1042 Known.Zero.setHighBits(LeadZ);
1043 } else {
1044 unsigned LeadO = Res->countLeadingOnes();
1045 Known.One.setHighBits(LeadO);
1046 }
1047 }
1048
1049 Known = divComputeLowBit(Known, LHS, RHS, Exact);
1050 return Known;
1051}
1052
1053KnownBits KnownBits::udiv(const KnownBits &LHS, const KnownBits &RHS,
1054 bool Exact) {
1055 unsigned BitWidth = LHS.getBitWidth();
1056 KnownBits Known(BitWidth);
1057
1058 if (LHS.isZero() || RHS.isZero()) {
1059 // Result is either known Zero or UB. Return Zero either way.
1060 // Checking this earlier saves us a lot of special cases later on.
1061 Known.setAllZero();
1062 return Known;
1063 }
1064
1065 // We can figure out the minimum number of upper zero bits by doing
1066 // MaxNumerator / MinDenominator. If the Numerator gets smaller or Denominator
1067 // gets larger, the number of upper zero bits increases.
1068 APInt MinDenom = RHS.getMinValue();
1069 APInt MaxNum = LHS.getMaxValue();
1070 APInt MaxRes = MinDenom.isZero() ? MaxNum : MaxNum.udiv(MinDenom);
1071
1072 unsigned LeadZ = MaxRes.countLeadingZeros();
1073
1074 Known.Zero.setHighBits(LeadZ);
1075 Known = divComputeLowBit(Known, LHS, RHS, Exact);
1076
1077 return Known;
1078}
1079
1080KnownBits KnownBits::remGetLowBits(const KnownBits &LHS, const KnownBits &RHS) {
1081 unsigned BitWidth = LHS.getBitWidth();
1082 if (!RHS.isZero() && RHS.Zero[0]) {
1083 // rem X, Y where Y[0:N] is zero will preserve X[0:N] in the result.
1084 unsigned RHSZeros = RHS.countMinTrailingZeros();
1085 APInt Mask = APInt::getLowBitsSet(BitWidth, RHSZeros);
1086 APInt OnesMask = LHS.One & Mask;
1087 APInt ZerosMask = LHS.Zero & Mask;
1088 return KnownBits(ZerosMask, OnesMask);
1089 }
1090 return KnownBits(BitWidth);
1091}
1092
1093KnownBits KnownBits::urem(const KnownBits &LHS, const KnownBits &RHS) {
1094 KnownBits Known = remGetLowBits(LHS, RHS);
1095 if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
1096 // NB: Low bits set in `remGetLowBits`.
1097 APInt HighBits = ~(RHS.getConstant() - 1);
1098 Known.Zero |= HighBits;
1099 return Known;
1100 }
1101
1102 // Since the result is less than or equal to either operand, any leading
1103 // zero bits in either operand must also exist in the result.
1104 uint32_t Leaders =
1105 std::max(LHS.countMinLeadingZeros(), RHS.countMinLeadingZeros());
1106 Known.Zero.setHighBits(Leaders);
1107 return Known;
1108}
1109
1110KnownBits KnownBits::srem(const KnownBits &LHS, const KnownBits &RHS) {
1111 KnownBits Known = remGetLowBits(LHS, RHS);
1112 if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) {
1113 // NB: Low bits are set in `remGetLowBits`.
1114 APInt LowBits = RHS.getConstant() - 1;
1115 // If the first operand is non-negative or has all low bits zero, then
1116 // the upper bits are all zero.
1117 if (LHS.isNonNegative() || LowBits.isSubsetOf(LHS.Zero))
1118 Known.Zero |= ~LowBits;
1119
1120 // If the first operand is negative and not all low bits are zero, then
1121 // the upper bits are all one.
1122 if (LHS.isNegative() && LowBits.intersects(LHS.One))
1123 Known.One |= ~LowBits;
1124 return Known;
1125 }
1126
1127 // The sign bit is the LHS's sign bit, except when the result of the
1128 // remainder is zero. The magnitude of the result should be less than or
1129 // equal to the magnitude of either operand.
1130 if (LHS.isNegative() && Known.isNonZero())
1131 Known.One.setHighBits(
1132 std::max(LHS.countMinLeadingOnes(), RHS.countMinSignBits()));
1133 else if (LHS.isNonNegative())
1134 Known.Zero.setHighBits(
1135 std::max(LHS.countMinLeadingZeros(), RHS.countMinSignBits()));
1136 return Known;
1137}
1138
1139KnownBits &KnownBits::operator&=(const KnownBits &RHS) {
1140 // Result bit is 0 if either operand bit is 0.
1141 Zero |= RHS.Zero;
1142 // Result bit is 1 if both operand bits are 1.
1143 One &= RHS.One;
1144 return *this;
1145}
1146
1147KnownBits &KnownBits::operator|=(const KnownBits &RHS) {
1148 // Result bit is 0 if both operand bits are 0.
1149 Zero &= RHS.Zero;
1150 // Result bit is 1 if either operand bit is 1.
1151 One |= RHS.One;
1152 return *this;
1153}
1154
1155KnownBits &KnownBits::operator^=(const KnownBits &RHS) {
1156 // Result bit is 0 if both operand bits are 0 or both are 1.
1157 APInt Z = (Zero & RHS.Zero) | (One & RHS.One);
1158 // Result bit is 1 if one operand bit is 0 and the other is 1.
1159 One = (Zero & RHS.One) | (One & RHS.Zero);
1160 Zero = std::move(Z);
1161 return *this;
1162}
1163
1164KnownBits KnownBits::blsi() const {
1165 unsigned BitWidth = getBitWidth();
1166 KnownBits Known(Zero, APInt(BitWidth, 0));
1167 unsigned Max = countMaxTrailingZeros();
1168 Known.Zero.setBitsFrom(std::min(Max + 1, BitWidth));
1169 unsigned Min = countMinTrailingZeros();
1170 if (Max == Min && Max < BitWidth)
1171 Known.One.setBit(Max);
1172 return Known;
1173}
1174
1175KnownBits KnownBits::blsmsk() const {
1176 unsigned BitWidth = getBitWidth();
1177 KnownBits Known(BitWidth);
1178 unsigned Max = countMaxTrailingZeros();
1179 Known.Zero.setBitsFrom(std::min(Max + 1, BitWidth));
1180 unsigned Min = countMinTrailingZeros();
1181 Known.One.setLowBits(std::min(Min + 1, BitWidth));
1182 return Known;
1183}
1184
1186 unsigned BitWidth = getBitWidth();
1187 for (unsigned I = 0; I < BitWidth; ++I) {
1188 unsigned N = BitWidth - I - 1;
1189 if (Zero[N] && One[N])
1190 OS << "!";
1191 else if (Zero[N])
1192 OS << "0";
1193 else if (One[N])
1194 OS << "1";
1195 else
1196 OS << "?";
1197 }
1198}
1199
1200#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1202 print(dbgs());
1203 dbgs() << "\n";
1204}
1205#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
static KnownBits avgComputeU(KnownBits LHS, KnownBits RHS, bool IsCeil)
static KnownBits computeForSatAddSub(bool Add, bool Signed, const KnownBits &LHS, const KnownBits &RHS)
static KnownBits divComputeLowBit(KnownBits Known, const KnownBits &LHS, const KnownBits &RHS, bool Exact)
static KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, bool CarryZero, bool CarryOne)
Definition KnownBits.cpp:30
static unsigned getMaxShiftAmount(const APInt &MaxValue, unsigned BitWidth)
#define I(x, y, z)
Definition MD5.cpp:57
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:1971
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2055
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1573
LLVM_ABI APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition APInt.cpp:644
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1392
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1386
LLVM_ABI uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const
Definition APInt.cpp:520
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:936
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:207
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1331
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2026
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
void setSignBit()
Set the sign bit to 1.
Definition APInt.h:1341
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:217
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1250
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1644
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1397
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:835
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1599
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition APInt.cpp:2005
unsigned countLeadingZeros() const
Definition APInt.h:1607
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1616
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition APInt.h:1436
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:476
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2036
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:472
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1368
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1258
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1389
void clearSignBit()
Set the sign bit to 0.
Definition APInt.h:1450
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2045
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:344
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:293
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:331
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:280
@ Add
Sum of integers.
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1915
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#define N
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:304
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
static LLVM_ABI std::optional< bool > eq(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_EQ result.
LLVM_ABI KnownBits sextInReg(unsigned SrcBitWidth) const
Return known bits for a in-register sign extension of the value we're tracking.
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:108
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:127
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:254
LLVM_ABI KnownBits reduceAdd(unsigned NumElts) const
Compute known bits for horizontal add for a vector with NumElts elements, where each element has the ...
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:245
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:66
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:277
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
LLVM_ABI KnownBits makeGE(const APInt &Val) const
Return KnownBits based on this, but updated given that the underlying value is known to be greater th...
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
void makeNegative()
Make this value negative.
Definition KnownBits.h:122
void setAllConflict()
Make all bits known to be both zero and one.
Definition KnownBits.h:99
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI std::optional< bool > sge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGE result.
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:292
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:86
LLVM_ABI KnownBits & operator|=(const KnownBits &RHS)
Update known bits based on ORing with RHS.
LLVM_ABI void print(raw_ostream &OS) const
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
LLVM_DUMP_METHOD void dump() const
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:111
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:228
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:314
static LLVM_ABI KnownBits computeForSubBorrow(const KnownBits &LHS, KnownBits RHS, const KnownBits &Borrow)
Compute known bits results from subtracting RHS from LHS with 1-bit Borrow.
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:251
KnownBits()=default
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
LLVM_ABI KnownBits & operator&=(const KnownBits &RHS)
Update known bits based on ANDing with RHS.
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI std::optional< bool > ugt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGT result.
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
static LLVM_ABI std::optional< bool > slt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLT result.
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:60
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI std::optional< bool > ult(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULT result.
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
static LLVM_ABI std::optional< bool > ule(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_ULE result.
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:105
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:53
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sle(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SLE result.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
unsigned countMinPopulation() const
Returns the number of bits known to be one.
Definition KnownBits.h:289
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
LLVM_ABI KnownBits & operator^=(const KnownBits &RHS)
Update known bits based on XORing with RHS.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:60