1//===- ConstantRange.cpp - ConstantRange implementation -------------------===//
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// Represent a range of possible values that may occur when the program is run
10// for an integral value. This keeps track of a lower and upper bound for the
11// constant, which MAY wrap around the end of the numeric range. To do this, it
12// keeps track of a [lower, upper) bound, which specifies an interval just like
13// STL iterators. When used with boolean values, the following are important
14// ranges (other integral ranges use min/max values for special range values):
15//
16// [F, F) = {} = Empty set
17// [T, F) = {T}
18// [F, T) = {F}
19// [T, T) = {F, T} = Full set
20//
21//===----------------------------------------------------------------------===//
22
23#include "llvm/IR/ConstantRange.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/Config/llvm-config.h"
26#include "llvm/IR/CmpPredicate.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Metadata.h"
33#include "llvm/IR/Operator.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/KnownBits.h"
38#include "llvm/Support/raw_ostream.h"
39#include <algorithm>
40#include <cassert>
41#include <cstdint>
42#include <optional>
43
44using namespace llvm;
45
46ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
47 : Lower(Full ? APInt::getMaxValue(numBits: BitWidth) : APInt::getMinValue(numBits: BitWidth)),
48 Upper(Lower) {}
49
50ConstantRange::ConstantRange(APInt V)
51 : Lower(std::move(V)), Upper(Lower + 1) {}
52
53ConstantRange::ConstantRange(APInt L, APInt U)
54 : Lower(std::move(L)), Upper(std::move(U)) {
55 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
56 "ConstantRange with unequal bit widths");
57 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
58 "Lower == Upper, but they aren't min or max value!");
59}
60
61ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
62 bool IsSigned) {
63 if (Known.hasConflict())
64 return getEmpty(BitWidth: Known.getBitWidth());
65 if (Known.isUnknown())
66 return getFull(BitWidth: Known.getBitWidth());
67
68 // For unsigned ranges, or signed ranges with known sign bit, create a simple
69 // range between the smallest and largest possible value.
70 if (!IsSigned || Known.isNegative() || Known.isNonNegative())
71 return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
72
73 // If we don't know the sign bit, pick the lower bound as a negative number
74 // and the upper bound as a non-negative one.
75 APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
76 Lower.setSignBit();
77 Upper.clearSignBit();
78 return ConstantRange(Lower, Upper + 1);
79}
80
81KnownBits ConstantRange::toKnownBits() const {
82 // TODO: We could return conflicting known bits here, but consumers are
83 // likely not prepared for that.
84 if (isEmptySet())
85 return KnownBits(getBitWidth());
86
87 // We can only retain the top bits that are the same between min and max.
88 APInt Min = getUnsignedMin();
89 APInt Max = getUnsignedMax();
90 KnownBits Known = KnownBits::makeConstant(C: Min);
91 if (std::optional<unsigned> DifferentBit =
92 APIntOps::GetMostSignificantDifferentBit(A: Min, B: Max)) {
93 Known.Zero.clearLowBits(loBits: *DifferentBit + 1);
94 Known.One.clearLowBits(loBits: *DifferentBit + 1);
95 }
96 return Known;
97}
98
99std::pair<ConstantRange, ConstantRange> ConstantRange::splitPosNeg() const {
100 uint32_t BW = getBitWidth();
101 APInt Zero = APInt::getZero(numBits: BW), One = APInt(BW, 1);
102 APInt SignedMin = APInt::getSignedMinValue(numBits: BW);
103 // There are no positive 1-bit values. The 1 would get interpreted as -1.
104 ConstantRange PosFilter =
105 BW == 1 ? getEmpty() : ConstantRange(One, SignedMin);
106 ConstantRange NegFilter(SignedMin, Zero);
107 return {intersectWith(CR: PosFilter), intersectWith(CR: NegFilter)};
108}
109
110ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
111 const ConstantRange &CR) {
112 if (CR.isEmptySet())
113 return CR;
114
115 uint32_t W = CR.getBitWidth();
116 switch (Pred) {
117 default:
118 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
119 case CmpInst::ICMP_EQ:
120 return CR;
121 case CmpInst::ICMP_NE:
122 if (CR.isSingleElement())
123 return ConstantRange(CR.getUpper(), CR.getLower());
124 return getFull(BitWidth: W);
125 case CmpInst::ICMP_ULT: {
126 APInt UMax(CR.getUnsignedMax());
127 if (UMax.isMinValue())
128 return getEmpty(BitWidth: W);
129 return ConstantRange(APInt::getMinValue(numBits: W), std::move(UMax));
130 }
131 case CmpInst::ICMP_SLT: {
132 APInt SMax(CR.getSignedMax());
133 if (SMax.isMinSignedValue())
134 return getEmpty(BitWidth: W);
135 return ConstantRange(APInt::getSignedMinValue(numBits: W), std::move(SMax));
136 }
137 case CmpInst::ICMP_ULE:
138 return getNonEmpty(Lower: APInt::getMinValue(numBits: W), Upper: CR.getUnsignedMax() + 1);
139 case CmpInst::ICMP_SLE:
140 return getNonEmpty(Lower: APInt::getSignedMinValue(numBits: W), Upper: CR.getSignedMax() + 1);
141 case CmpInst::ICMP_UGT: {
142 APInt UMin(CR.getUnsignedMin());
143 if (UMin.isMaxValue())
144 return getEmpty(BitWidth: W);
145 return ConstantRange(std::move(UMin) + 1, APInt::getZero(numBits: W));
146 }
147 case CmpInst::ICMP_SGT: {
148 APInt SMin(CR.getSignedMin());
149 if (SMin.isMaxSignedValue())
150 return getEmpty(BitWidth: W);
151 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(numBits: W));
152 }
153 case CmpInst::ICMP_UGE:
154 return getNonEmpty(Lower: CR.getUnsignedMin(), Upper: APInt::getZero(numBits: W));
155 case CmpInst::ICMP_SGE:
156 return getNonEmpty(Lower: CR.getSignedMin(), Upper: APInt::getSignedMinValue(numBits: W));
157 }
158}
159
160ConstantRange ConstantRange::makeAllowedICmpRegion(CmpPredicate Pred,
161 const ConstantRange &CR) {
162 ConstantRange Result = makeAllowedICmpRegion(Pred: Pred.dropSameSign(), CR);
163 if (!Pred.hasSameSign())
164 return Result;
165 return Result.intersectWith(
166 CR: makeAllowedICmpRegion(Pred: Pred.getPreferredSignedPredicate(), CR));
167}
168
169ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
170 const ConstantRange &CR) {
171 // Follows from De-Morgan's laws:
172 //
173 // ~(~A union ~B) == A intersect B.
174 //
175 return makeAllowedICmpRegion(Pred: CmpInst::getInversePredicate(pred: Pred), CR)
176 .inverse();
177}
178
179ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
180 const APInt &C) {
181 // Computes the exact range that is equal to both the constant ranges returned
182 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
183 // when RHS is a singleton such as an APInt. However for non-singleton RHS,
184 // for example ult [2,5) makeAllowedICmpRegion returns [0,4) but
185 // makeSatisfyICmpRegion returns [0,2).
186 //
187 return makeAllowedICmpRegion(Pred, CR: C);
188}
189
190bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(
191 const ConstantRange &CR1, const ConstantRange &CR2) {
192 if (CR1.isEmptySet() || CR2.isEmptySet())
193 return true;
194
195 return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
196 (CR1.isAllNegative() && CR2.isAllNegative());
197}
198
199bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
200 const ConstantRange &CR1, const ConstantRange &CR2) {
201 if (CR1.isEmptySet() || CR2.isEmptySet())
202 return true;
203
204 return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
205 (CR1.isAllNegative() && CR2.isAllNonNegative());
206}
207
208CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(
209 CmpInst::Predicate Pred, const ConstantRange &CR1,
210 const ConstantRange &CR2) {
211 assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&
212 "Only for relational integer predicates!");
213
214 CmpInst::Predicate FlippedSignednessPred =
215 ICmpInst::getFlippedSignednessPredicate(Pred);
216
217 if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))
218 return FlippedSignednessPred;
219
220 if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))
221 return CmpInst::getInversePredicate(pred: FlippedSignednessPred);
222
223 return CmpInst::Predicate::BAD_ICMP_PREDICATE;
224}
225
226void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
227 APInt &RHS, APInt &Offset) const {
228 Offset = APInt(getBitWidth(), 0);
229 if (isFullSet() || isEmptySet()) {
230 Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
231 RHS = APInt(getBitWidth(), 0);
232 } else if (auto *OnlyElt = getSingleElement()) {
233 Pred = CmpInst::ICMP_EQ;
234 RHS = *OnlyElt;
235 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
236 Pred = CmpInst::ICMP_NE;
237 RHS = *OnlyMissingElt;
238 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
239 Pred =
240 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
241 RHS = getUpper();
242 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
243 Pred =
244 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
245 RHS = getLower();
246 } else {
247 Pred = CmpInst::ICMP_ULT;
248 RHS = getUpper() - getLower();
249 Offset = -getLower();
250 }
251
252 assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&
253 "Bad result!");
254}
255
256bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
257 APInt &RHS) const {
258 APInt Offset;
259 getEquivalentICmp(Pred, RHS, Offset);
260 return Offset.isZero();
261}
262
263bool ConstantRange::icmp(CmpInst::Predicate Pred,
264 const ConstantRange &Other) const {
265 if (isEmptySet() || Other.isEmptySet())
266 return true;
267
268 switch (Pred) {
269 case CmpInst::ICMP_EQ:
270 if (const APInt *L = getSingleElement())
271 if (const APInt *R = Other.getSingleElement())
272 return *L == *R;
273 return false;
274 case CmpInst::ICMP_NE:
275 return inverse().contains(CR: Other);
276 case CmpInst::ICMP_ULT:
277 return getUnsignedMax().ult(RHS: Other.getUnsignedMin());
278 case CmpInst::ICMP_ULE:
279 return getUnsignedMax().ule(RHS: Other.getUnsignedMin());
280 case CmpInst::ICMP_UGT:
281 return getUnsignedMin().ugt(RHS: Other.getUnsignedMax());
282 case CmpInst::ICMP_UGE:
283 return getUnsignedMin().uge(RHS: Other.getUnsignedMax());
284 case CmpInst::ICMP_SLT:
285 return getSignedMax().slt(RHS: Other.getSignedMin());
286 case CmpInst::ICMP_SLE:
287 return getSignedMax().sle(RHS: Other.getSignedMin());
288 case CmpInst::ICMP_SGT:
289 return getSignedMin().sgt(RHS: Other.getSignedMax());
290 case CmpInst::ICMP_SGE:
291 return getSignedMin().sge(RHS: Other.getSignedMax());
292 default:
293 llvm_unreachable("Invalid ICmp predicate");
294 }
295}
296
297/// Exact mul nuw region for single element RHS.
298static ConstantRange makeExactMulNUWRegion(const APInt &V) {
299 unsigned BitWidth = V.getBitWidth();
300 if (V == 0)
301 return ConstantRange::getFull(BitWidth: V.getBitWidth());
302
303 return ConstantRange::getNonEmpty(
304 Lower: APIntOps::RoundingUDiv(A: APInt::getMinValue(numBits: BitWidth), B: V,
305 RM: APInt::Rounding::UP),
306 Upper: APIntOps::RoundingUDiv(A: APInt::getMaxValue(numBits: BitWidth), B: V,
307 RM: APInt::Rounding::DOWN) + 1);
308}
309
310/// Exact mul nsw region for single element RHS.
311static ConstantRange makeExactMulNSWRegion(const APInt &V) {
312 // Handle 0 and -1 separately to avoid division by zero or overflow.
313 unsigned BitWidth = V.getBitWidth();
314 if (V == 0)
315 return ConstantRange::getFull(BitWidth);
316
317 APInt MinValue = APInt::getSignedMinValue(numBits: BitWidth);
318 APInt MaxValue = APInt::getSignedMaxValue(numBits: BitWidth);
319 // e.g. Returning [-127, 127], represented as [-127, -128).
320 if (V.isAllOnes())
321 return ConstantRange(-MaxValue, MinValue);
322
323 APInt Lower, Upper;
324 if (V.isNegative()) {
325 Lower = APIntOps::RoundingSDiv(A: MaxValue, B: V, RM: APInt::Rounding::UP);
326 Upper = APIntOps::RoundingSDiv(A: MinValue, B: V, RM: APInt::Rounding::DOWN);
327 } else {
328 Lower = APIntOps::RoundingSDiv(A: MinValue, B: V, RM: APInt::Rounding::UP);
329 Upper = APIntOps::RoundingSDiv(A: MaxValue, B: V, RM: APInt::Rounding::DOWN);
330 }
331 return ConstantRange::getNonEmpty(Lower, Upper: Upper + 1);
332}
333
334ConstantRange
335ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
336 const ConstantRange &Other,
337 unsigned NoWrapKind) {
338 using OBO = OverflowingBinaryOperator;
339
340 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
341
342 assert((NoWrapKind == OBO::NoSignedWrap ||
343 NoWrapKind == OBO::NoUnsignedWrap) &&
344 "NoWrapKind invalid!");
345
346 bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
347 unsigned BitWidth = Other.getBitWidth();
348
349 switch (BinOp) {
350 default:
351 llvm_unreachable("Unsupported binary op");
352
353 case Instruction::Add: {
354 if (Unsigned)
355 return getNonEmpty(Lower: APInt::getZero(numBits: BitWidth), Upper: -Other.getUnsignedMax());
356
357 APInt SignedMinVal = APInt::getSignedMinValue(numBits: BitWidth);
358 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
359 return getNonEmpty(
360 Lower: SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
361 Upper: SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
362 }
363
364 case Instruction::Sub: {
365 if (Unsigned)
366 return getNonEmpty(Lower: Other.getUnsignedMax(), Upper: APInt::getMinValue(numBits: BitWidth));
367
368 APInt SignedMinVal = APInt::getSignedMinValue(numBits: BitWidth);
369 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
370 return getNonEmpty(
371 Lower: SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
372 Upper: SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
373 }
374
375 case Instruction::Mul:
376 if (Unsigned)
377 return makeExactMulNUWRegion(V: Other.getUnsignedMax());
378
379 // Avoid one makeExactMulNSWRegion() call for the common case of constants.
380 if (const APInt *C = Other.getSingleElement())
381 return makeExactMulNSWRegion(V: *C);
382
383 return makeExactMulNSWRegion(V: Other.getSignedMin())
384 .intersectWith(CR: makeExactMulNSWRegion(V: Other.getSignedMax()));
385
386 case Instruction::Shl: {
387 // For given range of shift amounts, if we ignore all illegal shift amounts
388 // (that always produce poison), what shift amount range is left?
389 ConstantRange ShAmt = Other.intersectWith(
390 CR: ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
391 if (ShAmt.isEmptySet()) {
392 // If the entire range of shift amounts is already poison-producing,
393 // then we can freely add more poison-producing flags ontop of that.
394 return getFull(BitWidth);
395 }
396 // There are some legal shift amounts, we can compute conservatively-correct
397 // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
398 // to be at most bitwidth-1, which results in most conservative range.
399 APInt ShAmtUMax = ShAmt.getUnsignedMax();
400 if (Unsigned)
401 return getNonEmpty(Lower: APInt::getZero(numBits: BitWidth),
402 Upper: APInt::getMaxValue(numBits: BitWidth).lshr(ShiftAmt: ShAmtUMax) + 1);
403 return getNonEmpty(Lower: APInt::getSignedMinValue(numBits: BitWidth).ashr(ShiftAmt: ShAmtUMax),
404 Upper: APInt::getSignedMaxValue(numBits: BitWidth).ashr(ShiftAmt: ShAmtUMax) + 1);
405 }
406 }
407}
408
409ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
410 const APInt &Other,
411 unsigned NoWrapKind) {
412 using OBO = OverflowingBinaryOperator;
413
414 assert(
415 (NoWrapKind == OBO::NoSignedWrap || NoWrapKind == OBO::NoUnsignedWrap) &&
416 "NoWrapKind invalid!");
417
418 bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
419 unsigned BitWidth = Other.getBitWidth();
420 switch (BinOp) {
421 case Instruction::Add: {
422 if (Unsigned)
423 return getNonEmpty(Lower: APInt::getZero(numBits: BitWidth), Upper: -Other);
424 APInt SignedMinVal = APInt::getSignedMinValue(numBits: BitWidth);
425 return Other.isNegative() ? getNonEmpty(Lower: SignedMinVal - Other, Upper: SignedMinVal)
426 : getNonEmpty(Lower: SignedMinVal, Upper: SignedMinVal - Other);
427 }
428
429 case Instruction::Sub: {
430 if (Unsigned)
431 return getNonEmpty(Lower: Other, Upper: APInt::getZero(numBits: BitWidth));
432 APInt SignedMinVal = APInt::getSignedMinValue(numBits: BitWidth);
433 return Other.isNegative() ? getNonEmpty(Lower: SignedMinVal, Upper: SignedMinVal + Other)
434 : getNonEmpty(Lower: SignedMinVal + Other, Upper: SignedMinVal);
435 }
436
437 case Instruction::Mul:
438 return Unsigned ? makeExactMulNUWRegion(V: Other)
439 : makeExactMulNSWRegion(V: Other);
440
441 case Instruction::Shl:
442 // Shift amounts >= BitWidth always produce poison.
443 if (Other.uge(RHS: BitWidth))
444 return getFull(BitWidth);
445 if (Unsigned)
446 return getNonEmpty(Lower: APInt::getZero(numBits: BitWidth),
447 Upper: APInt::getMaxValue(numBits: BitWidth).lshr(ShiftAmt: Other) + 1);
448 return getNonEmpty(Lower: APInt::getSignedMinValue(numBits: BitWidth).ashr(ShiftAmt: Other),
449 Upper: APInt::getSignedMaxValue(numBits: BitWidth).ashr(ShiftAmt: Other) + 1);
450
451 default:
452 llvm_unreachable("Unsupported binary op");
453 }
454}
455
456ConstantRange ConstantRange::makeMaskNotEqualRange(const APInt &Mask,
457 const APInt &C) {
458 unsigned BitWidth = Mask.getBitWidth();
459
460 if ((Mask & C) != C)
461 return getFull(BitWidth);
462
463 if (Mask.isZero())
464 return getEmpty(BitWidth);
465
466 // If (Val & Mask) != C, constrained to the non-equality being
467 // satisfiable, then the value must be larger than the lowest set bit of
468 // Mask, offset by constant C.
469 return ConstantRange::getNonEmpty(
470 Lower: APInt::getOneBitSet(numBits: BitWidth, BitNo: Mask.countr_zero()) + C, Upper: C);
471}
472
473bool ConstantRange::isFullSet() const {
474 return Lower == Upper && Lower.isMaxValue();
475}
476
477bool ConstantRange::isEmptySet() const {
478 return Lower == Upper && Lower.isMinValue();
479}
480
481bool ConstantRange::isWrappedSet() const {
482 return Lower.ugt(RHS: Upper) && !Upper.isZero();
483}
484
485bool ConstantRange::isUpperWrapped() const {
486 return Lower.ugt(RHS: Upper);
487}
488
489bool ConstantRange::isSignWrappedSet() const {
490 return Lower.sgt(RHS: Upper) && !Upper.isMinSignedValue();
491}
492
493bool ConstantRange::isUpperSignWrapped() const {
494 return Lower.sgt(RHS: Upper);
495}
496
497bool
498ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
499 assert(getBitWidth() == Other.getBitWidth());
500 if (isFullSet())
501 return false;
502 if (Other.isFullSet())
503 return true;
504 return (Upper - Lower).ult(RHS: Other.Upper - Other.Lower);
505}
506
507bool
508ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
509 // If this a full set, we need special handling to avoid needing an extra bit
510 // to represent the size.
511 if (isFullSet())
512 return MaxSize == 0 || APInt::getMaxValue(numBits: getBitWidth()).ugt(RHS: MaxSize - 1);
513
514 return (Upper - Lower).ugt(RHS: MaxSize);
515}
516
517bool ConstantRange::isAllNegative() const {
518 // Empty set is all negative, full set is not.
519 if (isEmptySet())
520 return true;
521 if (isFullSet())
522 return false;
523
524 return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
525}
526
527bool ConstantRange::isAllNonNegative() const {
528 // Empty and full set are automatically treated correctly.
529 return !isSignWrappedSet() && Lower.isNonNegative();
530}
531
532bool ConstantRange::isAllPositive() const {
533 // Empty set is all positive, full set is not.
534 if (isEmptySet())
535 return true;
536 if (isFullSet())
537 return false;
538
539 return !isSignWrappedSet() && Lower.isStrictlyPositive();
540}
541
542APInt ConstantRange::getUnsignedMax() const {
543 if (isFullSet() || isUpperWrapped())
544 return APInt::getMaxValue(numBits: getBitWidth());
545 return getUpper() - 1;
546}
547
548APInt ConstantRange::getUnsignedMin() const {
549 if (isFullSet() || isWrappedSet())
550 return APInt::getMinValue(numBits: getBitWidth());
551 return getLower();
552}
553
554APInt ConstantRange::getSignedMax() const {
555 if (isFullSet() || isUpperSignWrapped())
556 return APInt::getSignedMaxValue(numBits: getBitWidth());
557 return getUpper() - 1;
558}
559
560APInt ConstantRange::getSignedMin() const {
561 if (isFullSet() || isSignWrappedSet())
562 return APInt::getSignedMinValue(numBits: getBitWidth());
563 return getLower();
564}
565
566bool ConstantRange::contains(const APInt &V) const {
567 if (Lower == Upper)
568 return isFullSet();
569
570 if (!isUpperWrapped())
571 return Lower.ule(RHS: V) && V.ult(RHS: Upper);
572 return Lower.ule(RHS: V) || V.ult(RHS: Upper);
573}
574
575bool ConstantRange::contains(const ConstantRange &Other) const {
576 if (isFullSet() || Other.isEmptySet()) return true;
577 if (isEmptySet() || Other.isFullSet()) return false;
578
579 if (!isUpperWrapped()) {
580 if (Other.isUpperWrapped())
581 return false;
582
583 return Lower.ule(RHS: Other.getLower()) && Other.getUpper().ule(RHS: Upper);
584 }
585
586 if (!Other.isUpperWrapped())
587 return Other.getUpper().ule(RHS: Upper) ||
588 Lower.ule(RHS: Other.getLower());
589
590 return Other.getUpper().ule(RHS: Upper) && Lower.ule(RHS: Other.getLower());
591}
592
593unsigned ConstantRange::getActiveBits() const {
594 if (isEmptySet())
595 return 0;
596
597 return getUnsignedMax().getActiveBits();
598}
599
600unsigned ConstantRange::getMinSignedBits() const {
601 if (isEmptySet())
602 return 0;
603
604 return std::max(a: getSignedMin().getSignificantBits(),
605 b: getSignedMax().getSignificantBits());
606}
607
608ConstantRange ConstantRange::subtract(const APInt &Val) const {
609 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
610 // If the set is empty or full, don't modify the endpoints.
611 if (Lower == Upper)
612 return *this;
613 return ConstantRange(Lower - Val, Upper - Val);
614}
615
616ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
617 return intersectWith(CR: CR.inverse());
618}
619
620static ConstantRange getPreferredRange(
621 const ConstantRange &CR1, const ConstantRange &CR2,
622 ConstantRange::PreferredRangeType Type) {
623 if (Type == ConstantRange::Unsigned) {
624 if (!CR1.isWrappedSet() && CR2.isWrappedSet())
625 return CR1;
626 if (CR1.isWrappedSet() && !CR2.isWrappedSet())
627 return CR2;
628 } else if (Type == ConstantRange::Signed) {
629 if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
630 return CR1;
631 if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
632 return CR2;
633 }
634
635 if (CR1.isSizeStrictlySmallerThan(Other: CR2))
636 return CR1;
637 return CR2;
638}
639
640ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
641 PreferredRangeType Type) const {
642 assert(getBitWidth() == CR.getBitWidth() &&
643 "ConstantRange types don't agree!");
644
645 // Handle common cases.
646 if ( isEmptySet() || CR.isFullSet()) return *this;
647 if (CR.isEmptySet() || isFullSet()) return CR;
648
649 if (!isUpperWrapped() && CR.isUpperWrapped())
650 return CR.intersectWith(CR: *this, Type);
651
652 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
653 if (Lower.ult(RHS: CR.Lower)) {
654 // L---U : this
655 // L---U : CR
656 if (Upper.ule(RHS: CR.Lower))
657 return getEmpty();
658
659 // L---U : this
660 // L---U : CR
661 if (Upper.ult(RHS: CR.Upper))
662 return ConstantRange(CR.Lower, Upper);
663
664 // L-------U : this
665 // L---U : CR
666 return CR;
667 }
668 // L---U : this
669 // L-------U : CR
670 if (Upper.ult(RHS: CR.Upper))
671 return *this;
672
673 // L-----U : this
674 // L-----U : CR
675 if (Lower.ult(RHS: CR.Upper))
676 return ConstantRange(Lower, CR.Upper);
677
678 // L---U : this
679 // L---U : CR
680 return getEmpty();
681 }
682
683 if (isUpperWrapped() && !CR.isUpperWrapped()) {
684 if (CR.Lower.ult(RHS: Upper)) {
685 // ------U L--- : this
686 // L--U : CR
687 if (CR.Upper.ult(RHS: Upper))
688 return CR;
689
690 // ------U L--- : this
691 // L------U : CR
692 if (CR.Upper.ule(RHS: Lower))
693 return ConstantRange(CR.Lower, Upper);
694
695 // ------U L--- : this
696 // L----------U : CR
697 return getPreferredRange(CR1: *this, CR2: CR, Type);
698 }
699 if (CR.Lower.ult(RHS: Lower)) {
700 // --U L---- : this
701 // L--U : CR
702 if (CR.Upper.ule(RHS: Lower))
703 return getEmpty();
704
705 // --U L---- : this
706 // L------U : CR
707 return ConstantRange(Lower, CR.Upper);
708 }
709
710 // --U L------ : this
711 // L--U : CR
712 return CR;
713 }
714
715 if (CR.Upper.ult(RHS: Upper)) {
716 // ------U L-- : this
717 // --U L------ : CR
718 if (CR.Lower.ult(RHS: Upper))
719 return getPreferredRange(CR1: *this, CR2: CR, Type);
720
721 // ----U L-- : this
722 // --U L---- : CR
723 if (CR.Lower.ult(RHS: Lower))
724 return ConstantRange(Lower, CR.Upper);
725
726 // ----U L---- : this
727 // --U L-- : CR
728 return CR;
729 }
730 if (CR.Upper.ule(RHS: Lower)) {
731 // --U L-- : this
732 // ----U L---- : CR
733 if (CR.Lower.ult(RHS: Lower))
734 return *this;
735
736 // --U L---- : this
737 // ----U L-- : CR
738 return ConstantRange(CR.Lower, Upper);
739 }
740
741 // --U L------ : this
742 // ------U L-- : CR
743 return getPreferredRange(CR1: *this, CR2: CR, Type);
744}
745
746ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
747 PreferredRangeType Type) const {
748 assert(getBitWidth() == CR.getBitWidth() &&
749 "ConstantRange types don't agree!");
750
751 if ( isFullSet() || CR.isEmptySet()) return *this;
752 if (CR.isFullSet() || isEmptySet()) return CR;
753
754 if (!isUpperWrapped() && CR.isUpperWrapped())
755 return CR.unionWith(CR: *this, Type);
756
757 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
758 // L---U and L---U : this
759 // L---U L---U : CR
760 // result in one of
761 // L---------U
762 // -----U L-----
763 if (CR.Upper.ult(RHS: Lower) || Upper.ult(RHS: CR.Lower))
764 return getPreferredRange(
765 CR1: ConstantRange(Lower, CR.Upper), CR2: ConstantRange(CR.Lower, Upper), Type);
766
767 APInt L = CR.Lower.ult(RHS: Lower) ? CR.Lower : Lower;
768 APInt U = (CR.Upper - 1).ugt(RHS: Upper - 1) ? CR.Upper : Upper;
769
770 if (L.isZero() && U.isZero())
771 return getFull();
772
773 return ConstantRange(std::move(L), std::move(U));
774 }
775
776 if (!CR.isUpperWrapped()) {
777 // ------U L----- and ------U L----- : this
778 // L--U L--U : CR
779 if (CR.Upper.ule(RHS: Upper) || CR.Lower.uge(RHS: Lower))
780 return *this;
781
782 // ------U L----- : this
783 // L---------U : CR
784 if (CR.Lower.ule(RHS: Upper) && Lower.ule(RHS: CR.Upper))
785 return getFull();
786
787 // ----U L---- : this
788 // L---U : CR
789 // results in one of
790 // ----------U L----
791 // ----U L----------
792 if (Upper.ult(RHS: CR.Lower) && CR.Upper.ult(RHS: Lower))
793 return getPreferredRange(
794 CR1: ConstantRange(Lower, CR.Upper), CR2: ConstantRange(CR.Lower, Upper), Type);
795
796 // ----U L----- : this
797 // L----U : CR
798 if (Upper.ult(RHS: CR.Lower) && Lower.ule(RHS: CR.Upper))
799 return ConstantRange(CR.Lower, Upper);
800
801 // ------U L---- : this
802 // L-----U : CR
803 assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
804 "ConstantRange::unionWith missed a case with one range wrapped");
805 return ConstantRange(Lower, CR.Upper);
806 }
807
808 // ------U L---- and ------U L---- : this
809 // -U L----------- and ------------U L : CR
810 if (CR.Lower.ule(RHS: Upper) || Lower.ule(RHS: CR.Upper))
811 return getFull();
812
813 APInt L = CR.Lower.ult(RHS: Lower) ? CR.Lower : Lower;
814 APInt U = CR.Upper.ugt(RHS: Upper) ? CR.Upper : Upper;
815
816 return ConstantRange(std::move(L), std::move(U));
817}
818
819std::optional<ConstantRange>
820ConstantRange::exactIntersectWith(const ConstantRange &CR) const {
821 // TODO: This can be implemented more efficiently.
822 ConstantRange Result = intersectWith(CR);
823 if (Result == inverse().unionWith(CR: CR.inverse()).inverse())
824 return Result;
825 return std::nullopt;
826}
827
828std::optional<ConstantRange>
829ConstantRange::exactUnionWith(const ConstantRange &CR) const {
830 // TODO: This can be implemented more efficiently.
831 ConstantRange Result = unionWith(CR);
832 if (Result == inverse().intersectWith(CR: CR.inverse()).inverse())
833 return Result;
834 return std::nullopt;
835}
836
837ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
838 uint32_t ResultBitWidth) const {
839 switch (CastOp) {
840 default:
841 llvm_unreachable("unsupported cast type");
842 case Instruction::Trunc:
843 return truncate(BitWidth: ResultBitWidth);
844 case Instruction::SExt:
845 return signExtend(BitWidth: ResultBitWidth);
846 case Instruction::ZExt:
847 return zeroExtend(BitWidth: ResultBitWidth);
848 case Instruction::BitCast:
849 return *this;
850 case Instruction::FPToUI:
851 case Instruction::FPToSI:
852 if (getBitWidth() == ResultBitWidth)
853 return *this;
854 else
855 return getFull(BitWidth: ResultBitWidth);
856 case Instruction::UIToFP: {
857 // TODO: use input range if available
858 auto BW = getBitWidth();
859 APInt Min = APInt::getMinValue(numBits: BW);
860 APInt Max = APInt::getMaxValue(numBits: BW);
861 if (ResultBitWidth > BW) {
862 Min = Min.zext(width: ResultBitWidth);
863 Max = Max.zext(width: ResultBitWidth);
864 }
865 return getNonEmpty(Lower: std::move(Min), Upper: std::move(Max) + 1);
866 }
867 case Instruction::SIToFP: {
868 // TODO: use input range if available
869 auto BW = getBitWidth();
870 APInt SMin = APInt::getSignedMinValue(numBits: BW);
871 APInt SMax = APInt::getSignedMaxValue(numBits: BW);
872 if (ResultBitWidth > BW) {
873 SMin = SMin.sext(width: ResultBitWidth);
874 SMax = SMax.sext(width: ResultBitWidth);
875 }
876 return getNonEmpty(Lower: std::move(SMin), Upper: std::move(SMax) + 1);
877 }
878 case Instruction::FPTrunc:
879 case Instruction::FPExt:
880 case Instruction::IntToPtr:
881 case Instruction::PtrToAddr:
882 case Instruction::PtrToInt:
883 case Instruction::AddrSpaceCast:
884 // Conservatively return getFull set.
885 return getFull(BitWidth: ResultBitWidth);
886 };
887}
888
889ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
890 if (isEmptySet()) return getEmpty(BitWidth: DstTySize);
891
892 unsigned SrcTySize = getBitWidth();
893 if (DstTySize == SrcTySize)
894 return *this;
895 assert(SrcTySize < DstTySize && "Not a value extension");
896 if (isFullSet() || isUpperWrapped()) {
897 // Change into [0, 1 << src bit width)
898 APInt LowerExt(DstTySize, 0);
899 if (!Upper) // special case: [X, 0) -- not really wrapping around
900 LowerExt = Lower.zext(width: DstTySize);
901 return ConstantRange(std::move(LowerExt),
902 APInt::getOneBitSet(numBits: DstTySize, BitNo: SrcTySize));
903 }
904
905 return ConstantRange(Lower.zext(width: DstTySize), Upper.zext(width: DstTySize));
906}
907
908ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
909 if (isEmptySet()) return getEmpty(BitWidth: DstTySize);
910
911 unsigned SrcTySize = getBitWidth();
912 if (DstTySize == SrcTySize)
913 return *this;
914 assert(SrcTySize < DstTySize && "Not a value extension");
915
916 // special case: [X, INT_MIN) -- not really wrapping around
917 if (Upper.isMinSignedValue())
918 return ConstantRange(Lower.sext(width: DstTySize), Upper.zext(width: DstTySize));
919
920 if (isFullSet() || isSignWrappedSet()) {
921 return ConstantRange(APInt::getHighBitsSet(numBits: DstTySize,hiBitsSet: DstTySize-SrcTySize+1),
922 APInt::getLowBitsSet(numBits: DstTySize, loBitsSet: SrcTySize-1) + 1);
923 }
924
925 return ConstantRange(Lower.sext(width: DstTySize), Upper.sext(width: DstTySize));
926}
927
928ConstantRange ConstantRange::truncate(uint32_t DstTySize,
929 unsigned NoWrapKind) const {
930 if (DstTySize == getBitWidth())
931 return *this;
932 assert(getBitWidth() > DstTySize && "Not a value truncation");
933 if (isEmptySet())
934 return getEmpty(BitWidth: DstTySize);
935 if (isFullSet())
936 return getFull(BitWidth: DstTySize);
937
938 APInt LowerDiv(Lower), UpperDiv(Upper);
939 ConstantRange Union(DstTySize, /*isFullSet=*/false);
940
941 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
942 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
943 // then we do the union with [MaxValue, Upper)
944 if (isUpperWrapped()) {
945 // If Upper is greater than MaxValue(DstTy), it covers the whole truncated
946 // range.
947 if (Upper.getActiveBits() > DstTySize)
948 return getFull(BitWidth: DstTySize);
949
950 // For nuw the two parts are: [0, Upper) \/ [Lower, MaxValue(DstTy)]
951 if (NoWrapKind & TruncInst::NoUnsignedWrap) {
952 Union = ConstantRange(APInt::getZero(numBits: DstTySize), Upper.trunc(width: DstTySize));
953 UpperDiv = APInt::getOneBitSet(numBits: getBitWidth(), BitNo: DstTySize);
954 } else {
955 // If Upper is equal to MaxValue(DstTy), it covers the whole truncated
956 // range.
957 if (Upper.countr_one() == DstTySize)
958 return getFull(BitWidth: DstTySize);
959 Union =
960 ConstantRange(APInt::getMaxValue(numBits: DstTySize), Upper.trunc(width: DstTySize));
961 UpperDiv.setAllBits();
962 // Union covers the MaxValue case, so return if the remaining range is
963 // just MaxValue(DstTy).
964 if (LowerDiv == UpperDiv)
965 return Union;
966 }
967 }
968
969 // Chop off the most significant bits that are past the destination bitwidth.
970 if (LowerDiv.getActiveBits() > DstTySize) {
971 // For trunc nuw if LowerDiv is greater than MaxValue(DstTy), the range is
972 // outside the whole truncated range.
973 if (NoWrapKind & TruncInst::NoUnsignedWrap)
974 return Union;
975 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
976 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(numBits: getBitWidth(), loBit: DstTySize);
977 LowerDiv -= Adjust;
978 UpperDiv -= Adjust;
979 }
980
981 unsigned UpperDivWidth = UpperDiv.getActiveBits();
982 if (UpperDivWidth <= DstTySize)
983 return ConstantRange(LowerDiv.trunc(width: DstTySize),
984 UpperDiv.trunc(width: DstTySize)).unionWith(CR: Union);
985
986 if (!LowerDiv.isZero() && NoWrapKind & TruncInst::NoUnsignedWrap)
987 return ConstantRange(LowerDiv.trunc(width: DstTySize), APInt::getZero(numBits: DstTySize))
988 .unionWith(CR: Union);
989
990 // The truncated value wraps around. Check if we can do better than fullset.
991 if (UpperDivWidth == DstTySize + 1) {
992 // Clear the MSB so that UpperDiv wraps around.
993 UpperDiv.clearBit(BitPosition: DstTySize);
994 if (UpperDiv.ult(RHS: LowerDiv))
995 return ConstantRange(LowerDiv.trunc(width: DstTySize),
996 UpperDiv.trunc(width: DstTySize)).unionWith(CR: Union);
997 }
998
999 return getFull(BitWidth: DstTySize);
1000}
1001
1002ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
1003 unsigned SrcTySize = getBitWidth();
1004 if (SrcTySize > DstTySize)
1005 return truncate(DstTySize);
1006 if (SrcTySize < DstTySize)
1007 return zeroExtend(DstTySize);
1008 return *this;
1009}
1010
1011ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
1012 unsigned SrcTySize = getBitWidth();
1013 if (SrcTySize > DstTySize)
1014 return truncate(DstTySize);
1015 if (SrcTySize < DstTySize)
1016 return signExtend(DstTySize);
1017 return *this;
1018}
1019
1020ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
1021 const ConstantRange &Other) const {
1022 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
1023
1024 switch (BinOp) {
1025 case Instruction::Add:
1026 return add(Other);
1027 case Instruction::Sub:
1028 return sub(Other);
1029 case Instruction::Mul:
1030 return multiply(Other);
1031 case Instruction::UDiv:
1032 return udiv(Other);
1033 case Instruction::SDiv:
1034 return sdiv(Other);
1035 case Instruction::URem:
1036 return urem(Other);
1037 case Instruction::SRem:
1038 return srem(Other);
1039 case Instruction::Shl:
1040 return shl(Other);
1041 case Instruction::LShr:
1042 return lshr(Other);
1043 case Instruction::AShr:
1044 return ashr(Other);
1045 case Instruction::And:
1046 return binaryAnd(Other);
1047 case Instruction::Or:
1048 return binaryOr(Other);
1049 case Instruction::Xor:
1050 return binaryXor(Other);
1051 // Note: floating point operations applied to abstract ranges are just
1052 // ideal integer operations with a lossy representation
1053 case Instruction::FAdd:
1054 return add(Other);
1055 case Instruction::FSub:
1056 return sub(Other);
1057 case Instruction::FMul:
1058 return multiply(Other);
1059 default:
1060 // Conservatively return getFull set.
1061 return getFull();
1062 }
1063}
1064
1065ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
1066 const ConstantRange &Other,
1067 unsigned NoWrapKind) const {
1068 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
1069
1070 switch (BinOp) {
1071 case Instruction::Add:
1072 return addWithNoWrap(Other, NoWrapKind);
1073 case Instruction::Sub:
1074 return subWithNoWrap(Other, NoWrapKind);
1075 case Instruction::Mul:
1076 return multiply(Other, NoWrapKind);
1077 case Instruction::Shl:
1078 return shlWithNoWrap(Other, NoWrapKind);
1079 default:
1080 // Don't know about this Overflowing Binary Operation.
1081 // Conservatively fallback to plain binop handling.
1082 return binaryOp(BinOp, Other);
1083 }
1084}
1085
1086ConstantRange ConstantRange::binaryOp(const BinaryOperator &BO,
1087 const ConstantRange &Other) const {
1088 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(Val: &BO))
1089 return overflowingBinaryOp(BinOp: BO.getOpcode(), Other, NoWrapKind: OBO->getNoWrapKind());
1090
1091 if (BO.getOpcode() == Instruction::Or)
1092 return binaryOr(Other, IsDisjoint: cast<PossiblyDisjointInst>(Val: BO).isDisjoint());
1093
1094 return binaryOp(BinOp: BO.getOpcode(), Other);
1095}
1096
1097bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
1098 switch (IntrinsicID) {
1099 case Intrinsic::uadd_sat:
1100 case Intrinsic::usub_sat:
1101 case Intrinsic::sadd_sat:
1102 case Intrinsic::ssub_sat:
1103 case Intrinsic::umin:
1104 case Intrinsic::umax:
1105 case Intrinsic::smin:
1106 case Intrinsic::smax:
1107 case Intrinsic::abs:
1108 case Intrinsic::ctlz:
1109 case Intrinsic::cttz:
1110 case Intrinsic::ctpop:
1111 return true;
1112 default:
1113 return false;
1114 }
1115}
1116
1117ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
1118 ArrayRef<ConstantRange> Ops) {
1119 switch (IntrinsicID) {
1120 case Intrinsic::uadd_sat:
1121 return Ops[0].uadd_sat(Other: Ops[1]);
1122 case Intrinsic::usub_sat:
1123 return Ops[0].usub_sat(Other: Ops[1]);
1124 case Intrinsic::sadd_sat:
1125 return Ops[0].sadd_sat(Other: Ops[1]);
1126 case Intrinsic::ssub_sat:
1127 return Ops[0].ssub_sat(Other: Ops[1]);
1128 case Intrinsic::umin:
1129 return Ops[0].umin(Other: Ops[1]);
1130 case Intrinsic::umax:
1131 return Ops[0].umax(Other: Ops[1]);
1132 case Intrinsic::smin:
1133 return Ops[0].smin(Other: Ops[1]);
1134 case Intrinsic::smax:
1135 return Ops[0].smax(Other: Ops[1]);
1136 case Intrinsic::abs: {
1137 const APInt *IntMinIsPoison = Ops[1].getSingleElement();
1138 assert(IntMinIsPoison && "Must be known (immarg)");
1139 assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
1140 return Ops[0].abs(IntMinIsPoison: IntMinIsPoison->getBoolValue());
1141 }
1142 case Intrinsic::ctlz: {
1143 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1144 assert(ZeroIsPoison && "Must be known (immarg)");
1145 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1146 return Ops[0].ctlz(ZeroIsPoison: ZeroIsPoison->getBoolValue());
1147 }
1148 case Intrinsic::cttz: {
1149 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1150 assert(ZeroIsPoison && "Must be known (immarg)");
1151 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1152 return Ops[0].cttz(ZeroIsPoison: ZeroIsPoison->getBoolValue());
1153 }
1154 case Intrinsic::ctpop:
1155 return Ops[0].ctpop();
1156 default:
1157 assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
1158 llvm_unreachable("Unsupported intrinsic");
1159 }
1160}
1161
1162ConstantRange
1163ConstantRange::add(const ConstantRange &Other) const {
1164 if (isEmptySet() || Other.isEmptySet())
1165 return getEmpty();
1166 if (isFullSet() || Other.isFullSet())
1167 return getFull();
1168
1169 APInt NewLower = getLower() + Other.getLower();
1170 APInt NewUpper = getUpper() + Other.getUpper() - 1;
1171 if (NewLower == NewUpper)
1172 return getFull();
1173
1174 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1175 if (X.isSizeStrictlySmallerThan(Other: *this) ||
1176 X.isSizeStrictlySmallerThan(Other))
1177 // We've wrapped, therefore, full set.
1178 return getFull();
1179 return X;
1180}
1181
1182ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
1183 unsigned NoWrapKind,
1184 PreferredRangeType RangeType) const {
1185 // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
1186 // (X is from this, and Y is from Other)
1187 if (isEmptySet() || Other.isEmptySet())
1188 return getEmpty();
1189 if (isFullSet() && Other.isFullSet())
1190 return getFull();
1191
1192 using OBO = OverflowingBinaryOperator;
1193 ConstantRange Result = add(Other);
1194
1195 // If an overflow happens for every value pair in these two constant ranges,
1196 // we must return Empty set. In this case, we get that for free, because we
1197 // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
1198 // in an empty set.
1199
1200 if (NoWrapKind & OBO::NoSignedWrap)
1201 Result = Result.intersectWith(CR: sadd_sat(Other), Type: RangeType);
1202
1203 if (NoWrapKind & OBO::NoUnsignedWrap)
1204 Result = Result.intersectWith(CR: uadd_sat(Other), Type: RangeType);
1205
1206 return Result;
1207}
1208
1209ConstantRange
1210ConstantRange::sub(const ConstantRange &Other) const {
1211 if (isEmptySet() || Other.isEmptySet())
1212 return getEmpty();
1213 if (isFullSet() || Other.isFullSet())
1214 return getFull();
1215
1216 APInt NewLower = getLower() - Other.getUpper() + 1;
1217 APInt NewUpper = getUpper() - Other.getLower();
1218 if (NewLower == NewUpper)
1219 return getFull();
1220
1221 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1222 if (X.isSizeStrictlySmallerThan(Other: *this) ||
1223 X.isSizeStrictlySmallerThan(Other))
1224 // We've wrapped, therefore, full set.
1225 return getFull();
1226 return X;
1227}
1228
1229ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
1230 unsigned NoWrapKind,
1231 PreferredRangeType RangeType) const {
1232 // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1233 // (X is from this, and Y is from Other)
1234 if (isEmptySet() || Other.isEmptySet())
1235 return getEmpty();
1236 if (isFullSet() && Other.isFullSet())
1237 return getFull();
1238
1239 using OBO = OverflowingBinaryOperator;
1240 ConstantRange Result = sub(Other);
1241
1242 // If an overflow happens for every value pair in these two constant ranges,
1243 // we must return Empty set. In signed case, we get that for free, because we
1244 // get lucky that intersection of sub() with ssub_sat() results in an
1245 // empty set. But for unsigned we must perform the overflow check manually.
1246
1247 if (NoWrapKind & OBO::NoSignedWrap)
1248 Result = Result.intersectWith(CR: ssub_sat(Other), Type: RangeType);
1249
1250 if (NoWrapKind & OBO::NoUnsignedWrap) {
1251 if (getUnsignedMax().ult(RHS: Other.getUnsignedMin()))
1252 return getEmpty(); // Always overflows.
1253 Result = Result.intersectWith(CR: usub_sat(Other), Type: RangeType);
1254 }
1255
1256 return Result;
1257}
1258
1259ConstantRange ConstantRange::multiply(const ConstantRange &Other,
1260 unsigned NoWrapKind) const {
1261 // TODO: If either operand is a single element and the multiply is known to
1262 // be non-wrapping, round the result min and max value to the appropriate
1263 // multiple of that element. If wrapping is possible, at least adjust the
1264 // range according to the greatest power-of-two factor of the single element.
1265
1266 if (isEmptySet() || Other.isEmptySet())
1267 return getEmpty();
1268
1269 if (const APInt *C = getSingleElement()) {
1270 if (C->isOne())
1271 return Other;
1272 if (C->isAllOnes())
1273 return ConstantRange(APInt::getZero(numBits: getBitWidth())).sub(Other);
1274 }
1275
1276 if (const APInt *C = Other.getSingleElement()) {
1277 if (C->isOne())
1278 return *this;
1279 if (C->isAllOnes())
1280 return ConstantRange(APInt::getZero(numBits: getBitWidth())).sub(Other: *this);
1281 }
1282
1283 // Multiplication is signedness-independent. However different ranges can be
1284 // obtained depending on how the input ranges are treated. These different
1285 // ranges are all conservatively correct, but one might be better than the
1286 // other. We calculate two ranges; one treating the inputs as unsigned
1287 // and the other signed, then return the smallest of these ranges.
1288
1289 // Unsigned range first.
1290 unsigned BW = getBitWidth();
1291 ConstantRange UR = getEmpty();
1292 if (NoWrapKind & OverflowingBinaryOperator::NoUnsignedWrap) {
1293 bool MinOv;
1294 APInt MinMul = getUnsignedMin().umul_ov(RHS: Other.getUnsignedMin(), Overflow&: MinOv);
1295 if (MinOv)
1296 return getEmpty();
1297
1298 APInt MaxMul = getUnsignedMax().umul_sat(RHS: Other.getUnsignedMax());
1299 UR = ConstantRange::getNonEmpty(Lower: MinMul, Upper: MaxMul + 1);
1300 } else {
1301 APInt this_min = getUnsignedMin().zext(width: BW * 2);
1302 APInt this_max = getUnsignedMax().zext(width: BW * 2);
1303 APInt Other_min = Other.getUnsignedMin().zext(width: BW * 2);
1304 APInt Other_max = Other.getUnsignedMax().zext(width: BW * 2);
1305
1306 ConstantRange Result_zext =
1307 ConstantRange(this_min * Other_min, this_max * Other_max + 1);
1308 UR = Result_zext.truncate(DstTySize: BW);
1309 }
1310
1311 // If the unsigned range doesn't wrap, and isn't negative then it's a range
1312 // from one positive number to another which is as good as we can generate.
1313 // In this case, skip the extra work of generating signed ranges which aren't
1314 // going to be better than this range.
1315 if (!(NoWrapKind & OverflowingBinaryOperator::NoSignedWrap) &&
1316 !UR.isUpperWrapped() &&
1317 (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
1318 return UR;
1319
1320 // Now the signed range. Because we could be dealing with negative numbers
1321 // here, the lower bound is the smallest of the cartesian product of the
1322 // lower and upper ranges; for example:
1323 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1324 // Similarly for the upper bound, swapping min for max.
1325
1326 // FIXME: Avoid wide multiplications if nsw.
1327 APInt this_min = getSignedMin().sext(width: BW * 2);
1328 APInt this_max = getSignedMax().sext(width: BW * 2);
1329 APInt Other_min = Other.getSignedMin().sext(width: BW * 2);
1330 APInt Other_max = Other.getSignedMax().sext(width: BW * 2);
1331
1332 auto L = {this_min * Other_min, this_min * Other_max,
1333 this_max * Other_min, this_max * Other_max};
1334 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(RHS: B); };
1335 ConstantRange Result_sext(std::min(l: L, comp: Compare), std::max(l: L, comp: Compare) + 1);
1336 if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap) {
1337 Result_sext = Result_sext.intersectWith(
1338 CR: ConstantRange(APInt::getSignedMinValue(numBits: BW).sext(width: BW * 2),
1339 APInt::getSignedMaxValue(numBits: BW).sext(width: BW * 2) + 1));
1340 }
1341 ConstantRange SR = Result_sext.truncate(DstTySize: BW);
1342 ConstantRange Result = UR.isSizeStrictlySmallerThan(Other: SR) ? UR : SR;
1343
1344 // mul nsw nuw X, Y s>= 0 if X s> 1 or Y s> 1
1345 if ((NoWrapKind == (OverflowingBinaryOperator::NoSignedWrap |
1346 OverflowingBinaryOperator::NoUnsignedWrap)) &&
1347 !Result.isAllNonNegative()) {
1348 if (getSignedMin().sgt(RHS: 1) || Other.getSignedMin().sgt(RHS: 1))
1349 Result = Result.intersectWith(
1350 CR: getNonEmpty(Lower: APInt::getZero(numBits: getBitWidth()),
1351 Upper: APInt::getSignedMinValue(numBits: getBitWidth())));
1352 }
1353
1354 return Result;
1355}
1356
1357ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
1358 if (isEmptySet() || Other.isEmptySet())
1359 return getEmpty();
1360
1361 APInt Min = getSignedMin();
1362 APInt Max = getSignedMax();
1363 APInt OtherMin = Other.getSignedMin();
1364 APInt OtherMax = Other.getSignedMax();
1365
1366 bool O1, O2, O3, O4;
1367 auto Muls = {Min.smul_ov(RHS: OtherMin, Overflow&: O1), Min.smul_ov(RHS: OtherMax, Overflow&: O2),
1368 Max.smul_ov(RHS: OtherMin, Overflow&: O3), Max.smul_ov(RHS: OtherMax, Overflow&: O4)};
1369 if (O1 || O2 || O3 || O4)
1370 return getFull();
1371
1372 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(RHS: B); };
1373 return getNonEmpty(Lower: std::min(l: Muls, comp: Compare), Upper: std::max(l: Muls, comp: Compare) + 1);
1374}
1375
1376ConstantRange
1377ConstantRange::smax(const ConstantRange &Other) const {
1378 // X smax Y is: range(smax(X_smin, Y_smin),
1379 // smax(X_smax, Y_smax))
1380 if (isEmptySet() || Other.isEmptySet())
1381 return getEmpty();
1382 APInt NewL = APIntOps::smax(A: getSignedMin(), B: Other.getSignedMin());
1383 APInt NewU = APIntOps::smax(A: getSignedMax(), B: Other.getSignedMax()) + 1;
1384 ConstantRange Res = getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1385 if (isSignWrappedSet() || Other.isSignWrappedSet())
1386 return Res.intersectWith(CR: unionWith(CR: Other, Type: Signed), Type: Signed);
1387 return Res;
1388}
1389
1390ConstantRange
1391ConstantRange::umax(const ConstantRange &Other) const {
1392 // X umax Y is: range(umax(X_umin, Y_umin),
1393 // umax(X_umax, Y_umax))
1394 if (isEmptySet() || Other.isEmptySet())
1395 return getEmpty();
1396 APInt NewL = APIntOps::umax(A: getUnsignedMin(), B: Other.getUnsignedMin());
1397 APInt NewU = APIntOps::umax(A: getUnsignedMax(), B: Other.getUnsignedMax()) + 1;
1398 ConstantRange Res = getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1399 if (isWrappedSet() || Other.isWrappedSet())
1400 return Res.intersectWith(CR: unionWith(CR: Other, Type: Unsigned), Type: Unsigned);
1401 return Res;
1402}
1403
1404ConstantRange
1405ConstantRange::smin(const ConstantRange &Other) const {
1406 // X smin Y is: range(smin(X_smin, Y_smin),
1407 // smin(X_smax, Y_smax))
1408 if (isEmptySet() || Other.isEmptySet())
1409 return getEmpty();
1410 APInt NewL = APIntOps::smin(A: getSignedMin(), B: Other.getSignedMin());
1411 APInt NewU = APIntOps::smin(A: getSignedMax(), B: Other.getSignedMax()) + 1;
1412 ConstantRange Res = getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1413 if (isSignWrappedSet() || Other.isSignWrappedSet())
1414 return Res.intersectWith(CR: unionWith(CR: Other, Type: Signed), Type: Signed);
1415 return Res;
1416}
1417
1418ConstantRange
1419ConstantRange::umin(const ConstantRange &Other) const {
1420 // X umin Y is: range(umin(X_umin, Y_umin),
1421 // umin(X_umax, Y_umax))
1422 if (isEmptySet() || Other.isEmptySet())
1423 return getEmpty();
1424 APInt NewL = APIntOps::umin(A: getUnsignedMin(), B: Other.getUnsignedMin());
1425 APInt NewU = APIntOps::umin(A: getUnsignedMax(), B: Other.getUnsignedMax()) + 1;
1426 ConstantRange Res = getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1427 if (isWrappedSet() || Other.isWrappedSet())
1428 return Res.intersectWith(CR: unionWith(CR: Other, Type: Unsigned), Type: Unsigned);
1429 return Res;
1430}
1431
1432ConstantRange
1433ConstantRange::udiv(const ConstantRange &RHS) const {
1434 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1435 return getEmpty();
1436
1437 APInt Lower = getUnsignedMin().udiv(RHS: RHS.getUnsignedMax());
1438
1439 APInt RHS_umin = RHS.getUnsignedMin();
1440 if (RHS_umin.isZero()) {
1441 // We want the lowest value in RHS excluding zero. Usually that would be 1
1442 // except for a range in the form of [X, 1) in which case it would be X.
1443 if (RHS.getUpper() == 1)
1444 RHS_umin = RHS.getLower();
1445 else
1446 RHS_umin = 1;
1447 }
1448
1449 APInt Upper = getUnsignedMax().udiv(RHS: RHS_umin) + 1;
1450 return getNonEmpty(Lower: std::move(Lower), Upper: std::move(Upper));
1451}
1452
1453ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
1454 APInt Zero = APInt::getZero(numBits: getBitWidth());
1455 APInt SignedMin = APInt::getSignedMinValue(numBits: getBitWidth());
1456
1457 // We split up the LHS and RHS into positive and negative components
1458 // and then also compute the positive and negative components of the result
1459 // separately by combining division results with the appropriate signs.
1460 auto [PosL, NegL] = splitPosNeg();
1461 auto [PosR, NegR] = RHS.splitPosNeg();
1462
1463 ConstantRange PosRes = getEmpty();
1464 if (!PosL.isEmptySet() && !PosR.isEmptySet())
1465 // pos / pos = pos.
1466 PosRes = ConstantRange(PosL.Lower.sdiv(RHS: PosR.Upper - 1),
1467 (PosL.Upper - 1).sdiv(RHS: PosR.Lower) + 1);
1468
1469 if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1470 // neg / neg = pos.
1471 //
1472 // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1473 // IR level, so we'll want to exclude this case when calculating bounds.
1474 // (For APInts the operation is well-defined and yields SignedMin.) We
1475 // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1476 APInt Lo = (NegL.Upper - 1).sdiv(RHS: NegR.Lower);
1477 if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1478 // Remove -1 from the LHS. Skip if it's the only element, as this would
1479 // leave us with an empty set.
1480 if (!NegR.Lower.isAllOnes()) {
1481 APInt AdjNegRUpper;
1482 if (RHS.Lower.isAllOnes())
1483 // Negative part of [-1, X] without -1 is [SignedMin, X].
1484 AdjNegRUpper = RHS.Upper;
1485 else
1486 // [X, -1] without -1 is [X, -2].
1487 AdjNegRUpper = NegR.Upper - 1;
1488
1489 PosRes = PosRes.unionWith(
1490 CR: ConstantRange(Lo, NegL.Lower.sdiv(RHS: AdjNegRUpper - 1) + 1));
1491 }
1492
1493 // Remove SignedMin from the RHS. Skip if it's the only element, as this
1494 // would leave us with an empty set.
1495 if (NegL.Upper != SignedMin + 1) {
1496 APInt AdjNegLLower;
1497 if (Upper == SignedMin + 1)
1498 // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1499 AdjNegLLower = Lower;
1500 else
1501 // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1502 AdjNegLLower = NegL.Lower + 1;
1503
1504 PosRes = PosRes.unionWith(
1505 CR: ConstantRange(std::move(Lo),
1506 AdjNegLLower.sdiv(RHS: NegR.Upper - 1) + 1));
1507 }
1508 } else {
1509 PosRes = PosRes.unionWith(
1510 CR: ConstantRange(std::move(Lo), NegL.Lower.sdiv(RHS: NegR.Upper - 1) + 1));
1511 }
1512 }
1513
1514 ConstantRange NegRes = getEmpty();
1515 if (!PosL.isEmptySet() && !NegR.isEmptySet())
1516 // pos / neg = neg.
1517 NegRes = ConstantRange((PosL.Upper - 1).sdiv(RHS: NegR.Upper - 1),
1518 PosL.Lower.sdiv(RHS: NegR.Lower) + 1);
1519
1520 if (!NegL.isEmptySet() && !PosR.isEmptySet())
1521 // neg / pos = neg.
1522 NegRes = NegRes.unionWith(
1523 CR: ConstantRange(NegL.Lower.sdiv(RHS: PosR.Lower),
1524 (NegL.Upper - 1).sdiv(RHS: PosR.Upper - 1) + 1));
1525
1526 // Prefer a non-wrapping signed range here.
1527 ConstantRange Res = NegRes.unionWith(CR: PosRes, Type: PreferredRangeType::Signed);
1528
1529 // Preserve the zero that we dropped when splitting the LHS by sign.
1530 if (contains(V: Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1531 Res = Res.unionWith(CR: ConstantRange(Zero));
1532 return Res;
1533}
1534
1535ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
1536 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1537 return getEmpty();
1538
1539 if (const APInt *RHSInt = RHS.getSingleElement()) {
1540 // UREM by null is UB.
1541 if (RHSInt->isZero())
1542 return getEmpty();
1543 // Use APInt's implementation of UREM for single element ranges.
1544 if (const APInt *LHSInt = getSingleElement())
1545 return {LHSInt->urem(RHS: *RHSInt)};
1546 }
1547
1548 // L % R for L < R is L.
1549 if (getUnsignedMax().ult(RHS: RHS.getUnsignedMin()))
1550 return *this;
1551
1552 // L % R is <= L and < R.
1553 APInt Upper = APIntOps::umin(A: getUnsignedMax(), B: RHS.getUnsignedMax() - 1) + 1;
1554 return getNonEmpty(Lower: APInt::getZero(numBits: getBitWidth()), Upper: std::move(Upper));
1555}
1556
1557ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
1558 if (isEmptySet() || RHS.isEmptySet())
1559 return getEmpty();
1560
1561 if (const APInt *RHSInt = RHS.getSingleElement()) {
1562 // SREM by null is UB.
1563 if (RHSInt->isZero())
1564 return getEmpty();
1565 // Use APInt's implementation of SREM for single element ranges.
1566 if (const APInt *LHSInt = getSingleElement())
1567 return {LHSInt->srem(RHS: *RHSInt)};
1568 }
1569
1570 ConstantRange AbsRHS = RHS.abs();
1571 APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1572 APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1573
1574 // Modulus by zero is UB.
1575 if (MaxAbsRHS.isZero())
1576 return getEmpty();
1577
1578 if (MinAbsRHS.isZero())
1579 ++MinAbsRHS;
1580
1581 APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1582
1583 if (MinLHS.isNonNegative()) {
1584 // L % R for L < R is L.
1585 if (MaxLHS.ult(RHS: MinAbsRHS))
1586 return *this;
1587
1588 // L % R is <= L and < R.
1589 APInt Upper = APIntOps::umin(A: MaxLHS, B: MaxAbsRHS - 1) + 1;
1590 return ConstantRange(APInt::getZero(numBits: getBitWidth()), std::move(Upper));
1591 }
1592
1593 // Same basic logic as above, but the result is negative.
1594 if (MaxLHS.isNegative()) {
1595 if (MinLHS.ugt(RHS: -MinAbsRHS))
1596 return *this;
1597
1598 APInt Lower = APIntOps::umax(A: MinLHS, B: -MaxAbsRHS + 1);
1599 return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1600 }
1601
1602 // LHS range crosses zero.
1603 APInt Lower = APIntOps::umax(A: MinLHS, B: -MaxAbsRHS + 1);
1604 APInt Upper = APIntOps::umin(A: MaxLHS, B: MaxAbsRHS - 1) + 1;
1605 return ConstantRange(std::move(Lower), std::move(Upper));
1606}
1607
1608ConstantRange ConstantRange::binaryNot() const {
1609 return ConstantRange(APInt::getAllOnes(numBits: getBitWidth())).sub(Other: *this);
1610}
1611
1612/// Estimate the 'bit-masked AND' operation's lower bound.
1613///
1614/// E.g., given two ranges as follows (single quotes are separators and
1615/// have no meaning here),
1616///
1617/// LHS = [10'00101'1, ; LLo
1618/// 10'10000'0] ; LHi
1619/// RHS = [10'11111'0, ; RLo
1620/// 10'11111'1] ; RHi
1621///
1622/// we know that the higher 2 bits of the result is always 10; and we also
1623/// notice that RHS[1:6] are always 1, so the result[1:6] cannot be less than
1624/// LHS[1:6] (i.e., 00101). Thus, the lower bound is 10'00101'0.
1625///
1626/// The algorithm is as follows,
1627/// 1. we first calculate a mask to find the higher common bits by
1628/// Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1629/// Mask = clear all non-leading-ones bits in Mask;
1630/// in the example, the Mask is set to 11'00000'0;
1631/// 2. calculate a new mask by setting all common leading bits to 1 in RHS, and
1632/// keeping the longest leading ones (i.e., 11'11111'0 in the example);
1633/// 3. return (LLo & new mask) as the lower bound;
1634/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
1635/// bound with the larger one.
1636static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
1637 const ConstantRange &RHS) {
1638 auto BitWidth = LHS.getBitWidth();
1639 // If either is full set or unsigned wrapped, then the range must contain '0'
1640 // which leads the lower bound to 0.
1641 if ((LHS.isFullSet() || RHS.isFullSet()) ||
1642 (LHS.isWrappedSet() || RHS.isWrappedSet()))
1643 return APInt::getZero(numBits: BitWidth);
1644
1645 auto LLo = LHS.getLower();
1646 auto LHi = LHS.getUpper() - 1;
1647 auto RLo = RHS.getLower();
1648 auto RHi = RHS.getUpper() - 1;
1649
1650 // Calculate the mask for the higher common bits.
1651 auto Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1652 unsigned LeadingOnes = Mask.countLeadingOnes();
1653 Mask.clearLowBits(loBits: BitWidth - LeadingOnes);
1654
1655 auto estimateBound = [BitWidth, &Mask](APInt ALo, const APInt &BLo,
1656 const APInt &BHi) {
1657 unsigned LeadingOnes = ((BLo & BHi) | Mask).countLeadingOnes();
1658 unsigned StartBit = BitWidth - LeadingOnes;
1659 ALo.clearLowBits(loBits: StartBit);
1660 return ALo;
1661 };
1662
1663 auto LowerBoundByLHS = estimateBound(LLo, RLo, RHi);
1664 auto LowerBoundByRHS = estimateBound(RLo, LLo, LHi);
1665
1666 return APIntOps::umax(A: LowerBoundByLHS, B: LowerBoundByRHS);
1667}
1668
1669ConstantRange ConstantRange::binaryAnd(const ConstantRange &Other) const {
1670 if (isEmptySet() || Other.isEmptySet())
1671 return getEmpty();
1672
1673 ConstantRange KnownBitsRange =
1674 fromKnownBits(Known: toKnownBits() & Other.toKnownBits(), IsSigned: false);
1675 auto LowerBound = estimateBitMaskedAndLowerBound(LHS: *this, RHS: Other);
1676 ConstantRange UMinUMaxRange = getNonEmpty(
1677 Lower: LowerBound, Upper: APIntOps::umin(A: Other.getUnsignedMax(), B: getUnsignedMax()) + 1);
1678 return KnownBitsRange.intersectWith(CR: UMinUMaxRange);
1679}
1680
1681ConstantRange ConstantRange::binaryOr(const ConstantRange &Other,
1682 bool IsDisjoint) const {
1683 if (isEmptySet() || Other.isEmptySet())
1684 return getEmpty();
1685
1686 ConstantRange KnownBitsRange =
1687 fromKnownBits(Known: toKnownBits() | Other.toKnownBits(), IsSigned: false);
1688
1689 // ~a & ~b >= x
1690 // <=> ~(~a & ~b) <= ~x
1691 // <=> a | b <= ~x
1692 // <=> a | b < ~x + 1 = -x
1693 // thus, UpperBound(a | b) == -LowerBound(~a & ~b)
1694 auto UpperBound =
1695 -estimateBitMaskedAndLowerBound(LHS: binaryNot(), RHS: Other.binaryNot());
1696 // Upper wrapped range.
1697 ConstantRange UMaxUMinRange = getNonEmpty(
1698 Lower: APIntOps::umax(A: getUnsignedMin(), B: Other.getUnsignedMin()), Upper: UpperBound);
1699 ConstantRange Result = KnownBitsRange.intersectWith(CR: UMaxUMinRange);
1700
1701 if (IsDisjoint) {
1702 // Treat 'or disjoint' as both 'add nuw nsw' and binary or, picking the best
1703 // from both.
1704 using OBO = OverflowingBinaryOperator;
1705 Result = addWithNoWrap(Other, NoWrapKind: OBO::NoUnsignedWrap | OBO::NoSignedWrap)
1706 .intersectWith(CR: Result);
1707 }
1708 return Result;
1709}
1710
1711ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
1712 if (isEmptySet() || Other.isEmptySet())
1713 return getEmpty();
1714
1715 // Use APInt's implementation of XOR for single element ranges.
1716 if (isSingleElement() && Other.isSingleElement())
1717 return {*getSingleElement() ^ *Other.getSingleElement()};
1718
1719 // Special-case binary complement, since we can give a precise answer.
1720 if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1721 return binaryNot();
1722 if (isSingleElement() && getSingleElement()->isAllOnes())
1723 return Other.binaryNot();
1724
1725 KnownBits LHSKnown = toKnownBits();
1726 KnownBits RHSKnown = Other.toKnownBits();
1727 KnownBits Known = LHSKnown ^ RHSKnown;
1728 ConstantRange CR = fromKnownBits(Known, /*IsSigned*/ false);
1729 // Typically the following code doesn't improve the result if BW = 1.
1730 if (getBitWidth() == 1)
1731 return CR;
1732
1733 // If LHS is known to be the subset of RHS, treat LHS ^ RHS as RHS -nuw/nsw
1734 // LHS. If RHS is known to be the subset of LHS, treat LHS ^ RHS as LHS
1735 // -nuw/nsw RHS.
1736 if ((~LHSKnown.Zero).isSubsetOf(RHS: RHSKnown.One))
1737 CR = CR.intersectWith(CR: Other.sub(Other: *this), Type: PreferredRangeType::Unsigned);
1738 else if ((~RHSKnown.Zero).isSubsetOf(RHS: LHSKnown.One))
1739 CR = CR.intersectWith(CR: this->sub(Other), Type: PreferredRangeType::Unsigned);
1740 return CR;
1741}
1742
1743ConstantRange
1744ConstantRange::shl(const ConstantRange &Other) const {
1745 if (isEmptySet() || Other.isEmptySet())
1746 return getEmpty();
1747
1748 APInt Min = getUnsignedMin();
1749 APInt Max = getUnsignedMax();
1750 if (const APInt *RHS = Other.getSingleElement()) {
1751 unsigned BW = getBitWidth();
1752 if (RHS->uge(RHS: BW))
1753 return getEmpty();
1754
1755 unsigned EqualLeadingBits = (Min ^ Max).countl_zero();
1756 if (RHS->ule(RHS: EqualLeadingBits))
1757 return getNonEmpty(Lower: Min << *RHS, Upper: (Max << *RHS) + 1);
1758
1759 return getNonEmpty(Lower: APInt::getZero(numBits: BW),
1760 Upper: APInt::getBitsSetFrom(numBits: BW, loBit: RHS->getZExtValue()) + 1);
1761 }
1762
1763 APInt OtherMax = Other.getUnsignedMax();
1764 if (isAllNegative() && OtherMax.ule(RHS: Min.countl_one())) {
1765 // For negative numbers, if the shift does not overflow in a signed sense,
1766 // a larger shift will make the number smaller.
1767 Max <<= Other.getUnsignedMin();
1768 Min <<= OtherMax;
1769 return ConstantRange::getNonEmpty(Lower: std::move(Min), Upper: std::move(Max) + 1);
1770 }
1771
1772 // There's overflow!
1773 if (OtherMax.ugt(RHS: Max.countl_zero()))
1774 return getFull();
1775
1776 // FIXME: implement the other tricky cases
1777
1778 Min <<= Other.getUnsignedMin();
1779 Max <<= OtherMax;
1780
1781 return ConstantRange::getNonEmpty(Lower: std::move(Min), Upper: std::move(Max) + 1);
1782}
1783
1784static ConstantRange computeShlNUW(const ConstantRange &LHS,
1785 const ConstantRange &RHS) {
1786 unsigned BitWidth = LHS.getBitWidth();
1787 bool Overflow;
1788 APInt LHSMin = LHS.getUnsignedMin();
1789 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(Limit: BitWidth);
1790 APInt MinShl = LHSMin.ushl_ov(Amt: RHSMin, Overflow);
1791 if (Overflow)
1792 return ConstantRange::getEmpty(BitWidth);
1793 APInt LHSMax = LHS.getUnsignedMax();
1794 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(Limit: BitWidth);
1795 APInt MaxShl = MinShl;
1796 unsigned MaxShAmt = LHSMax.countLeadingZeros();
1797 if (RHSMin <= MaxShAmt)
1798 MaxShl = LHSMax << std::min(a: RHSMax, b: MaxShAmt);
1799 RHSMin = std::max(a: RHSMin, b: MaxShAmt + 1);
1800 RHSMax = std::min(a: RHSMax, b: LHSMin.countLeadingZeros());
1801 if (RHSMin <= RHSMax)
1802 MaxShl = APIntOps::umax(A: MaxShl,
1803 B: APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - RHSMin));
1804 return ConstantRange::getNonEmpty(Lower: MinShl, Upper: MaxShl + 1);
1805}
1806
1807static ConstantRange computeShlNSWWithNNegLHS(const APInt &LHSMin,
1808 const APInt &LHSMax,
1809 unsigned RHSMin,
1810 unsigned RHSMax) {
1811 unsigned BitWidth = LHSMin.getBitWidth();
1812 bool Overflow;
1813 APInt MinShl = LHSMin.sshl_ov(Amt: RHSMin, Overflow);
1814 if (Overflow)
1815 return ConstantRange::getEmpty(BitWidth);
1816 APInt MaxShl = MinShl;
1817 unsigned MaxShAmt = LHSMax.countLeadingZeros() - 1;
1818 if (RHSMin <= MaxShAmt)
1819 MaxShl = LHSMax << std::min(a: RHSMax, b: MaxShAmt);
1820 RHSMin = std::max(a: RHSMin, b: MaxShAmt + 1);
1821 RHSMax = std::min(a: RHSMax, b: LHSMin.countLeadingZeros() - 1);
1822 if (RHSMin <= RHSMax)
1823 MaxShl = APIntOps::umax(A: MaxShl,
1824 B: APInt::getBitsSet(numBits: BitWidth, loBit: RHSMin, hiBit: BitWidth - 1));
1825 return ConstantRange::getNonEmpty(Lower: MinShl, Upper: MaxShl + 1);
1826}
1827
1828static ConstantRange computeShlNSWWithNegLHS(const APInt &LHSMin,
1829 const APInt &LHSMax,
1830 unsigned RHSMin, unsigned RHSMax) {
1831 unsigned BitWidth = LHSMin.getBitWidth();
1832 bool Overflow;
1833 APInt MaxShl = LHSMax.sshl_ov(Amt: RHSMin, Overflow);
1834 if (Overflow)
1835 return ConstantRange::getEmpty(BitWidth);
1836 APInt MinShl = MaxShl;
1837 unsigned MaxShAmt = LHSMin.countLeadingOnes() - 1;
1838 if (RHSMin <= MaxShAmt)
1839 MinShl = LHSMin.shl(shiftAmt: std::min(a: RHSMax, b: MaxShAmt));
1840 RHSMin = std::max(a: RHSMin, b: MaxShAmt + 1);
1841 RHSMax = std::min(a: RHSMax, b: LHSMax.countLeadingOnes() - 1);
1842 if (RHSMin <= RHSMax)
1843 MinShl = APInt::getSignMask(BitWidth);
1844 return ConstantRange::getNonEmpty(Lower: MinShl, Upper: MaxShl + 1);
1845}
1846
1847static ConstantRange computeShlNSW(const ConstantRange &LHS,
1848 const ConstantRange &RHS) {
1849 unsigned BitWidth = LHS.getBitWidth();
1850 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(Limit: BitWidth);
1851 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(Limit: BitWidth);
1852 APInt LHSMin = LHS.getSignedMin();
1853 APInt LHSMax = LHS.getSignedMax();
1854 if (LHSMin.isNonNegative())
1855 return computeShlNSWWithNNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1856 else if (LHSMax.isNegative())
1857 return computeShlNSWWithNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1858 return computeShlNSWWithNNegLHS(LHSMin: APInt::getZero(numBits: BitWidth), LHSMax, RHSMin,
1859 RHSMax)
1860 .unionWith(CR: computeShlNSWWithNegLHS(LHSMin, LHSMax: APInt::getAllOnes(numBits: BitWidth),
1861 RHSMin, RHSMax),
1862 Type: ConstantRange::Signed);
1863}
1864
1865ConstantRange ConstantRange::shlWithNoWrap(const ConstantRange &Other,
1866 unsigned NoWrapKind,
1867 PreferredRangeType RangeType) const {
1868 if (isEmptySet() || Other.isEmptySet())
1869 return getEmpty();
1870
1871 switch (NoWrapKind) {
1872 case 0:
1873 return shl(Other);
1874 case OverflowingBinaryOperator::NoSignedWrap:
1875 return computeShlNSW(LHS: *this, RHS: Other);
1876 case OverflowingBinaryOperator::NoUnsignedWrap:
1877 return computeShlNUW(LHS: *this, RHS: Other);
1878 case OverflowingBinaryOperator::NoSignedWrap |
1879 OverflowingBinaryOperator::NoUnsignedWrap:
1880 return computeShlNSW(LHS: *this, RHS: Other)
1881 .intersectWith(CR: computeShlNUW(LHS: *this, RHS: Other), Type: RangeType);
1882 default:
1883 llvm_unreachable("Invalid NoWrapKind");
1884 }
1885}
1886
1887ConstantRange
1888ConstantRange::lshr(const ConstantRange &Other) const {
1889 if (isEmptySet() || Other.isEmptySet())
1890 return getEmpty();
1891
1892 APInt max = getUnsignedMax().lshr(ShiftAmt: Other.getUnsignedMin()) + 1;
1893 APInt min = getUnsignedMin().lshr(ShiftAmt: Other.getUnsignedMax());
1894 return getNonEmpty(Lower: std::move(min), Upper: std::move(max));
1895}
1896
1897ConstantRange
1898ConstantRange::ashr(const ConstantRange &Other) const {
1899 if (isEmptySet() || Other.isEmptySet())
1900 return getEmpty();
1901
1902 // May straddle zero, so handle both positive and negative cases.
1903 // 'PosMax' is the upper bound of the result of the ashr
1904 // operation, when Upper of the LHS of ashr is a non-negative.
1905 // number. Since ashr of a non-negative number will result in a
1906 // smaller number, the Upper value of LHS is shifted right with
1907 // the minimum value of 'Other' instead of the maximum value.
1908 APInt PosMax = getSignedMax().ashr(ShiftAmt: Other.getUnsignedMin()) + 1;
1909
1910 // 'PosMin' is the lower bound of the result of the ashr
1911 // operation, when Lower of the LHS is a non-negative number.
1912 // Since ashr of a non-negative number will result in a smaller
1913 // number, the Lower value of LHS is shifted right with the
1914 // maximum value of 'Other'.
1915 APInt PosMin = getSignedMin().ashr(ShiftAmt: Other.getUnsignedMax());
1916
1917 // 'NegMax' is the upper bound of the result of the ashr
1918 // operation, when Upper of the LHS of ashr is a negative number.
1919 // Since 'ashr' of a negative number will result in a bigger
1920 // number, the Upper value of LHS is shifted right with the
1921 // maximum value of 'Other'.
1922 APInt NegMax = getSignedMax().ashr(ShiftAmt: Other.getUnsignedMax()) + 1;
1923
1924 // 'NegMin' is the lower bound of the result of the ashr
1925 // operation, when Lower of the LHS of ashr is a negative number.
1926 // Since 'ashr' of a negative number will result in a bigger
1927 // number, the Lower value of LHS is shifted right with the
1928 // minimum value of 'Other'.
1929 APInt NegMin = getSignedMin().ashr(ShiftAmt: Other.getUnsignedMin());
1930
1931 APInt max, min;
1932 if (getSignedMin().isNonNegative()) {
1933 // Upper and Lower of LHS are non-negative.
1934 min = std::move(PosMin);
1935 max = std::move(PosMax);
1936 } else if (getSignedMax().isNegative()) {
1937 // Upper and Lower of LHS are negative.
1938 min = std::move(NegMin);
1939 max = std::move(NegMax);
1940 } else {
1941 // Upper is non-negative and Lower is negative.
1942 min = std::move(NegMin);
1943 max = std::move(PosMax);
1944 }
1945 return getNonEmpty(Lower: std::move(min), Upper: std::move(max));
1946}
1947
1948ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1949 if (isEmptySet() || Other.isEmptySet())
1950 return getEmpty();
1951
1952 APInt NewL = getUnsignedMin().uadd_sat(RHS: Other.getUnsignedMin());
1953 APInt NewU = getUnsignedMax().uadd_sat(RHS: Other.getUnsignedMax()) + 1;
1954 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1955}
1956
1957ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1958 if (isEmptySet() || Other.isEmptySet())
1959 return getEmpty();
1960
1961 APInt NewL = getSignedMin().sadd_sat(RHS: Other.getSignedMin());
1962 APInt NewU = getSignedMax().sadd_sat(RHS: Other.getSignedMax()) + 1;
1963 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1964}
1965
1966ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1967 if (isEmptySet() || Other.isEmptySet())
1968 return getEmpty();
1969
1970 APInt NewL = getUnsignedMin().usub_sat(RHS: Other.getUnsignedMax());
1971 APInt NewU = getUnsignedMax().usub_sat(RHS: Other.getUnsignedMin()) + 1;
1972 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1973}
1974
1975ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1976 if (isEmptySet() || Other.isEmptySet())
1977 return getEmpty();
1978
1979 APInt NewL = getSignedMin().ssub_sat(RHS: Other.getSignedMax());
1980 APInt NewU = getSignedMax().ssub_sat(RHS: Other.getSignedMin()) + 1;
1981 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1982}
1983
1984ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
1985 if (isEmptySet() || Other.isEmptySet())
1986 return getEmpty();
1987
1988 APInt NewL = getUnsignedMin().umul_sat(RHS: Other.getUnsignedMin());
1989 APInt NewU = getUnsignedMax().umul_sat(RHS: Other.getUnsignedMax()) + 1;
1990 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
1991}
1992
1993ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
1994 if (isEmptySet() || Other.isEmptySet())
1995 return getEmpty();
1996
1997 // Because we could be dealing with negative numbers here, the lower bound is
1998 // the smallest of the cartesian product of the lower and upper ranges;
1999 // for example:
2000 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
2001 // Similarly for the upper bound, swapping min for max.
2002
2003 APInt Min = getSignedMin();
2004 APInt Max = getSignedMax();
2005 APInt OtherMin = Other.getSignedMin();
2006 APInt OtherMax = Other.getSignedMax();
2007
2008 auto L = {Min.smul_sat(RHS: OtherMin), Min.smul_sat(RHS: OtherMax),
2009 Max.smul_sat(RHS: OtherMin), Max.smul_sat(RHS: OtherMax)};
2010 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(RHS: B); };
2011 return getNonEmpty(Lower: std::min(l: L, comp: Compare), Upper: std::max(l: L, comp: Compare) + 1);
2012}
2013
2014ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
2015 if (isEmptySet() || Other.isEmptySet())
2016 return getEmpty();
2017
2018 APInt NewL = getUnsignedMin().ushl_sat(RHS: Other.getUnsignedMin());
2019 APInt NewU = getUnsignedMax().ushl_sat(RHS: Other.getUnsignedMax()) + 1;
2020 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
2021}
2022
2023ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
2024 if (isEmptySet() || Other.isEmptySet())
2025 return getEmpty();
2026
2027 APInt Min = getSignedMin(), Max = getSignedMax();
2028 APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
2029 APInt NewL = Min.sshl_sat(RHS: Min.isNonNegative() ? ShAmtMin : ShAmtMax);
2030 APInt NewU = Max.sshl_sat(RHS: Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
2031 return getNonEmpty(Lower: std::move(NewL), Upper: std::move(NewU));
2032}
2033
2034ConstantRange ConstantRange::inverse() const {
2035 if (isFullSet())
2036 return getEmpty();
2037 if (isEmptySet())
2038 return getFull();
2039 return ConstantRange(Upper, Lower);
2040}
2041
2042ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
2043 if (isEmptySet())
2044 return getEmpty();
2045
2046 if (isSignWrappedSet()) {
2047 APInt Lo;
2048 // Check whether the range crosses zero.
2049 if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
2050 Lo = APInt::getZero(numBits: getBitWidth());
2051 else
2052 Lo = APIntOps::umin(A: Lower, B: -Upper + 1);
2053
2054 // If SignedMin is not poison, then it is included in the result range.
2055 if (IntMinIsPoison)
2056 return ConstantRange(Lo, APInt::getSignedMinValue(numBits: getBitWidth()));
2057 else
2058 return ConstantRange(Lo, APInt::getSignedMinValue(numBits: getBitWidth()) + 1);
2059 }
2060
2061 APInt SMin = getSignedMin(), SMax = getSignedMax();
2062
2063 // Skip SignedMin if it is poison.
2064 if (IntMinIsPoison && SMin.isMinSignedValue()) {
2065 // The range may become empty if it *only* contains SignedMin.
2066 if (SMax.isMinSignedValue())
2067 return getEmpty();
2068 ++SMin;
2069 }
2070
2071 // All non-negative.
2072 if (SMin.isNonNegative())
2073 return ConstantRange(SMin, SMax + 1);
2074
2075 // All negative.
2076 if (SMax.isNegative())
2077 return ConstantRange(-SMax, -SMin + 1);
2078
2079 // Range crosses zero.
2080 return ConstantRange::getNonEmpty(Lower: APInt::getZero(numBits: getBitWidth()),
2081 Upper: APIntOps::umax(A: -SMin, B: SMax) + 1);
2082}
2083
2084ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
2085 if (isEmptySet())
2086 return getEmpty();
2087
2088 APInt Zero = APInt::getZero(numBits: getBitWidth());
2089 if (ZeroIsPoison && contains(V: Zero)) {
2090 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
2091 // which a zero can appear:
2092 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
2093 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
2094 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
2095
2096 if (getLower().isZero()) {
2097 if ((getUpper() - 1).isZero()) {
2098 // We have in input interval of kind [0, 1). In this case we cannot
2099 // really help but return empty-set.
2100 return getEmpty();
2101 }
2102
2103 // Compute the resulting range by excluding zero from Lower.
2104 return ConstantRange(
2105 APInt(getBitWidth(), (getUpper() - 1).countl_zero()),
2106 APInt(getBitWidth(), (getLower() + 1).countl_zero() + 1));
2107 } else if ((getUpper() - 1).isZero()) {
2108 // Compute the resulting range by excluding zero from Upper.
2109 return ConstantRange(Zero,
2110 APInt(getBitWidth(), getLower().countl_zero() + 1));
2111 } else {
2112 return ConstantRange(Zero, APInt(getBitWidth(), getBitWidth()));
2113 }
2114 }
2115
2116 // Zero is either safe or not in the range. The output range is composed by
2117 // the result of countLeadingZero of the two extremes.
2118 return getNonEmpty(Lower: APInt(getBitWidth(), getUnsignedMax().countl_zero()),
2119 Upper: APInt(getBitWidth(), getUnsignedMin().countl_zero()) + 1);
2120}
2121
2122static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower,
2123 const APInt &Upper) {
2124 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2125 "Unexpected wrapped set.");
2126 assert(Lower != Upper && "Unexpected empty set.");
2127 unsigned BitWidth = Lower.getBitWidth();
2128 if (Lower + 1 == Upper)
2129 return ConstantRange(APInt(BitWidth, Lower.countr_zero()));
2130 if (Lower.isZero())
2131 return ConstantRange(APInt::getZero(numBits: BitWidth),
2132 APInt(BitWidth, BitWidth + 1));
2133
2134 // Calculate longest common prefix.
2135 unsigned LCPLength = (Lower ^ (Upper - 1)).countl_zero();
2136 // If Lower is {LCP, 000...}, the maximum is Lower.countr_zero().
2137 // Otherwise, the maximum is BitWidth - LCPLength - 1 ({LCP, 100...}).
2138 return ConstantRange(
2139 APInt::getZero(numBits: BitWidth),
2140 APInt(BitWidth,
2141 std::max(a: BitWidth - LCPLength - 1, b: Lower.countr_zero()) + 1));
2142}
2143
2144ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
2145 if (isEmptySet())
2146 return getEmpty();
2147
2148 unsigned BitWidth = getBitWidth();
2149 APInt Zero = APInt::getZero(numBits: BitWidth);
2150 if (ZeroIsPoison && contains(V: Zero)) {
2151 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
2152 // which a zero can appear:
2153 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
2154 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
2155 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
2156
2157 if (Lower.isZero()) {
2158 if (Upper == 1) {
2159 // We have in input interval of kind [0, 1). In this case we cannot
2160 // really help but return empty-set.
2161 return getEmpty();
2162 }
2163
2164 // Compute the resulting range by excluding zero from Lower.
2165 return getUnsignedCountTrailingZerosRange(Lower: APInt(BitWidth, 1), Upper);
2166 } else if (Upper == 1) {
2167 // Compute the resulting range by excluding zero from Upper.
2168 return getUnsignedCountTrailingZerosRange(Lower, Upper: Zero);
2169 } else {
2170 ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Upper: Zero);
2171 ConstantRange CR2 =
2172 getUnsignedCountTrailingZerosRange(Lower: APInt(BitWidth, 1), Upper);
2173 return CR1.unionWith(CR: CR2);
2174 }
2175 }
2176
2177 if (isFullSet())
2178 return getNonEmpty(Lower: Zero, Upper: APInt(BitWidth, BitWidth) + 1);
2179 if (!isWrappedSet())
2180 return getUnsignedCountTrailingZerosRange(Lower, Upper);
2181 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2182 // [Lower, 0).
2183 // Handle [Lower, 0)
2184 ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Upper: Zero);
2185 // Handle [0, Upper)
2186 ConstantRange CR2 = getUnsignedCountTrailingZerosRange(Lower: Zero, Upper);
2187 return CR1.unionWith(CR: CR2);
2188}
2189
2190static ConstantRange getUnsignedPopCountRange(const APInt &Lower,
2191 const APInt &Upper) {
2192 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2193 "Unexpected wrapped set.");
2194 assert(Lower != Upper && "Unexpected empty set.");
2195 unsigned BitWidth = Lower.getBitWidth();
2196 if (Lower + 1 == Upper)
2197 return ConstantRange(APInt(BitWidth, Lower.popcount()));
2198
2199 APInt Max = Upper - 1;
2200 // Calculate longest common prefix.
2201 unsigned LCPLength = (Lower ^ Max).countl_zero();
2202 unsigned LCPPopCount = Lower.getHiBits(numBits: LCPLength).popcount();
2203 // If Lower is {LCP, 000...}, the minimum is the popcount of LCP.
2204 // Otherwise, the minimum is the popcount of LCP + 1.
2205 unsigned MinBits =
2206 LCPPopCount + (Lower.countr_zero() < BitWidth - LCPLength ? 1 : 0);
2207 // If Max is {LCP, 111...}, the maximum is the popcount of LCP + (BitWidth -
2208 // length of LCP).
2209 // Otherwise, the minimum is the popcount of LCP + (BitWidth -
2210 // length of LCP - 1).
2211 unsigned MaxBits = LCPPopCount + (BitWidth - LCPLength) -
2212 (Max.countr_one() < BitWidth - LCPLength ? 1 : 0);
2213 return ConstantRange(APInt(BitWidth, MinBits), APInt(BitWidth, MaxBits + 1));
2214}
2215
2216ConstantRange ConstantRange::ctpop() const {
2217 if (isEmptySet())
2218 return getEmpty();
2219
2220 unsigned BitWidth = getBitWidth();
2221 APInt Zero = APInt::getZero(numBits: BitWidth);
2222 if (isFullSet())
2223 return getNonEmpty(Lower: Zero, Upper: APInt(BitWidth, BitWidth) + 1);
2224 if (!isWrappedSet())
2225 return getUnsignedPopCountRange(Lower, Upper);
2226 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2227 // [Lower, 0).
2228 // Handle [Lower, 0) == [Lower, Max]
2229 ConstantRange CR1 = ConstantRange(APInt(BitWidth, Lower.countl_one()),
2230 APInt(BitWidth, BitWidth + 1));
2231 // Handle [0, Upper)
2232 ConstantRange CR2 = getUnsignedPopCountRange(Lower: Zero, Upper);
2233 return CR1.unionWith(CR: CR2);
2234}
2235
2236ConstantRange ConstantRange::sqrtFloor() const {
2237 if (isEmptySet())
2238 return getEmpty();
2239
2240 // sqrtFloor is monotonic, so the output range is composed by the result of
2241 // sqrtFloor of the two extremes.
2242 return getNonEmpty(Lower: getUnsignedMin().sqrtFloor(),
2243 Upper: getUnsignedMax().sqrtFloor() + 1);
2244}
2245
2246ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
2247 const ConstantRange &Other) const {
2248 if (isEmptySet() || Other.isEmptySet())
2249 return OverflowResult::MayOverflow;
2250
2251 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2252 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2253
2254 // a u+ b overflows high iff a u> ~b.
2255 if (Min.ugt(RHS: ~OtherMin))
2256 return OverflowResult::AlwaysOverflowsHigh;
2257 if (Max.ugt(RHS: ~OtherMax))
2258 return OverflowResult::MayOverflow;
2259 return OverflowResult::NeverOverflows;
2260}
2261
2262ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
2263 const ConstantRange &Other) const {
2264 if (isEmptySet() || Other.isEmptySet())
2265 return OverflowResult::MayOverflow;
2266
2267 APInt Min = getSignedMin(), Max = getSignedMax();
2268 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2269
2270 APInt SignedMin = APInt::getSignedMinValue(numBits: getBitWidth());
2271 APInt SignedMax = APInt::getSignedMaxValue(numBits: getBitWidth());
2272
2273 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
2274 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
2275 if (Min.isNonNegative() && OtherMin.isNonNegative() &&
2276 Min.sgt(RHS: SignedMax - OtherMin))
2277 return OverflowResult::AlwaysOverflowsHigh;
2278 if (Max.isNegative() && OtherMax.isNegative() &&
2279 Max.slt(RHS: SignedMin - OtherMax))
2280 return OverflowResult::AlwaysOverflowsLow;
2281
2282 if (Max.isNonNegative() && OtherMax.isNonNegative() &&
2283 Max.sgt(RHS: SignedMax - OtherMax))
2284 return OverflowResult::MayOverflow;
2285 if (Min.isNegative() && OtherMin.isNegative() &&
2286 Min.slt(RHS: SignedMin - OtherMin))
2287 return OverflowResult::MayOverflow;
2288
2289 return OverflowResult::NeverOverflows;
2290}
2291
2292ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
2293 const ConstantRange &Other) const {
2294 if (isEmptySet() || Other.isEmptySet())
2295 return OverflowResult::MayOverflow;
2296
2297 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2298 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2299
2300 // a u- b overflows low iff a u< b.
2301 if (Max.ult(RHS: OtherMin))
2302 return OverflowResult::AlwaysOverflowsLow;
2303 if (Min.ult(RHS: OtherMax))
2304 return OverflowResult::MayOverflow;
2305 return OverflowResult::NeverOverflows;
2306}
2307
2308ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
2309 const ConstantRange &Other) const {
2310 if (isEmptySet() || Other.isEmptySet())
2311 return OverflowResult::MayOverflow;
2312
2313 APInt Min = getSignedMin(), Max = getSignedMax();
2314 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2315
2316 APInt SignedMin = APInt::getSignedMinValue(numBits: getBitWidth());
2317 APInt SignedMax = APInt::getSignedMaxValue(numBits: getBitWidth());
2318
2319 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
2320 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
2321 if (Min.isNonNegative() && OtherMax.isNegative() &&
2322 Min.sgt(RHS: SignedMax + OtherMax))
2323 return OverflowResult::AlwaysOverflowsHigh;
2324 if (Max.isNegative() && OtherMin.isNonNegative() &&
2325 Max.slt(RHS: SignedMin + OtherMin))
2326 return OverflowResult::AlwaysOverflowsLow;
2327
2328 if (Max.isNonNegative() && OtherMin.isNegative() &&
2329 Max.sgt(RHS: SignedMax + OtherMin))
2330 return OverflowResult::MayOverflow;
2331 if (Min.isNegative() && OtherMax.isNonNegative() &&
2332 Min.slt(RHS: SignedMin + OtherMax))
2333 return OverflowResult::MayOverflow;
2334
2335 return OverflowResult::NeverOverflows;
2336}
2337
2338ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
2339 const ConstantRange &Other) const {
2340 if (isEmptySet() || Other.isEmptySet())
2341 return OverflowResult::MayOverflow;
2342
2343 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2344 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2345 bool Overflow;
2346
2347 (void) Min.umul_ov(RHS: OtherMin, Overflow);
2348 if (Overflow)
2349 return OverflowResult::AlwaysOverflowsHigh;
2350
2351 (void) Max.umul_ov(RHS: OtherMax, Overflow);
2352 if (Overflow)
2353 return OverflowResult::MayOverflow;
2354
2355 return OverflowResult::NeverOverflows;
2356}
2357
2358void ConstantRange::print(raw_ostream &OS) const {
2359 if (isFullSet())
2360 OS << "full-set";
2361 else if (isEmptySet())
2362 OS << "empty-set";
2363 else
2364 OS << "[" << Lower << "," << Upper << ")";
2365}
2366
2367#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2368LLVM_DUMP_METHOD void ConstantRange::dump() const {
2369 print(dbgs());
2370}
2371#endif
2372
2373ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
2374 const unsigned NumRanges = Ranges.getNumOperands() / 2;
2375 assert(NumRanges >= 1 && "Must have at least one range!");
2376 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
2377
2378 auto *FirstLow = mdconst::extract<ConstantInt>(MD: Ranges.getOperand(I: 0));
2379 auto *FirstHigh = mdconst::extract<ConstantInt>(MD: Ranges.getOperand(I: 1));
2380
2381 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
2382
2383 for (unsigned i = 1; i < NumRanges; ++i) {
2384 auto *Low = mdconst::extract<ConstantInt>(MD: Ranges.getOperand(I: 2 * i + 0));
2385 auto *High = mdconst::extract<ConstantInt>(MD: Ranges.getOperand(I: 2 * i + 1));
2386
2387 // Note: unionWith will potentially create a range that contains values not
2388 // contained in any of the original N ranges.
2389 CR = CR.unionWith(CR: ConstantRange(Low->getValue(), High->getValue()));
2390 }
2391
2392 return CR;
2393}
2394