clang 24.0.0git
RangeConstraintManager.cpp
Go to the documentation of this file.
1//== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
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 defines RangeConstraintManager, a class that tracks simple
10// equality and inequality constraints on symbolic values of ProgramState.
11//
12//===----------------------------------------------------------------------===//
13
20#include "llvm/ADT/FoldingSet.h"
21#include "llvm/ADT/ImmutableSet.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/raw_ostream.h"
27#include <algorithm>
28#include <iterator>
29#include <optional>
30
31using namespace clang;
32using namespace ento;
33
34// This class can be extended with other tables which will help to reason
35// about ranges more precisely.
37 static_assert(BO_LT < BO_GT && BO_GT < BO_LE && BO_LE < BO_GE &&
38 BO_GE < BO_EQ && BO_EQ < BO_NE,
39 "This class relies on operators order. Rework it otherwise.");
40
41public:
47
48private:
49 // CmpOpTable holds states which represent the corresponding range for
50 // branching an exploded graph. We can reason about the branch if there is
51 // a previously known fact of the existence of a comparison expression with
52 // operands used in the current expression.
53 // E.g. assuming (x < y) is true that means (x != y) is surely true.
54 // if (x previous_operation y) // < | != | >
55 // if (x operation y) // != | > | <
56 // tristate // True | Unknown | False
57 //
58 // CmpOpTable represents next:
59 // __|< |> |<=|>=|==|!=|UnknownX2|
60 // < |1 |0 |* |0 |0 |* |1 |
61 // > |0 |1 |0 |* |0 |* |1 |
62 // <=|1 |0 |1 |* |1 |* |0 |
63 // >=|0 |1 |* |1 |1 |* |0 |
64 // ==|0 |0 |* |* |1 |0 |1 |
65 // !=|1 |1 |* |* |0 |1 |0 |
66 //
67 // Columns stands for a previous operator.
68 // Rows stands for a current operator.
69 // Each row has exactly two `Unknown` cases.
70 // UnknownX2 means that both `Unknown` previous operators are met in code,
71 // and there is a special column for that, for example:
72 // if (x >= y)
73 // if (x != y)
74 // if (x <= y)
75 // False only
76 static constexpr size_t CmpOpCount = BO_NE - BO_LT + 1;
77 const TriStateKind CmpOpTable[CmpOpCount][CmpOpCount + 1] = {
78 // < > <= >= == != UnknownX2
81 {True, False, True, Unknown, True, Unknown, False}, // <=
82 {False, True, Unknown, True, True, Unknown, False}, // >=
83 {False, False, Unknown, Unknown, True, False, True}, // ==
84 {True, True, Unknown, Unknown, False, True, False}, // !=
85 };
86
87 static size_t getIndexFromOp(BinaryOperatorKind OP) {
88 return static_cast<size_t>(OP - BO_LT);
89 }
90
91public:
92 constexpr size_t getCmpOpCount() const { return CmpOpCount; }
93
94 static BinaryOperatorKind getOpFromIndex(size_t Index) {
95 return static_cast<BinaryOperatorKind>(Index + BO_LT);
96 }
97
99 BinaryOperatorKind QueriedOP) const {
100 return CmpOpTable[getIndexFromOp(CurrentOP)][getIndexFromOp(QueriedOP)];
101 }
102
104 return CmpOpTable[getIndexFromOp(CurrentOP)][CmpOpCount];
105 }
106};
107
108//===----------------------------------------------------------------------===//
109// RangeSet implementation
110//===----------------------------------------------------------------------===//
111
112const RangeSet::ContainerType RangeSet::Factory::EmptySet{};
113
115 ContainerType Result;
116 Result.reserve(LHS.size() + RHS.size());
117 std::merge(LHS.begin(), LHS.end(), RHS.begin(), RHS.end(),
118 std::back_inserter(Result));
119 return makePersistent(std::move(Result));
120}
121
123 ContainerType Result;
124 Result.reserve(Original.size() + 1);
125
126 const_iterator Lower = llvm::lower_bound(Original, Element);
127 Result.insert(Result.end(), Original.begin(), Lower);
128 Result.push_back(Element);
129 Result.insert(Result.end(), Lower, Original.end());
130
131 return makePersistent(std::move(Result));
132}
133
134RangeSet RangeSet::Factory::add(RangeSet Original, const llvm::APSInt &Point) {
135 return add(Original, Range(Point));
136}
137
139 ContainerType Result = unite(*LHS.Impl, *RHS.Impl);
140 return makePersistent(std::move(Result));
141}
142
144 ContainerType Result;
145 Result.push_back(R);
146 Result = unite(*Original.Impl, Result);
147 return makePersistent(std::move(Result));
148}
149
150RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt Point) {
151 return unite(Original, Range(ValueFactory.getValue(Point)));
152}
153
154RangeSet RangeSet::Factory::unite(RangeSet Original, llvm::APSInt From,
155 llvm::APSInt To) {
156 return unite(Original,
157 Range(ValueFactory.getValue(From), ValueFactory.getValue(To)));
158}
159
160template <typename T>
161static void swapIterators(T &First, T &FirstEnd, T &Second, T &SecondEnd) {
162 std::swap(First, Second);
163 std::swap(FirstEnd, SecondEnd);
164}
165
166RangeSet::ContainerType RangeSet::Factory::unite(const ContainerType &LHS,
167 const ContainerType &RHS) {
168 if (LHS.empty())
169 return RHS;
170 if (RHS.empty())
171 return LHS;
172
173 using llvm::APSInt;
174 using iterator = ContainerType::const_iterator;
175
176 iterator First = LHS.begin();
177 iterator FirstEnd = LHS.end();
178 iterator Second = RHS.begin();
179 iterator SecondEnd = RHS.end();
180 APSIntType Ty = APSIntType(First->From());
181 const APSInt Min = Ty.getMinValue();
182
183 // Handle a corner case first when both range sets start from MIN.
184 // This helps to avoid complicated conditions below. Specifically, this
185 // particular check for `MIN` is not needed in the loop below every time
186 // when we do `Second->From() - One` operation.
187 if (Min == First->From() && Min == Second->From()) {
188 if (First->To() > Second->To()) {
189 // [ First ]--->
190 // [ Second ]----->
191 // MIN^
192 // The Second range is entirely inside the First one.
193
194 // Check if Second is the last in its RangeSet.
195 if (++Second == SecondEnd)
196 // [ First ]--[ First + 1 ]--->
197 // [ Second ]--------------------->
198 // MIN^
199 // The Union is equal to First's RangeSet.
200 return LHS;
201 } else {
202 // case 1: [ First ]----->
203 // case 2: [ First ]--->
204 // [ Second ]--->
205 // MIN^
206 // The First range is entirely inside or equal to the Second one.
207
208 // Check if First is the last in its RangeSet.
209 if (++First == FirstEnd)
210 // [ First ]----------------------->
211 // [ Second ]--[ Second + 1 ]---->
212 // MIN^
213 // The Union is equal to Second's RangeSet.
214 return RHS;
215 }
216 }
217
218 const APSInt One = Ty.getValue(1);
219 ContainerType Result;
220
221 // This is called when there are no ranges left in one of the ranges.
222 // Append the rest of the ranges from another range set to the Result
223 // and return with that.
224 const auto AppendTheRest = [&Result](iterator I, iterator E) {
225 Result.append(I, E);
226 return Result;
227 };
228
229 while (true) {
230 // We want to keep the following invariant at all times:
231 // ---[ First ------>
232 // -----[ Second --->
233 if (First->From() > Second->From())
234 swapIterators(First, FirstEnd, Second, SecondEnd);
235
236 // The Union definitely starts with First->From().
237 // ----------[ First ------>
238 // ------------[ Second --->
239 // ----------[ Union ------>
240 // UnionStart^
241 const llvm::APSInt &UnionStart = First->From();
242
243 // Loop where the invariant holds.
244 while (true) {
245 // Skip all enclosed ranges.
246 // ---[ First ]--->
247 // -----[ Second ]--[ Second + 1 ]--[ Second + N ]----->
248 while (First->To() >= Second->To()) {
249 // Check if Second is the last in its RangeSet.
250 if (++Second == SecondEnd) {
251 // Append the Union.
252 // ---[ Union ]--->
253 // -----[ Second ]----->
254 // --------[ First ]--->
255 // UnionEnd^
256 Result.emplace_back(UnionStart, First->To());
257 // ---[ Union ]----------------->
258 // --------------[ First + 1]--->
259 // Append all remaining ranges from the First's RangeSet.
260 return AppendTheRest(++First, FirstEnd);
261 }
262 }
263
264 // Check if First and Second are disjoint. It means that we find
265 // the end of the Union. Exit the loop and append the Union.
266 // ---[ First ]=------------->
267 // ------------=[ Second ]--->
268 // ----MinusOne^
269 if (First->To() < Second->From() - One)
270 break;
271
272 // First is entirely inside the Union. Go next.
273 // ---[ Union ----------->
274 // ---- [ First ]-------->
275 // -------[ Second ]----->
276 // Check if First is the last in its RangeSet.
277 if (++First == FirstEnd) {
278 // Append the Union.
279 // ---[ Union ]--->
280 // -----[ First ]------->
281 // --------[ Second ]--->
282 // UnionEnd^
283 Result.emplace_back(UnionStart, Second->To());
284 // ---[ Union ]------------------>
285 // --------------[ Second + 1]--->
286 // Append all remaining ranges from the Second's RangeSet.
287 return AppendTheRest(++Second, SecondEnd);
288 }
289
290 // We know that we are at one of the two cases:
291 // case 1: --[ First ]--------->
292 // case 2: ----[ First ]------->
293 // --------[ Second ]---------->
294 // In both cases First starts after Second->From().
295 // Make sure that the loop invariant holds.
296 swapIterators(First, FirstEnd, Second, SecondEnd);
297 }
298
299 // Here First and Second are disjoint.
300 // Append the Union.
301 // ---[ Union ]--------------->
302 // -----------------[ Second ]--->
303 // ------[ First ]--------------->
304 // UnionEnd^
305 Result.emplace_back(UnionStart, First->To());
306
307 // Check if First is the last in its RangeSet.
308 if (++First == FirstEnd)
309 // ---[ Union ]--------------->
310 // --------------[ Second ]--->
311 // Append all remaining ranges from the Second's RangeSet.
312 return AppendTheRest(Second, SecondEnd);
313 }
314
315 llvm_unreachable("Normally, we should not reach here");
316}
317
319 ContainerType Result;
320 Result.push_back(From);
321 return makePersistent(std::move(Result));
322}
323
325 for (const auto &[CachedTy, Set] : FullRangeSets)
326 if (CachedTy == Ty)
327 return Set;
328
330 getRangeSet(ValueFactory.getMinValue(Ty), ValueFactory.getMaxValue(Ty));
331 FullRangeSets.emplace_back(Ty, Result.Impl);
332 return Result;
333}
334
335RangeSet RangeSet::Factory::makePersistent(ContainerType &&From) {
336 llvm::FoldingSetNodeID ID;
337 llvm::FoldingSetInsertToken InsertToken;
338
339 From.Profile(ID);
340 ContainerType *Result = Cache.lookup(ID, InsertToken);
341
342 if (!Result) {
343 // It is cheaper to fully construct the resulting range on stack
344 // and move it to the freshly allocated buffer if we don't have
345 // a set like this already.
346 Result = construct(std::move(From));
347 Cache.insert(Result, InsertToken);
348 }
349
350 return Result;
351}
352
353RangeSet::ContainerType *RangeSet::Factory::construct(ContainerType &&From) {
354 void *Buffer = Arena.Allocate();
355 return new (Buffer) ContainerType(std::move(From));
356}
357
358const llvm::APSInt &RangeSet::getMinValue() const {
359 assert(!isEmpty());
360 return begin()->From();
361}
362
363const llvm::APSInt &RangeSet::getMaxValue() const {
364 assert(!isEmpty());
365 return std::prev(end())->To();
366}
367
369 assert(!isEmpty());
370 return begin()->From().isUnsigned();
371}
372
374 assert(!isEmpty());
375 return begin()->From().getBitWidth();
376}
377
379 assert(!isEmpty());
380 return APSIntType(begin()->From());
381}
382
383bool RangeSet::containsImpl(llvm::APSInt &Point) const {
384 if (isEmpty() || !pin(Point))
385 return false;
386
387 Range Dummy(Point);
388 const_iterator It = llvm::upper_bound(*this, Dummy);
389 if (It == begin())
390 return false;
391
392 return std::prev(It)->Includes(Point);
393}
394
395bool RangeSet::pin(llvm::APSInt &Point) const {
397 if (Type.testInRange(Point, true) != APSIntType::RTR_Within)
398 return false;
399
400 Type.apply(Point);
401 return true;
402}
403
404bool RangeSet::pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
405 // This function has nine cases, the cartesian product of range-testing
406 // both the upper and lower bounds against the symbol's type.
407 // Each case requires a different pinning operation.
408 // The function returns false if the described range is entirely outside
409 // the range of values for the associated symbol.
411 APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
412 APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
413
414 switch (LowerTest) {
416 switch (UpperTest) {
418 // The entire range is outside the symbol's set of possible values.
419 // If this is a conventionally-ordered range, the state is infeasible.
420 if (Lower <= Upper)
421 return false;
422
423 // However, if the range wraps around, it spans all possible values.
424 Lower = Type.getMinValue();
425 Upper = Type.getMaxValue();
426 break;
428 // The range starts below what's possible but ends within it. Pin.
429 Lower = Type.getMinValue();
430 Type.apply(Upper);
431 break;
433 // The range spans all possible values for the symbol. Pin.
434 Lower = Type.getMinValue();
435 Upper = Type.getMaxValue();
436 break;
437 }
438 break;
440 switch (UpperTest) {
442 // The range wraps around, but all lower values are not possible.
443 Type.apply(Lower);
444 Upper = Type.getMaxValue();
445 break;
447 // The range may or may not wrap around, but both limits are valid.
448 Type.apply(Lower);
449 Type.apply(Upper);
450 break;
452 // The range starts within what's possible but ends above it. Pin.
453 Type.apply(Lower);
454 Upper = Type.getMaxValue();
455 break;
456 }
457 break;
459 switch (UpperTest) {
461 // The range wraps but is outside the symbol's set of possible values.
462 return false;
464 // The range starts above what's possible but ends within it (wrap).
465 Lower = Type.getMinValue();
466 Type.apply(Upper);
467 break;
469 // The entire range is outside the symbol's set of possible values.
470 // If this is a conventionally-ordered range, the state is infeasible.
471 if (Lower <= Upper)
472 return false;
473
474 // However, if the range wraps around, it spans all possible values.
475 Lower = Type.getMinValue();
476 Upper = Type.getMaxValue();
477 break;
478 }
479 break;
480 }
481
482 return true;
483}
484
486 llvm::APSInt Upper) {
487 if (What.isEmpty() || !What.pin(Lower, Upper))
488 return getEmptySet();
489
490 ContainerType DummyContainer;
491
492 if (Lower <= Upper) {
493 // [Lower, Upper] is a regular range.
494 //
495 // Shortcut: check that there is even a possibility of the intersection
496 // by checking the two following situations:
497 //
498 // <---[ What ]---[------]------>
499 // Lower Upper
500 // -or-
501 // <----[------]----[ What ]---->
502 // Lower Upper
503 if (What.getMaxValue() < Lower || Upper < What.getMinValue())
504 return getEmptySet();
505
506 DummyContainer.push_back(
507 Range(ValueFactory.getValue(Lower), ValueFactory.getValue(Upper)));
508 } else {
509 // [Lower, Upper] is an inverted range, i.e. [MIN, Upper] U [Lower, MAX]
510 //
511 // Shortcut: check that there is even a possibility of the intersection
512 // by checking the following situation:
513 //
514 // <------]---[ What ]---[------>
515 // Upper Lower
516 if (What.getMaxValue() < Lower && Upper < What.getMinValue())
517 return getEmptySet();
518
519 DummyContainer.push_back(
520 Range(ValueFactory.getMinValue(Upper), ValueFactory.getValue(Upper)));
521 DummyContainer.push_back(
522 Range(ValueFactory.getValue(Lower), ValueFactory.getMaxValue(Lower)));
523 }
524
525 return intersect(*What.Impl, DummyContainer);
526}
527
528RangeSet RangeSet::Factory::intersect(const RangeSet::ContainerType &LHS,
529 const RangeSet::ContainerType &RHS) {
530 ContainerType Result;
531 Result.reserve(std::max(LHS.size(), RHS.size()));
532
533 const_iterator First = LHS.begin(), Second = RHS.begin(),
534 FirstEnd = LHS.end(), SecondEnd = RHS.end();
535
536 // If we ran out of ranges in one set, but not in the other,
537 // it means that those elements are definitely not in the
538 // intersection.
539 while (First != FirstEnd && Second != SecondEnd) {
540 // We want to keep the following invariant at all times:
541 //
542 // ----[ First ---------------------->
543 // --------[ Second ----------------->
544 if (Second->From() < First->From())
545 swapIterators(First, FirstEnd, Second, SecondEnd);
546
547 // Loop where the invariant holds:
548 do {
549 // Check for the following situation:
550 //
551 // ----[ First ]--------------------->
552 // ---------------[ Second ]--------->
553 //
554 // which means that...
555 if (Second->From() > First->To()) {
556 // ...First is not in the intersection.
557 //
558 // We should move on to the next range after First and break out of the
559 // loop because the invariant might not be true.
560 ++First;
561 break;
562 }
563
564 // We have a guaranteed intersection at this point!
565 // And this is the current situation:
566 //
567 // ----[ First ]----------------->
568 // -------[ Second ------------------>
569 //
570 // Additionally, it definitely starts with Second->From().
571 const llvm::APSInt &IntersectionStart = Second->From();
572
573 // It is important to know which of the two ranges' ends
574 // is greater. That "longer" range might have some other
575 // intersections, while the "shorter" range might not.
576 if (Second->To() > First->To()) {
577 // Here we make a decision to keep First as the "longer"
578 // range.
579 swapIterators(First, FirstEnd, Second, SecondEnd);
580 }
581
582 // At this point, we have the following situation:
583 //
584 // ---- First ]-------------------->
585 // ---- Second ]--[ Second+1 ---------->
586 //
587 // We don't know the relationship between First->From and
588 // Second->From and we don't know whether Second+1 intersects
589 // with First.
590 //
591 // However, we know that [IntersectionStart, Second->To] is
592 // a part of the intersection...
593 Result.push_back(Range(IntersectionStart, Second->To()));
594 ++Second;
595 // ...and that the invariant will hold for a valid Second+1
596 // because First->From <= Second->To < (Second+1)->From.
597 } while (Second != SecondEnd);
598 }
599
600 if (Result.empty())
601 return getEmptySet();
602
603 return makePersistent(std::move(Result));
604}
605
607 // Shortcut: let's see if the intersection is even possible.
608 if (LHS.isEmpty() || RHS.isEmpty() || LHS.getMaxValue() < RHS.getMinValue() ||
609 RHS.getMaxValue() < LHS.getMinValue())
610 return getEmptySet();
611
612 // Shortcut: if one set is a single range covering the other set, the result
613 // is the other set.
614 if (RHS.size() == 1 && RHS.getMinValue() <= LHS.getMinValue() &&
615 LHS.getMaxValue() <= RHS.getMaxValue())
616 return LHS;
617 if (LHS.size() == 1 && LHS.getMinValue() <= RHS.getMinValue() &&
618 RHS.getMaxValue() <= LHS.getMaxValue())
619 return RHS;
620
621 return intersect(*LHS.Impl, *RHS.Impl);
622}
623
625 if (LHS.containsImpl(Point))
626 return getRangeSet(ValueFactory.getValue(Point));
627
628 return getEmptySet();
629}
630
632 if (What.isEmpty())
633 return getEmptySet();
634
635 const llvm::APSInt SampleValue = What.getMinValue();
636 const llvm::APSInt &MIN = ValueFactory.getMinValue(SampleValue);
637 const llvm::APSInt &MAX = ValueFactory.getMaxValue(SampleValue);
638
639 ContainerType Result;
640 Result.reserve(What.size() + (SampleValue == MIN));
641
642 // Handle a special case for MIN value.
643 const_iterator It = What.begin();
644 const_iterator End = What.end();
645
646 const llvm::APSInt &From = It->From();
647 const llvm::APSInt &To = It->To();
648
649 if (From == MIN) {
650 // If the range [From, To] is [MIN, MAX], then result is also [MIN, MAX].
651 if (To == MAX) {
652 return What;
653 }
654
655 const_iterator Last = std::prev(End);
656
657 // Try to find and unite the following ranges:
658 // [MIN, MIN] & [MIN + 1, N] => [MIN, N].
659 if (Last->To() == MAX) {
660 // It means that in the original range we have ranges
661 // [MIN, A], ... , [B, MAX]
662 // And the result should be [MIN, -B], ..., [-A, MAX]
663 Result.emplace_back(MIN, ValueFactory.getValue(-Last->From()));
664 // We already negated Last, so we can skip it.
665 End = Last;
666 } else {
667 // Add a separate range for the lowest value.
668 Result.emplace_back(MIN, MIN);
669 }
670
671 // Skip adding the second range in case when [From, To] are [MIN, MIN].
672 if (To != MIN) {
673 Result.emplace_back(ValueFactory.getValue(-To), MAX);
674 }
675
676 // Skip the first range in the loop.
677 ++It;
678 }
679
680 // Negate all other ranges.
681 for (; It != End; ++It) {
682 // Negate int values.
683 const llvm::APSInt &NewFrom = ValueFactory.getValue(-It->To());
684 const llvm::APSInt &NewTo = ValueFactory.getValue(-It->From());
685
686 // Add a negated range.
687 Result.emplace_back(NewFrom, NewTo);
688 }
689
690 llvm::sort(Result);
691 return makePersistent(std::move(Result));
692}
693
694// Convert range set to the given integral type using truncation and promotion.
695// This works similar to APSIntType::apply function but for the range set.
697 // Set is empty or NOOP (aka cast to the same type).
698 if (What.isEmpty() || What.getAPSIntType() == Ty)
699 return What;
700
701 const bool IsConversion = What.isUnsigned() != Ty.isUnsigned();
702 const bool IsTruncation = What.getBitWidth() > Ty.getBitWidth();
703 const bool IsPromotion = What.getBitWidth() < Ty.getBitWidth();
704
705 if (IsTruncation)
706 return makePersistent(truncateTo(What, Ty));
707
708 // Here we handle 2 cases:
709 // - IsConversion && !IsPromotion.
710 // In this case we handle changing a sign with same bitwidth: char -> uchar,
711 // uint -> int. Here we convert negatives to positives and positives which
712 // is out of range to negatives. We use convertTo function for that.
713 // - IsConversion && IsPromotion && !What.isUnsigned().
714 // In this case we handle changing a sign from signeds to unsigneds with
715 // higher bitwidth: char -> uint, int-> uint64. The point is that we also
716 // need convert negatives to positives and use convertTo function as well.
717 // For example, we don't need such a convertion when converting unsigned to
718 // signed with higher bitwidth, because all the values of unsigned is valid
719 // for the such signed.
720 if (IsConversion && (!IsPromotion || !What.isUnsigned()))
721 return makePersistent(convertTo(What, Ty));
722
723 assert(IsPromotion && "Only promotion operation from unsigneds left.");
724 return makePersistent(promoteTo(What, Ty));
725}
726
728 assert(T->isIntegralOrEnumerationType() && "T shall be an integral type.");
729 return castTo(What, ValueFactory.getAPSIntType(T));
730}
731
732RangeSet::ContainerType RangeSet::Factory::truncateTo(RangeSet What,
733 APSIntType Ty) {
734 using llvm::APInt;
735 using llvm::APSInt;
736 ContainerType Result;
737 ContainerType Dummy;
738 // CastRangeSize is an amount of all possible values of cast type.
739 // Example: `char` has 256 values; `short` has 65536 values.
740 // But in fact we use `amount of values` - 1, because
741 // we can't keep `amount of values of UINT64` inside uint64_t.
742 // E.g. 256 is an amount of all possible values of `char` and we can't keep
743 // it inside `char`.
744 // And it's OK, it's enough to do correct calculations.
745 uint64_t CastRangeSize = APInt::getMaxValue(Ty.getBitWidth()).getZExtValue();
746 for (const Range &R : What) {
747 // Get bounds of the given range.
748 APSInt FromInt = R.From();
749 APSInt ToInt = R.To();
750 // CurrentRangeSize is an amount of all possible values of the current
751 // range minus one.
752 uint64_t CurrentRangeSize = (ToInt - FromInt).getZExtValue();
753 // This is an optimization for a specific case when this Range covers
754 // the whole range of the target type.
755 Dummy.clear();
756 if (CurrentRangeSize >= CastRangeSize) {
757 Dummy.emplace_back(ValueFactory.getMinValue(Ty),
758 ValueFactory.getMaxValue(Ty));
759 Result = std::move(Dummy);
760 break;
761 }
762 // Cast the bounds.
763 Ty.apply(FromInt);
764 Ty.apply(ToInt);
765 const APSInt &PersistentFrom = ValueFactory.getValue(FromInt);
766 const APSInt &PersistentTo = ValueFactory.getValue(ToInt);
767 if (FromInt > ToInt) {
768 Dummy.emplace_back(ValueFactory.getMinValue(Ty), PersistentTo);
769 Dummy.emplace_back(PersistentFrom, ValueFactory.getMaxValue(Ty));
770 } else
771 Dummy.emplace_back(PersistentFrom, PersistentTo);
772 // Every range retrieved after truncation potentialy has garbage values.
773 // So, we have to unite every next range with the previouses.
774 Result = unite(Result, Dummy);
775 }
776
777 return Result;
778}
779
780// Divide the convertion into two phases (presented as loops here).
781// First phase(loop) works when casted values go in ascending order.
782// E.g. char{1,3,5,127} -> uint{1,3,5,127}
783// Interrupt the first phase and go to second one when casted values start
784// go in descending order. That means that we crossed over the middle of
785// the type value set (aka 0 for signeds and MAX/2+1 for unsigneds).
786// For instance:
787// 1: uchar{1,3,5,128,255} -> char{1,3,5,-128,-1}
788// Here we put {1,3,5} to one array and {-128, -1} to another
789// 2: char{-128,-127,-1,0,1,2} -> uchar{128,129,255,0,1,3}
790// Here we put {128,129,255} to one array and {0,1,3} to another.
791// After that we unite both arrays.
792// NOTE: We don't just concatenate the arrays, because they may have
793// adjacent ranges, e.g.:
794// 1: char(-128, 127) -> uchar -> arr1(128, 255), arr2(0, 127) ->
795// unite -> uchar(0, 255)
796// 2: uchar(0, 1)U(254, 255) -> char -> arr1(0, 1), arr2(-2, -1) ->
797// unite -> uchar(-2, 1)
798RangeSet::ContainerType RangeSet::Factory::convertTo(RangeSet What,
799 APSIntType Ty) {
800 using llvm::APInt;
801 using llvm::APSInt;
802 using Bounds = std::pair<const APSInt &, const APSInt &>;
803 ContainerType AscendArray;
804 ContainerType DescendArray;
805 auto CastRange = [Ty, &VF = ValueFactory](const Range &R) -> Bounds {
806 // Get bounds of the given range.
807 APSInt FromInt = R.From();
808 APSInt ToInt = R.To();
809 // Cast the bounds.
810 Ty.apply(FromInt);
811 Ty.apply(ToInt);
812 return {VF.getValue(FromInt), VF.getValue(ToInt)};
813 };
814 // Phase 1. Fill the first array.
815 APSInt LastConvertedInt = Ty.getMinValue();
816 const auto *It = What.begin();
817 const auto *E = What.end();
818 while (It != E) {
819 Bounds NewBounds = CastRange(*(It++));
820 // If values stop going acsending order, go to the second phase(loop).
821 if (NewBounds.first < LastConvertedInt) {
822 DescendArray.emplace_back(NewBounds.first, NewBounds.second);
823 break;
824 }
825 // If the range contains a midpoint, then split the range.
826 // E.g. char(-5, 5) -> uchar(251, 5)
827 // Here we shall add a range (251, 255) to the first array and (0, 5) to the
828 // second one.
829 if (NewBounds.first > NewBounds.second) {
830 DescendArray.emplace_back(ValueFactory.getMinValue(Ty), NewBounds.second);
831 AscendArray.emplace_back(NewBounds.first, ValueFactory.getMaxValue(Ty));
832 } else
833 // Values are going acsending order.
834 AscendArray.emplace_back(NewBounds.first, NewBounds.second);
835 LastConvertedInt = NewBounds.first;
836 }
837 // Phase 2. Fill the second array.
838 while (It != E) {
839 Bounds NewBounds = CastRange(*(It++));
840 DescendArray.emplace_back(NewBounds.first, NewBounds.second);
841 }
842 // Unite both arrays.
843 return unite(AscendArray, DescendArray);
844}
845
846/// Promotion from unsigneds to signeds/unsigneds left.
847RangeSet::ContainerType RangeSet::Factory::promoteTo(RangeSet What,
848 APSIntType Ty) {
849 ContainerType Result;
850 // We definitely know the size of the result set.
851 Result.reserve(What.size());
852
853 // Each unsigned value fits every larger type without any changes,
854 // whether the larger type is signed or unsigned. So just promote and push
855 // back each range one by one.
856 for (const Range &R : What) {
857 // Get bounds of the given range.
858 llvm::APSInt FromInt = R.From();
859 llvm::APSInt ToInt = R.To();
860 // Cast the bounds.
861 Ty.apply(FromInt);
862 Ty.apply(ToInt);
863 Result.emplace_back(ValueFactory.getValue(FromInt),
864 ValueFactory.getValue(ToInt));
865 }
866 return Result;
867}
868
870 const llvm::APSInt &Point) {
871 if (!From.contains(Point))
872 return From;
873
874 llvm::APSInt Upper = Point;
875 llvm::APSInt Lower = Point;
876
877 ++Upper;
878 --Lower;
879
880 // Notice that the lower bound is greater than the upper bound.
881 return intersect(From, Upper, Lower);
882}
883
884LLVM_DUMP_METHOD void Range::dump(raw_ostream &OS) const {
885 OS << '[' << toString(From(), 10) << ", " << toString(To(), 10) << ']';
886}
887LLVM_DUMP_METHOD void Range::dump() const { dump(llvm::errs()); }
888
889LLVM_DUMP_METHOD void RangeSet::dump(raw_ostream &OS) const {
890 OS << "{ ";
891 llvm::interleaveComma(*this, OS, [&OS](const Range &R) { R.dump(OS); });
892 OS << " }";
893}
894LLVM_DUMP_METHOD void RangeSet::dump() const { dump(llvm::errs()); }
895
897
898namespace {
899class EquivalenceClass;
900} // end anonymous namespace
901
902REGISTER_MAP_WITH_PROGRAMSTATE(ClassMap, SymbolRef, EquivalenceClass)
903REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
904REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
905
906REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
907REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
908
909namespace {
910/// This class encapsulates a set of symbols equal to each other.
911///
912/// The main idea of the approach requiring such classes is in narrowing
913/// and sharing constraints between symbols within the class. Also we can
914/// conclude that there is no practical need in storing constraints for
915/// every member of the class separately.
916///
917/// Main terminology:
918///
919/// * "Equivalence class" is an object of this class, which can be efficiently
920/// compared to other classes. It represents the whole class without
921/// storing the actual in it. The members of the class however can be
922/// retrieved from the state.
923///
924/// * "Class members" are the symbols corresponding to the class. This means
925/// that A == B for every member symbols A and B from the class. Members of
926/// each class are stored in the state.
927///
928/// * "Trivial class" is a class that has and ever had only one same symbol.
929///
930/// * "Merge operation" merges two classes into one. It is the main operation
931/// to produce non-trivial classes.
932/// If, at some point, we can assume that two symbols from two distinct
933/// classes are equal, we can merge these classes.
934class EquivalenceClass {
935public:
936 /// Find equivalence class for the given symbol in the given state.
937 [[nodiscard]] static inline EquivalenceClass find(ProgramStateRef State,
938 SymbolRef Sym);
939
940 /// Merge classes for the given symbols and return a new state.
941 [[nodiscard]] static inline ProgramStateRef merge(RangeSet::Factory &F,
942 ProgramStateRef State,
944 SymbolRef Second);
945 // Merge this class with the given class and return a new state.
946 [[nodiscard]] inline ProgramStateRef
947 merge(RangeSet::Factory &F, ProgramStateRef State, EquivalenceClass Other);
948
949 /// Return a set of class members for the given state.
950 [[nodiscard]] inline SymbolSet getClassMembers(ProgramStateRef State) const;
951
952 /// Return true if the current class is trivial in the given state.
953 /// A class is trivial if and only if there is not any member relations stored
954 /// to it in State/ClassMembers.
955 /// An equivalence class with one member might seem as it does not hold any
956 /// meaningful information, i.e. that is a tautology. However, during the
957 /// removal of dead symbols we do not remove classes with one member for
958 /// resource and performance reasons. Consequently, a class with one member is
959 /// not necessarily trivial. It could happen that we have a class with two
960 /// members and then during the removal of dead symbols we remove one of its
961 /// members. In this case, the class is still non-trivial (it still has the
962 /// mappings in ClassMembers), even though it has only one member.
963 [[nodiscard]] inline bool isTrivial(ProgramStateRef State) const;
964
965 /// Return true if the current class is trivial and its only member is dead.
966 [[nodiscard]] inline bool isTriviallyDead(ProgramStateRef State,
967 SymbolReaper &Reaper) const;
968
969 [[nodiscard]] static inline ProgramStateRef
970 markDisequal(RangeSet::Factory &F, ProgramStateRef State, SymbolRef First,
971 SymbolRef Second);
972 [[nodiscard]] static inline ProgramStateRef
973 markDisequal(RangeSet::Factory &F, ProgramStateRef State,
974 EquivalenceClass First, EquivalenceClass Second);
975 [[nodiscard]] inline ProgramStateRef
976 markDisequal(RangeSet::Factory &F, ProgramStateRef State,
977 EquivalenceClass Other) const;
978 [[nodiscard]] static inline ClassSet getDisequalClasses(ProgramStateRef State,
979 SymbolRef Sym);
980 [[nodiscard]] inline ClassSet getDisequalClasses(ProgramStateRef State) const;
981 [[nodiscard]] inline ClassSet
982 getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const;
983
984 [[nodiscard]] static inline std::optional<bool>
985 areEqual(ProgramStateRef State, EquivalenceClass First,
986 EquivalenceClass Second);
987 [[nodiscard]] static inline std::optional<bool>
988 areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second);
989
990 /// Remove one member from the class.
991 [[nodiscard]] ProgramStateRef removeMember(ProgramStateRef State,
992 const SymbolRef Old);
993
994 /// Iterate over all symbols and try to simplify them.
995 [[nodiscard]] static inline ProgramStateRef simplify(SValBuilder &SVB,
997 ProgramStateRef State,
998 EquivalenceClass Class);
999
1000 void dumpToStream(ProgramStateRef State, raw_ostream &os) const;
1001 LLVM_DUMP_METHOD void dump(ProgramStateRef State) const {
1002 dumpToStream(State, llvm::errs());
1003 }
1004
1005 /// Check equivalence data for consistency.
1006 [[nodiscard]] [[maybe_unused]] static bool
1007 isClassDataConsistent(ProgramStateRef State);
1008
1009 [[nodiscard]] QualType getType() const {
1010 return getRepresentativeSymbol()->getType();
1011 }
1012
1013 EquivalenceClass() = delete;
1014 EquivalenceClass(const EquivalenceClass &) = default;
1015 EquivalenceClass &operator=(const EquivalenceClass &) = delete;
1016 EquivalenceClass(EquivalenceClass &&) = default;
1017 EquivalenceClass &operator=(EquivalenceClass &&) = delete;
1018
1019 bool operator==(const EquivalenceClass &Other) const {
1020 return ID == Other.ID;
1021 }
1022 bool operator<(const EquivalenceClass &Other) const { return ID < Other.ID; }
1023 bool operator!=(const EquivalenceClass &Other) const {
1024 return !operator==(Other);
1025 }
1026
1027 static void Profile(llvm::FoldingSetNodeID &ID, uintptr_t CID) {
1028 ID.AddInteger(CID);
1029 }
1030
1031 void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, this->ID); }
1032
1033private:
1034 /* implicit */ EquivalenceClass(SymbolRef Sym)
1035 : ID(reinterpret_cast<uintptr_t>(Sym)) {}
1036
1037 /// This function is intended to be used ONLY within the class.
1038 /// The fact that ID is a pointer to a symbol is an implementation detail
1039 /// and should stay that way.
1040 /// In the current implementation, we use it to retrieve the only member
1041 /// of the trivial class.
1042 SymbolRef getRepresentativeSymbol() const {
1043 return reinterpret_cast<SymbolRef>(ID);
1044 }
1045 static inline SymbolSet::Factory &getMembersFactory(ProgramStateRef State);
1046
1047 inline ProgramStateRef mergeImpl(RangeSet::Factory &F, ProgramStateRef State,
1048 SymbolSet Members, EquivalenceClass Other,
1049 SymbolSet OtherMembers);
1050
1051 static inline bool
1052 addToDisequalityInfo(DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
1054 EquivalenceClass First, EquivalenceClass Second);
1055
1056 /// This is a unique identifier of the class.
1057 uintptr_t ID;
1058};
1059
1060//===----------------------------------------------------------------------===//
1061// Constraint functions
1062//===----------------------------------------------------------------------===//
1063
1064[[nodiscard]] [[maybe_unused]] bool areFeasible(ConstraintRangeTy Constraints) {
1065 return llvm::none_of(
1066 Constraints,
1067 [](const std::pair<EquivalenceClass, RangeSet> &ClassConstraint) {
1068 return ClassConstraint.second.isEmpty();
1069 });
1070}
1071
1072[[nodiscard]] inline const RangeSet *getConstraint(ProgramStateRef State,
1073 EquivalenceClass Class) {
1074 return State->get<ConstraintRange>(Class);
1075}
1076
1077[[nodiscard]] inline const RangeSet *getConstraint(ProgramStateRef State,
1078 SymbolRef Sym) {
1079 return getConstraint(State, EquivalenceClass::find(State, Sym));
1080}
1081
1082[[nodiscard]] ProgramStateRef setConstraint(ProgramStateRef State,
1083 EquivalenceClass Class,
1084 RangeSet Constraint) {
1085 return State->set<ConstraintRange>(Class, Constraint);
1086}
1087
1088[[nodiscard]] ProgramStateRef setConstraints(ProgramStateRef State,
1089 ConstraintRangeTy Constraints) {
1090 return State->set<ConstraintRange>(Constraints);
1091}
1092
1093//===----------------------------------------------------------------------===//
1094// Equality/diseqiality abstraction
1095//===----------------------------------------------------------------------===//
1096
1097/// A small helper function for detecting symbolic (dis)equality.
1098///
1099/// Equality check can have different forms (like a == b or a - b) and this
1100/// class encapsulates those away if the only thing the user wants to check -
1101/// whether it's equality/diseqiality or not.
1102///
1103/// \returns true if assuming this Sym to be true means equality of operands
1104/// false if it means disequality of operands
1105/// std::nullopt otherwise
1106std::optional<bool> meansEquality(const SymSymExpr *Sym) {
1107 switch (Sym->getOpcode()) {
1108 case BO_Sub:
1109 // This case is: A - B != 0 -> disequality check.
1110 return false;
1111 case BO_EQ:
1112 // This case is: A == B != 0 -> equality check.
1113 return true;
1114 case BO_NE:
1115 // This case is: A != B != 0 -> diseqiality check.
1116 return false;
1117 default:
1118 return std::nullopt;
1119 }
1120}
1121
1122//===----------------------------------------------------------------------===//
1123// Intersection functions
1124//===----------------------------------------------------------------------===//
1125
1126template <class SecondTy, class... RestTy>
1127[[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1128 SecondTy Second, RestTy... Tail);
1129
1130template <class... RangeTy> struct IntersectionTraits;
1131
1132template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
1133 // Found RangeSet, no need to check any further
1134 using Type = RangeSet;
1135};
1136
1137template <> struct IntersectionTraits<> {
1138 // We ran out of types, and we didn't find any RangeSet, so the result should
1139 // be optional.
1140 using Type = std::optional<RangeSet>;
1141};
1142
1143template <class OptionalOrPointer, class... TailTy>
1144struct IntersectionTraits<OptionalOrPointer, TailTy...> {
1145 // If current type is Optional or a raw pointer, we should keep looking.
1146 using Type = typename IntersectionTraits<TailTy...>::Type;
1147};
1148
1149template <class EndTy>
1150[[nodiscard]] inline EndTy intersect(RangeSet::Factory &F, EndTy End) {
1151 // If the list contains only RangeSet or std::optional<RangeSet>, simply
1152 // return that range set.
1153 return End;
1154}
1155
1156[[nodiscard]] [[maybe_unused]] inline std::optional<RangeSet>
1157intersect(RangeSet::Factory &F, const RangeSet *End) {
1158 // This is an extraneous conversion from a raw pointer into
1159 // std::optional<RangeSet>
1160 if (End) {
1161 return *End;
1162 }
1163 return std::nullopt;
1164}
1165
1166template <class... RestTy>
1167[[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1168 RangeSet Second, RestTy... Tail) {
1169 // Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
1170 // of the function and can be sure that the result is RangeSet.
1171 return intersect(F, F.intersect(Head, Second), Tail...);
1172}
1173
1174template <class SecondTy, class... RestTy>
1175[[nodiscard]] inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
1176 SecondTy Second, RestTy... Tail) {
1177 if (Second) {
1178 // Here we call the <RangeSet,RangeSet,...> version of the function...
1179 return intersect(F, Head, *Second, Tail...);
1180 }
1181 // ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
1182 // means that the result is definitely RangeSet.
1183 return intersect(F, Head, Tail...);
1184}
1185
1186/// Main generic intersect function.
1187/// It intersects all of the given range sets. If some of the given arguments
1188/// don't hold a range set (nullptr or std::nullopt), the function will skip
1189/// them.
1190///
1191/// Available representations for the arguments are:
1192/// * RangeSet
1193/// * std::optional<RangeSet>
1194/// * RangeSet *
1195/// Pointer to a RangeSet is automatically assumed to be nullable and will get
1196/// checked as well as the optional version. If this behaviour is undesired,
1197/// please dereference the pointer in the call.
1198///
1199/// Return type depends on the arguments' types. If we can be sure in compile
1200/// time that there will be a range set as a result, the returning type is
1201/// simply RangeSet, in other cases we have to back off to
1202/// std::optional<RangeSet>.
1203///
1204/// Please, prefer optional range sets to raw pointers. If the last argument is
1205/// a raw pointer and all previous arguments are std::nullopt, it will cost one
1206/// additional check to convert RangeSet * into std::optional<RangeSet>.
1207template <class HeadTy, class SecondTy, class... RestTy>
1208[[nodiscard]] inline
1209 typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
1210 intersect(RangeSet::Factory &F, HeadTy Head, SecondTy Second,
1211 RestTy... Tail) {
1212 if (Head) {
1213 return intersect(F, *Head, Second, Tail...);
1214 }
1215 return intersect(F, Second, Tail...);
1216}
1217
1218using SymbolRangeMap = llvm::DenseMap<SymbolRef, RangeSet>;
1219
1220//===----------------------------------------------------------------------===//
1221// Symbolic reasoning logic
1222//===----------------------------------------------------------------------===//
1223
1224/// A little component aggregating all of the reasoning we have about
1225/// the ranges of symbolic expressions.
1226///
1227/// Even when we don't know the exact values of the operands, we still
1228/// can get a pretty good estimate of the result's range.
1229class SymbolicRangeInferrer
1230 : public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
1231public:
1232 template <class SourceType>
1233 static RangeSet inferRange(RangeSet::Factory &F, ProgramStateRef State,
1234 SourceType Origin, SymbolRangeMap &Cache) {
1235 SymbolicRangeInferrer Inferrer(F, State, Cache);
1236 return Inferrer.infer(Origin);
1237 }
1238
1239 RangeSet VisitSymExpr(SymbolRef Sym) {
1240 if (std::optional<RangeSet> RS = getRangeForNegatedSym(Sym))
1241 return *RS;
1242 // If we've reached this line, the actual type of the symbolic
1243 // expression is not supported for advanced inference.
1244 // In this case, we simply backoff to the default "let's simply
1245 // infer the range from the expression's type".
1246 return infer(Sym->getType());
1247 }
1248
1249 RangeSet VisitUnarySymExpr(const UnarySymExpr *USE) {
1250 if (std::optional<RangeSet> RS = getRangeForNegatedUnarySym(USE))
1251 return *RS;
1252 return infer(USE->getType());
1253 }
1254
1255 RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
1256 return VisitBinaryOperator(Sym);
1257 }
1258
1259 RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
1260 return VisitBinaryOperator(Sym);
1261 }
1262
1263 RangeSet VisitSymSymExpr(const SymSymExpr *SSE) {
1264 return intersect(
1265 RangeFactory,
1266 // If Sym is a difference of symbols A - B, then maybe we have range
1267 // set stored for B - A.
1268 //
1269 // If we have range set stored for both A - B and B - A then
1270 // calculate the effective range set by intersecting the range set
1271 // for A - B and the negated range set of B - A.
1272 getRangeForNegatedSymSym(SSE),
1273 // If commutative, we may have constaints for the commuted variant.
1274 getRangeCommutativeSymSym(SSE),
1275 // If Sym is a comparison expression (except <=>),
1276 // find any other comparisons with the same operands.
1277 // See function description.
1278 getRangeForComparisonSymbol(SSE),
1279 // If Sym is (dis)equality, we might have some information
1280 // on that in our equality classes data structure.
1281 getRangeForEqualities(SSE),
1282 // And we should always check what we can get from the operands.
1283 VisitBinaryOperator(SSE));
1284 }
1285
1286private:
1287 SymbolicRangeInferrer(RangeSet::Factory &F, ProgramStateRef S,
1288 SymbolRangeMap &C)
1289 : ValueFactory(F.getValueFactory()), RangeFactory(F), State(S), Cache(C) {
1290 }
1291
1292 /// Infer range information from the given integer constant.
1293 ///
1294 /// It's not a real "inference", but is here for operating with
1295 /// sub-expressions in a more polymorphic manner.
1296 RangeSet inferAs(const llvm::APSInt &Val, QualType) {
1297 return {RangeFactory, Val};
1298 }
1299
1300 /// Infer range information from symbol in the context of the given type.
1301 RangeSet inferAs(SymbolRef Sym, QualType DestType) {
1302 QualType ActualType = Sym->getType();
1303 // Check that we can reason about the symbol at all.
1304 if (ActualType->isIntegralOrEnumerationType() ||
1305 Loc::isLocType(ActualType)) {
1306 return infer(Sym);
1307 }
1308 // Otherwise, let's simply infer from the destination type.
1309 // We couldn't figure out nothing else about that expression.
1310 return infer(DestType);
1311 }
1312
1313 RangeSet infer(SymbolRef Sym) {
1314 if (auto It = Cache.find(Sym); It != Cache.end())
1315 return It->second;
1316
1317 RangeSet Result = intersect(RangeFactory,
1318 // Of course, we should take the constraint
1319 // directly associated with this symbol into
1320 // consideration.
1321 getConstraint(State, Sym),
1322 // Apart from the Sym itself, we can infer quite
1323 // a lot if we look into subexpressions of Sym.
1324 Visit(Sym));
1325
1326 [[maybe_unused]] bool Inserted = Cache.try_emplace(Sym, Result).second;
1327 assert(Inserted);
1328 return Result;
1329 }
1330
1331 RangeSet infer(EquivalenceClass Class) {
1332 if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
1333 return *AssociatedConstraint;
1334
1335 return infer(Class.getType());
1336 }
1337
1338 /// Infer range information solely from the type.
1339 RangeSet infer(QualType T) {
1340 // Lazily generate a new RangeSet representing all possible values for the
1341 // given symbol type.
1342 RangeSet Result =
1343 RangeFactory.getFullRangeSet(ValueFactory.getAPSIntType(T));
1344
1345 // References are known to be non-zero.
1346 if (T->isReferenceType())
1347 return assumeNonZero(Result, T);
1348
1349 return Result;
1350 }
1351
1352 template <class BinarySymExprTy>
1353 RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
1354 // TODO #1: VisitBinaryOperator implementation might not make a good
1355 // use of the inferred ranges. In this case, we might be calculating
1356 // everything for nothing. This being said, we should introduce some
1357 // sort of laziness mechanism here.
1358 //
1359 // TODO #2: We didn't go into the nested expressions before, so it
1360 // might cause us spending much more time doing the inference.
1361 // This can be a problem for deeply nested expressions that are
1362 // involved in conditions and get tested continuously. We definitely
1363 // need to address this issue and introduce some sort of caching
1364 // in here.
1365 QualType ResultType = Sym->getType();
1366 return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
1367 Sym->getOpcode(),
1368 inferAs(Sym->getRHS(), ResultType), ResultType);
1369 }
1370
1371 RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
1372 RangeSet RHS, QualType T);
1373
1374 //===----------------------------------------------------------------------===//
1375 // Ranges and operators
1376 //===----------------------------------------------------------------------===//
1377
1378 /// Return a rough approximation of the given range set.
1379 ///
1380 /// For the range set:
1381 /// { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
1382 /// it will return the range [x_0, y_N].
1383 static Range fillGaps(RangeSet Origin) {
1384 assert(!Origin.isEmpty());
1385 return {Origin.getMinValue(), Origin.getMaxValue()};
1386 }
1387
1388 /// Try to convert given range into the given type.
1389 ///
1390 /// It will return std::nullopt only when the trivial conversion is possible.
1391 std::optional<Range> convert(const Range &Origin, APSIntType To) {
1392 if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
1393 To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
1394 return std::nullopt;
1395 }
1396 return Range(ValueFactory.Convert(To, Origin.From()),
1397 ValueFactory.Convert(To, Origin.To()));
1398 }
1399
1400 template <BinaryOperator::Opcode Op>
1401 RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
1402 assert(!LHS.isEmpty() && !RHS.isEmpty());
1403
1404 Range CoarseLHS = fillGaps(LHS);
1405 Range CoarseRHS = fillGaps(RHS);
1406
1407 APSIntType ResultType = ValueFactory.getAPSIntType(T);
1408
1409 // We need to convert ranges to the resulting type, so we can compare values
1410 // and combine them in a meaningful (in terms of the given operation) way.
1411 auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
1412 auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
1413
1414 // It is hard to reason about ranges when conversion changes
1415 // borders of the ranges.
1416 if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
1417 return infer(T);
1418 }
1419
1420 return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
1421 }
1422
1423 template <BinaryOperator::Opcode Op>
1424 RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
1425 return infer(T);
1426 }
1427
1428 /// Infer the range of an additive or multiplicative binary operator from the
1429 /// ranges of its operands.
1430 RangeSet inferFromCorners(BinaryOperator::Opcode Op, Range LHS, Range RHS,
1431 QualType T) {
1432 const bool IsUnsigned = T->isUnsignedIntegerOrEnumerationType();
1433
1434 auto Eval = [&](const llvm::APSInt &L,
1435 const llvm::APSInt &R) -> std::optional<llvm::APSInt> {
1436 bool Overflow = false;
1437 llvm::APInt Result;
1438 switch (Op) {
1439 case BO_Add:
1440 Result = IsUnsigned ? L.uadd_ov(R, Overflow) : L.sadd_ov(R, Overflow);
1441 break;
1442 case BO_Sub:
1443 Result = IsUnsigned ? L.usub_ov(R, Overflow) : L.ssub_ov(R, Overflow);
1444 break;
1445 case BO_Mul:
1446 Result = IsUnsigned ? L.umul_ov(R, Overflow) : L.smul_ov(R, Overflow);
1447 break;
1448 default:
1449 llvm_unreachable("only +, - and * are handled here");
1450 }
1451 if (Overflow)
1452 return std::nullopt;
1453 return llvm::APSInt(Result, IsUnsigned);
1454 };
1455
1456 // Fold over the four corners of the [LHS] x [RHS] rectangle, computing each
1457 // one lazily and merging it into the running [Min, Max].
1458 std::optional<llvm::APSInt> Min, Max;
1459 for (const llvm::APSInt &L : {LHS.From(), LHS.To()}) {
1460 for (const llvm::APSInt &R : {RHS.From(), RHS.To()}) {
1461 std::optional<llvm::APSInt> Corner = Eval(L, R);
1462 // A disengaged corner means the operation overflowed the result type,
1463 // so the true result may wrap around and we cannot bound it.
1464 if (!Corner.has_value())
1465 return infer(T);
1466 if (!Min || Corner.value() < *Min)
1467 Min = Corner;
1468 if (!Max || Corner.value() > *Max)
1469 Max = Corner;
1470 }
1471 }
1472 return RangeSet{RangeFactory, ValueFactory.getValue(Min.value()),
1473 ValueFactory.getValue(Max.value())};
1474 }
1475
1476 /// Return a symmetrical range for the given range and type.
1477 ///
1478 /// If T is signed, return the smallest range [-x..x] that covers the original
1479 /// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
1480 /// exist due to original range covering min(T)).
1481 ///
1482 /// If T is unsigned, return the smallest range [0..x] that covers the
1483 /// original range.
1484 Range getSymmetricalRange(Range Origin, QualType T) {
1485 APSIntType RangeType = ValueFactory.getAPSIntType(T);
1486
1487 if (RangeType.isUnsigned()) {
1488 return Range(ValueFactory.getMinValue(RangeType), Origin.To());
1489 }
1490
1491 if (Origin.From().isMinSignedValue()) {
1492 // If mini is a minimal signed value, absolute value of it is greater
1493 // than the maximal signed value. In order to avoid these
1494 // complications, we simply return the whole range.
1495 return {ValueFactory.getMinValue(RangeType),
1496 ValueFactory.getMaxValue(RangeType)};
1497 }
1498
1499 // At this point, we are sure that the type is signed and we can safely
1500 // use unary - operator.
1501 //
1502 // While calculating absolute maximum, we can use the following formula
1503 // because of these reasons:
1504 // * If From >= 0 then To >= From and To >= -From.
1505 // AbsMax == To == max(To, -From)
1506 // * If To <= 0 then -From >= -To and -From >= From.
1507 // AbsMax == -From == max(-From, To)
1508 // * Otherwise, From <= 0, To >= 0, and
1509 // AbsMax == max(abs(From), abs(To))
1510 llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
1511
1512 // Intersection is guaranteed to be non-empty.
1513 return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
1514 }
1515
1516 /// Return a range set subtracting zero from \p Domain.
1517 RangeSet assumeNonZero(RangeSet Domain, QualType T) {
1518 APSIntType IntType = ValueFactory.getAPSIntType(T);
1519 return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
1520 }
1521
1522 template <typename ProduceNegatedSymFunc>
1523 std::optional<RangeSet> getRangeForNegatedExpr(ProduceNegatedSymFunc F,
1524 QualType T) {
1525 // Do not negate if the type cannot be meaningfully negated.
1528 return std::nullopt;
1529
1530 if (SymbolRef NegatedSym = F())
1531 if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym))
1532 return RangeFactory.negate(*NegatedRange);
1533
1534 return std::nullopt;
1535 }
1536
1537 std::optional<RangeSet> getRangeForNegatedUnarySym(const UnarySymExpr *USE) {
1538 // Just get the operand when we negate a symbol that is already negated.
1539 // -(-a) == a
1540 return getRangeForNegatedExpr(
1541 [USE]() -> SymbolRef {
1542 if (USE->getOpcode() == UO_Minus)
1543 return USE->getOperand();
1544 return nullptr;
1545 },
1546 USE->getType());
1547 }
1548
1549 std::optional<RangeSet> getRangeForNegatedSymSym(const SymSymExpr *SSE) {
1550 return getRangeForNegatedExpr(
1551 [SSE, State = this->State]() -> SymbolRef {
1552 if (SSE->getOpcode() == BO_Sub)
1553 return State->getSymbolManager().acquire<SymSymExpr>(
1554 SSE->getRHS(), BO_Sub, SSE->getLHS(), SSE->getType());
1555 return nullptr;
1556 },
1557 SSE->getType());
1558 }
1559
1560 std::optional<RangeSet> getRangeForNegatedSym(SymbolRef Sym) {
1561 return getRangeForNegatedExpr(
1562 [Sym, State = this->State]() {
1563 return State->getSymbolManager().acquire<UnarySymExpr>(
1564 Sym, UO_Minus, Sym->getType());
1565 },
1566 Sym->getType());
1567 }
1568
1569 std::optional<RangeSet> getRangeCommutativeSymSym(const SymSymExpr *SSE) {
1570 auto Op = SSE->getOpcode();
1571 bool IsCommutative = llvm::is_contained(
1572 // ==, !=, |, &, +, *, ^
1573 {BO_EQ, BO_NE, BO_Or, BO_And, BO_Add, BO_Mul, BO_Xor}, Op);
1574 if (!IsCommutative)
1575 return std::nullopt;
1576
1577 SymbolRef Commuted = State->getSymbolManager().acquire<SymSymExpr>(
1578 SSE->getRHS(), Op, SSE->getLHS(), SSE->getType());
1579 if (const RangeSet *Range = getConstraint(State, Commuted))
1580 return *Range;
1581 return std::nullopt;
1582 }
1583
1584 // Returns ranges only for binary comparison operators (except <=>)
1585 // when left and right operands are symbolic values.
1586 // Finds any other comparisons with the same operands.
1587 // Then do logical calculations and refuse impossible branches.
1588 // E.g. (x < y) and (x > y) at the same time are impossible.
1589 // E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
1590 // E.g. (x == y) and (y == x) are just reversed but the same.
1591 // It covers all possible combinations (see CmpOpTable description).
1592 // Note that `x` and `y` can also stand for subexpressions,
1593 // not only for actual symbols.
1594 std::optional<RangeSet> getRangeForComparisonSymbol(const SymSymExpr *SSE) {
1595 const BinaryOperatorKind CurrentOP = SSE->getOpcode();
1596
1597 // We currently do not support <=> (C++20).
1598 if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
1599 return std::nullopt;
1600
1601 static const OperatorRelationsTable CmpOpTable{};
1602
1603 const SymExpr *LHS = SSE->getLHS();
1604 const SymExpr *RHS = SSE->getRHS();
1605 QualType T = SSE->getType();
1606
1607 SymbolManager &SymMgr = State->getSymbolManager();
1608
1609 // We use this variable to store the last queried operator (`QueriedOP`)
1610 // for which the `getCmpOpState` returned with `Unknown`. If there are two
1611 // different OPs that returned `Unknown` then we have to query the special
1612 // `UnknownX2` column. We assume that `getCmpOpState(CurrentOP, CurrentOP)`
1613 // never returns `Unknown`, so `CurrentOP` is a good initial value.
1614 BinaryOperatorKind LastQueriedOpToUnknown = CurrentOP;
1615
1616 // Loop goes through all of the columns exept the last one ('UnknownX2').
1617 // We treat `UnknownX2` column separately at the end of the loop body.
1618 for (size_t i = 0; i < CmpOpTable.getCmpOpCount(); ++i) {
1619
1620 // Let's find an expression e.g. (x < y).
1622 const SymSymExpr *SymSym =
1623 SymMgr.acquire<SymSymExpr>(LHS, QueriedOP, RHS, T);
1624 const RangeSet *QueriedRangeSet = getConstraint(State, SymSym);
1625
1626 // If ranges were not previously found,
1627 // try to find a reversed expression (y > x).
1628 if (!QueriedRangeSet) {
1629 const BinaryOperatorKind ROP =
1631 SymSym = SymMgr.acquire<SymSymExpr>(RHS, ROP, LHS, T);
1632 QueriedRangeSet = getConstraint(State, SymSym);
1633 }
1634
1635 if (!QueriedRangeSet || QueriedRangeSet->isEmpty())
1636 continue;
1637
1638 const llvm::APSInt *ConcreteValue = QueriedRangeSet->getConcreteValue();
1639 const bool isInFalseBranch =
1640 ConcreteValue ? (*ConcreteValue == 0) : false;
1641
1642 // If it is a false branch, we shall be guided by opposite operator,
1643 // because the table is made assuming we are in the true branch.
1644 // E.g. when (x <= y) is false, then (x > y) is true.
1645 if (isInFalseBranch)
1646 QueriedOP = BinaryOperator::negateComparisonOp(QueriedOP);
1647
1649 CmpOpTable.getCmpOpState(CurrentOP, QueriedOP);
1650
1651 if (BranchState == OperatorRelationsTable::Unknown) {
1652 if (LastQueriedOpToUnknown != CurrentOP &&
1653 LastQueriedOpToUnknown != QueriedOP) {
1654 // If we got the Unknown state for both different operators.
1655 // if (x <= y) // assume true
1656 // if (x != y) // assume true
1657 // if (x < y) // would be also true
1658 // Get a state from `UnknownX2` column.
1659 BranchState = CmpOpTable.getCmpOpStateForUnknownX2(CurrentOP);
1660 } else {
1661 LastQueriedOpToUnknown = QueriedOP;
1662 continue;
1663 }
1664 }
1665
1666 return (BranchState == OperatorRelationsTable::True) ? getTrueRange(T)
1667 : getFalseRange(T);
1668 }
1669
1670 return std::nullopt;
1671 }
1672
1673 std::optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) {
1674 std::optional<bool> Equality = meansEquality(Sym);
1675
1676 if (!Equality)
1677 return std::nullopt;
1678
1679 if (std::optional<bool> AreEqual =
1680 EquivalenceClass::areEqual(State, Sym->getLHS(), Sym->getRHS())) {
1681 // Here we cover two cases at once:
1682 // * if Sym is equality and its operands are known to be equal -> true
1683 // * if Sym is disequality and its operands are disequal -> true
1684 if (*AreEqual == *Equality) {
1685 return getTrueRange(Sym->getType());
1686 }
1687 // Opposite combinations result in false.
1688 return getFalseRange(Sym->getType());
1689 }
1690
1691 return std::nullopt;
1692 }
1693
1694 RangeSet getTrueRange(QualType T) {
1695 RangeSet TypeRange = infer(T);
1696 return assumeNonZero(TypeRange, T);
1697 }
1698
1699 RangeSet getFalseRange(QualType T) {
1700 const llvm::APSInt &Zero = ValueFactory.getValue(0, T);
1701 return RangeSet(RangeFactory, Zero);
1702 }
1703
1704 BasicValueFactory &ValueFactory;
1705 RangeSet::Factory &RangeFactory;
1706 ProgramStateRef State;
1707 SymbolRangeMap &Cache;
1708};
1709
1710//===----------------------------------------------------------------------===//
1711// Range-based reasoning about symbolic operations
1712//===----------------------------------------------------------------------===//
1713
1714template <>
1715RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_NE>(RangeSet LHS,
1716 RangeSet RHS,
1717 QualType T) {
1718 assert(!LHS.isEmpty() && !RHS.isEmpty());
1719
1720 if (LHS.getAPSIntType() == RHS.getAPSIntType()) {
1721 if (intersect(RangeFactory, LHS, RHS).isEmpty())
1722 return getTrueRange(T);
1723
1724 } else {
1725 // We can only lose information if we are casting smaller signed type to
1726 // bigger unsigned type. For e.g.,
1727 // LHS (unsigned short): [2, USHRT_MAX]
1728 // RHS (signed short): [SHRT_MIN, 0]
1729 //
1730 // Casting RHS to LHS type will leave us with overlapping values
1731 // CastedRHS : [0, 0] U [SHRT_MAX + 1, USHRT_MAX]
1732 //
1733 // We can avoid this by checking if signed type's maximum value is lesser
1734 // than unsigned type's minimum value.
1735
1736 // If both have different signs then only we can get more information.
1737 if (LHS.isUnsigned() != RHS.isUnsigned()) {
1738 if (LHS.isUnsigned() && (LHS.getBitWidth() >= RHS.getBitWidth())) {
1739 if (RHS.getMaxValue().isNegative() ||
1740 LHS.getAPSIntType().convert(RHS.getMaxValue()) < LHS.getMinValue())
1741 return getTrueRange(T);
1742
1743 } else if (RHS.isUnsigned() && (LHS.getBitWidth() <= RHS.getBitWidth())) {
1744 if (LHS.getMaxValue().isNegative() ||
1745 RHS.getAPSIntType().convert(LHS.getMaxValue()) < RHS.getMinValue())
1746 return getTrueRange(T);
1747 }
1748 }
1749
1750 // Both RangeSets should be casted to bigger unsigned type.
1751 APSIntType CastingType(std::max(LHS.getBitWidth(), RHS.getBitWidth()),
1752 LHS.isUnsigned() || RHS.isUnsigned());
1753
1754 RangeSet CastedLHS = RangeFactory.castTo(LHS, CastingType);
1755 RangeSet CastedRHS = RangeFactory.castTo(RHS, CastingType);
1756
1757 if (intersect(RangeFactory, CastedLHS, CastedRHS).isEmpty())
1758 return getTrueRange(T);
1759 }
1760
1761 // In all other cases, the resulting range cannot be deduced.
1762 return infer(T);
1763}
1764
1765template <>
1766RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Or>(Range LHS, Range RHS,
1767 QualType T) {
1768 APSIntType ResultType = ValueFactory.getAPSIntType(T);
1769 llvm::APSInt Zero = ResultType.getZeroValue();
1770
1771 bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1772 bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1773
1774 bool IsLHSNegative = LHS.To() < Zero;
1775 bool IsRHSNegative = RHS.To() < Zero;
1776
1777 // Check if both ranges have the same sign.
1778 if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1779 (IsLHSNegative && IsRHSNegative)) {
1780 // The result is definitely greater or equal than any of the operands.
1781 const llvm::APSInt &Min = std::max(LHS.From(), RHS.From());
1782
1783 // We estimate maximal value for positives as the maximal value for the
1784 // given type. For negatives, we estimate it with -1 (e.g. 0x11111111).
1785 //
1786 // TODO: We basically, limit the resulting range from below, but don't do
1787 // anything with the upper bound.
1788 //
1789 // For positive operands, it can be done as follows: for the upper
1790 // bound of LHS and RHS we calculate the most significant bit set.
1791 // Let's call it the N-th bit. Then we can estimate the maximal
1792 // number to be 2^(N+1)-1, i.e. the number with all the bits up to
1793 // the N-th bit set.
1794 const llvm::APSInt &Max = IsLHSNegative
1795 ? ValueFactory.getValue(--Zero)
1796 : ValueFactory.getMaxValue(ResultType);
1797
1798 return {RangeFactory, ValueFactory.getValue(Min), Max};
1799 }
1800
1801 // Otherwise, let's check if at least one of the operands is negative.
1802 if (IsLHSNegative || IsRHSNegative) {
1803 // This means that the result is definitely negative as well.
1804 return {RangeFactory, ValueFactory.getMinValue(ResultType),
1805 ValueFactory.getValue(--Zero)};
1806 }
1807
1808 RangeSet DefaultRange = infer(T);
1809
1810 // It is pretty hard to reason about operands with different signs
1811 // (and especially with possibly different signs). We simply check if it
1812 // can be zero. In order to conclude that the result could not be zero,
1813 // at least one of the operands should be definitely not zero itself.
1814 if (!LHS.Includes(Zero) || !RHS.Includes(Zero)) {
1815 return assumeNonZero(DefaultRange, T);
1816 }
1817
1818 // Nothing much else to do here.
1819 return DefaultRange;
1820}
1821
1822template <>
1823RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_And>(Range LHS,
1824 Range RHS,
1825 QualType T) {
1826 APSIntType ResultType = ValueFactory.getAPSIntType(T);
1827 llvm::APSInt Zero = ResultType.getZeroValue();
1828
1829 bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1830 bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1831
1832 bool IsLHSNegative = LHS.To() < Zero;
1833 bool IsRHSNegative = RHS.To() < Zero;
1834
1835 // Check if both ranges have the same sign.
1836 if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1837 (IsLHSNegative && IsRHSNegative)) {
1838 // The result is definitely less or equal than any of the operands.
1839 const llvm::APSInt &Max = std::min(LHS.To(), RHS.To());
1840
1841 // We conservatively estimate lower bound to be the smallest positive
1842 // or negative value corresponding to the sign of the operands.
1843 const llvm::APSInt &Min = IsLHSNegative
1844 ? ValueFactory.getMinValue(ResultType)
1845 : ValueFactory.getValue(Zero);
1846
1847 return {RangeFactory, Min, Max};
1848 }
1849
1850 // Otherwise, let's check if at least one of the operands is positive.
1851 if (IsLHSPositiveOrZero || IsRHSPositiveOrZero) {
1852 // This makes result definitely positive.
1853 //
1854 // We can also reason about a maximal value by finding the maximal
1855 // value of the positive operand.
1856 const llvm::APSInt &Max = IsLHSPositiveOrZero ? LHS.To() : RHS.To();
1857
1858 // The minimal value on the other hand is much harder to reason about.
1859 // The only thing we know for sure is that the result is positive.
1860 return {RangeFactory, ValueFactory.getValue(Zero),
1861 ValueFactory.getValue(Max)};
1862 }
1863
1864 // Nothing much else to do here.
1865 return infer(T);
1866}
1867
1868template <>
1869RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Rem>(Range LHS,
1870 Range RHS,
1871 QualType T) {
1872 llvm::APSInt Zero = ValueFactory.getAPSIntType(T).getZeroValue();
1873
1874 Range ConservativeRange = getSymmetricalRange(RHS, T);
1875
1876 llvm::APSInt Max = ConservativeRange.To();
1877 llvm::APSInt Min = ConservativeRange.From();
1878
1879 if (Max == Zero) {
1880 // It's an undefined behaviour to divide by 0 and it seems like we know
1881 // for sure that RHS is 0. Let's say that the resulting range is
1882 // simply infeasible for that matter.
1883 return RangeFactory.getEmptySet();
1884 }
1885
1886 // At this point, our conservative range is closed. The result, however,
1887 // couldn't be greater than the RHS' maximal absolute value. Because of
1888 // this reason, we turn the range into open (or half-open in case of
1889 // unsigned integers).
1890 //
1891 // While we operate on integer values, an open interval (a, b) can be easily
1892 // represented by the closed interval [a + 1, b - 1]. And this is exactly
1893 // what we do next.
1894 //
1895 // If we are dealing with unsigned case, we shouldn't move the lower bound.
1896 if (Min.isSigned()) {
1897 ++Min;
1898 }
1899 --Max;
1900
1901 bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1902 bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1903
1904 // Remainder operator results with negative operands is implementation
1905 // defined. Positive cases are much easier to reason about though.
1906 if (IsLHSPositiveOrZero && IsRHSPositiveOrZero) {
1907 // If maximal value of LHS is less than maximal value of RHS,
1908 // the result won't get greater than LHS.To().
1909 Max = std::min(LHS.To(), Max);
1910 // We want to check if it is a situation similar to the following:
1911 //
1912 // <------------|---[ LHS ]--------[ RHS ]----->
1913 // -INF 0 +INF
1914 //
1915 // In this situation, we can conclude that (LHS / RHS) == 0 and
1916 // (LHS % RHS) == LHS.
1917 Min = LHS.To() < RHS.From() ? LHS.From() : Zero;
1918 }
1919
1920 // Nevertheless, the symmetrical range for RHS is a conservative estimate
1921 // for any sign of either LHS, or RHS.
1922 return {RangeFactory, ValueFactory.getValue(Min), ValueFactory.getValue(Max)};
1923}
1924
1925template <>
1926RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Add>(Range LHS,
1927 Range RHS,
1928 QualType T) {
1929 return inferFromCorners(BO_Add, LHS, RHS, T);
1930}
1931
1932template <>
1933RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Sub>(Range LHS,
1934 Range RHS,
1935 QualType T) {
1936 return inferFromCorners(BO_Sub, LHS, RHS, T);
1937}
1938
1939template <>
1940RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Mul>(Range LHS,
1941 Range RHS,
1942 QualType T) {
1943 return inferFromCorners(BO_Mul, LHS, RHS, T);
1944}
1945
1946RangeSet SymbolicRangeInferrer::VisitBinaryOperator(RangeSet LHS,
1948 RangeSet RHS, QualType T) {
1949 // We should propagate information about unfeasbility of one of the
1950 // operands to the resulting range.
1951 if (LHS.isEmpty() || RHS.isEmpty()) {
1952 return RangeFactory.getEmptySet();
1953 }
1954
1955 switch (Op) {
1956 case BO_NE:
1957 return VisitBinaryOperator<BO_NE>(LHS, RHS, T);
1958 case BO_Or:
1959 return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
1960 case BO_And:
1961 return VisitBinaryOperator<BO_And>(LHS, RHS, T);
1962 case BO_Rem:
1963 return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
1964 case BO_Add:
1965 return VisitBinaryOperator<BO_Add>(LHS, RHS, T);
1966 case BO_Sub:
1967 return VisitBinaryOperator<BO_Sub>(LHS, RHS, T);
1968 case BO_Mul:
1969 return VisitBinaryOperator<BO_Mul>(LHS, RHS, T);
1970 default:
1971 return infer(T);
1972 }
1973}
1974
1975//===----------------------------------------------------------------------===//
1976// Constraint manager implementation details
1977//===----------------------------------------------------------------------===//
1978
1979class RangeConstraintManager final : public RangedConstraintManager {
1980public:
1981 RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB)
1982 : RangedConstraintManager(EE, SVB), F(getBasicVals()) {}
1983
1984 //===------------------------------------------------------------------===//
1985 // Implementation for interface from ConstraintManager.
1986 //===------------------------------------------------------------------===//
1987
1988 bool haveEqualConstraints(ProgramStateRef S1,
1989 ProgramStateRef S2) const override {
1990 // NOTE: ClassMembers are as simple as back pointers for ClassMap,
1991 // so comparing constraint ranges and class maps should be
1992 // sufficient.
1993 return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() &&
1994 S1->get<ClassMap>() == S2->get<ClassMap>();
1995 }
1996
1997 bool canReasonAbout(SVal X) const override;
1998
1999 ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
2000
2001 const llvm::APSInt *getSymVal(ProgramStateRef State,
2002 SymbolRef Sym) const override;
2003
2004 const llvm::APSInt *getSymMinVal(ProgramStateRef State,
2005 SymbolRef Sym) const override;
2006
2007 const llvm::APSInt *getSymMaxVal(ProgramStateRef State,
2008 SymbolRef Sym) const override;
2009
2010 ProgramStateRef removeDeadBindings(ProgramStateRef State,
2011 SymbolReaper &SymReaper) override;
2012
2013 void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
2014 unsigned int Space = 0, bool IsDot = false) const override;
2015 void printValue(raw_ostream &Out, ProgramStateRef State,
2016 SymbolRef Sym) override;
2017 void printConstraints(raw_ostream &Out, ProgramStateRef State,
2018 const char *NL = "\n", unsigned int Space = 0,
2019 bool IsDot = false) const;
2020 void printEquivalenceClasses(raw_ostream &Out, ProgramStateRef State,
2021 const char *NL = "\n", unsigned int Space = 0,
2022 bool IsDot = false) const;
2023 void printDisequalities(raw_ostream &Out, ProgramStateRef State,
2024 const char *NL = "\n", unsigned int Space = 0,
2025 bool IsDot = false) const;
2026
2027 //===------------------------------------------------------------------===//
2028 // Implementation for interface from RangedConstraintManager.
2029 //===------------------------------------------------------------------===//
2030
2031 ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
2032 const llvm::APSInt &V,
2033 const llvm::APSInt &Adjustment) override;
2034
2035 ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
2036 const llvm::APSInt &V,
2037 const llvm::APSInt &Adjustment) override;
2038
2039 ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
2040 const llvm::APSInt &V,
2041 const llvm::APSInt &Adjustment) override;
2042
2043 ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
2044 const llvm::APSInt &V,
2045 const llvm::APSInt &Adjustment) override;
2046
2047 ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
2048 const llvm::APSInt &V,
2049 const llvm::APSInt &Adjustment) override;
2050
2051 ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
2052 const llvm::APSInt &V,
2053 const llvm::APSInt &Adjustment) override;
2054
2055 ProgramStateRef assumeSymWithinInclusiveRange(
2056 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2057 const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
2058
2059 ProgramStateRef assumeSymOutsideInclusiveRange(
2060 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2061 const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
2062
2063private:
2064 mutable RangeSet::Factory F;
2065
2066 /// Ranges memoized for the state queried last. The ProgramStateRef keeps it
2067 /// alive, so this manager must be destroyed before the state set (see the
2068 /// member order in ProgramStateManager).
2069 mutable ProgramStateRef RangeCacheState;
2070 mutable SymbolRangeMap RangeCache;
2071
2072 RangeSet getRange(ProgramStateRef State, SymbolRef Sym) const;
2073 ProgramStateRef setRange(ProgramStateRef State, SymbolRef Sym,
2074 RangeSet Range);
2075
2076 RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
2077 const llvm::APSInt &Int,
2078 const llvm::APSInt &Adjustment) const;
2079 RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
2080 const llvm::APSInt &Int,
2081 const llvm::APSInt &Adjustment) const;
2082 RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
2083 const llvm::APSInt &Int,
2084 const llvm::APSInt &Adjustment) const;
2085 RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
2086 const llvm::APSInt &Int,
2087 const llvm::APSInt &Adjustment) const;
2088 RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
2089 const llvm::APSInt &Int,
2090 const llvm::APSInt &Adjustment) const;
2091};
2092
2093//===----------------------------------------------------------------------===//
2094// Constraint assignment logic
2095//===----------------------------------------------------------------------===//
2096
2097/// ConstraintAssignorBase is a small utility class that unifies visitor
2098/// for ranges with a visitor for constraints (rangeset/range/constant).
2099///
2100/// It is designed to have one derived class, but generally it can have more.
2101/// Derived class can control which types we handle by defining methods of the
2102/// following form:
2103///
2104/// bool assign${SYMBOL}To${CONSTRAINT}(const SYMBOL *Sym,
2105/// CONSTRAINT Constraint);
2106///
2107/// where SYMBOL is the type of the symbol (e.g. SymSymExpr, SymbolCast, etc.)
2108/// CONSTRAINT is the type of constraint (RangeSet/Range/Const)
2109/// return value signifies whether we should try other handle methods
2110/// (i.e. false would mean to stop right after calling this method)
2111template <class Derived> class ConstraintAssignorBase {
2112public:
2113 using Const = const llvm::APSInt &;
2114
2115#define DISPATCH(CLASS) return assign##CLASS##Impl(cast<CLASS>(Sym), Constraint)
2116
2117#define ASSIGN(CLASS, TO, SYM, CONSTRAINT) \
2118 if (!static_cast<Derived *>(this)->assign##CLASS##To##TO(SYM, CONSTRAINT)) \
2119 return false
2120
2121 void assign(SymbolRef Sym, RangeSet Constraint) {
2122 assignImpl(Sym, Constraint);
2123 }
2124
2125 bool assignImpl(SymbolRef Sym, RangeSet Constraint) {
2126 switch (Sym->getKind()) {
2127#define SYMBOL(Id, Parent) \
2128 case SymExpr::Id##Kind: \
2129 DISPATCH(Id);
2130#include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
2131 }
2132 llvm_unreachable("Unknown SymExpr kind!");
2133 }
2134
2135#define DEFAULT_ASSIGN(Id) \
2136 bool assign##Id##To##RangeSet(const Id *Sym, RangeSet Constraint) { \
2137 return true; \
2138 } \
2139 bool assign##Id##To##Range(const Id *Sym, Range Constraint) { return true; } \
2140 bool assign##Id##To##Const(const Id *Sym, Const Constraint) { return true; }
2141
2142 // When we dispatch for constraint types, we first try to check
2143 // if the new constraint is the constant and try the corresponding
2144 // assignor methods. If it didn't interrupt, we can proceed to the
2145 // range, and finally to the range set.
2146#define CONSTRAINT_DISPATCH(Id) \
2147 if (const llvm::APSInt *Const = Constraint.getConcreteValue()) { \
2148 ASSIGN(Id, Const, Sym, *Const); \
2149 } \
2150 if (Constraint.size() == 1) { \
2151 ASSIGN(Id, Range, Sym, *Constraint.begin()); \
2152 } \
2153 ASSIGN(Id, RangeSet, Sym, Constraint)
2154
2155 // Our internal assign method first tries to call assignor methods for all
2156 // constraint types that apply. And if not interrupted, continues with its
2157 // parent class.
2158#define SYMBOL(Id, Parent) \
2159 bool assign##Id##Impl(const Id *Sym, RangeSet Constraint) { \
2160 CONSTRAINT_DISPATCH(Id); \
2161 DISPATCH(Parent); \
2162 } \
2163 DEFAULT_ASSIGN(Id)
2164#define ABSTRACT_SYMBOL(Id, Parent) SYMBOL(Id, Parent)
2165#include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
2166
2167 // Default implementations for the top class that doesn't have parents.
2168 bool assignSymExprImpl(const SymExpr *Sym, RangeSet Constraint) {
2170 return true;
2171 }
2172 DEFAULT_ASSIGN(SymExpr);
2173
2174#undef DISPATCH
2175#undef CONSTRAINT_DISPATCH
2176#undef DEFAULT_ASSIGN
2177#undef ASSIGN
2178};
2179
2180/// A little component aggregating all of the reasoning we have about
2181/// assigning new constraints to symbols.
2182///
2183/// The main purpose of this class is to associate constraints to symbols,
2184/// and impose additional constraints on other symbols, when we can imply
2185/// them.
2186///
2187/// It has a nice symmetry with SymbolicRangeInferrer. When the latter
2188/// can provide more precise ranges by looking into the operands of the
2189/// expression in question, ConstraintAssignor looks into the operands
2190/// to see if we can imply more from the new constraint.
2191class ConstraintAssignor : public ConstraintAssignorBase<ConstraintAssignor> {
2192public:
2193 template <class ClassOrSymbol>
2194 [[nodiscard]] static ProgramStateRef
2195 assign(ProgramStateRef State, SValBuilder &Builder, RangeSet::Factory &F,
2196 ClassOrSymbol CoS, RangeSet NewConstraint) {
2197 if (!State || NewConstraint.isEmpty())
2198 return nullptr;
2199
2200 ConstraintAssignor Assignor{State, Builder, F};
2201 return Assignor.assign(CoS, NewConstraint);
2202 }
2203
2204 /// Handle expressions like: a % b != 0.
2205 template <typename SymT>
2206 bool handleRemainderOp(const SymT *Sym, RangeSet Constraint) {
2207 if (Sym->getOpcode() != BO_Rem)
2208 return true;
2209 // a % b != 0 implies that a != 0.
2210 if (!Constraint.containsZero()) {
2211 SVal SymSVal = Builder.makeSymbolVal(Sym->getLHS());
2212 if (auto NonLocSymSVal = SymSVal.getAs<nonloc::SymbolVal>()) {
2213 State = State->assume(*NonLocSymSVal, true);
2214 if (!State)
2215 return false;
2216 }
2217 }
2218 return true;
2219 }
2220
2221 inline bool assignSymExprToConst(const SymExpr *Sym, Const Constraint);
2222 inline bool assignSymIntExprToRangeSet(const SymIntExpr *Sym,
2223 RangeSet Constraint) {
2224 return handleRemainderOp(Sym, Constraint);
2225 }
2226 inline bool assignSymSymExprToRangeSet(const SymSymExpr *Sym,
2227 RangeSet Constraint);
2228
2229private:
2230 ConstraintAssignor(ProgramStateRef State, SValBuilder &Builder,
2232 : State(State), Builder(Builder), RangeFactory(F) {}
2233 using Base = ConstraintAssignorBase<ConstraintAssignor>;
2234
2235 /// Base method for handling new constraints for symbols.
2236 [[nodiscard]] ProgramStateRef assign(SymbolRef Sym, RangeSet NewConstraint) {
2237 // All constraints are actually associated with equivalence classes, and
2238 // that's what we are going to do first.
2239 State = assign(EquivalenceClass::find(State, Sym), NewConstraint);
2240 if (!State)
2241 return nullptr;
2242
2243 // And after that we can check what other things we can get from this
2244 // constraint.
2245 Base::assign(Sym, NewConstraint);
2246 return State;
2247 }
2248
2249 /// Base method for handling new constraints for classes.
2250 [[nodiscard]] ProgramStateRef assign(EquivalenceClass Class,
2251 RangeSet NewConstraint) {
2252 // There is a chance that we might need to update constraints for the
2253 // classes that are known to be disequal to Class.
2254 //
2255 // In order for this to be even possible, the new constraint should
2256 // be simply a constant because we can't reason about range disequalities.
2257 if (const llvm::APSInt *Point = NewConstraint.getConcreteValue()) {
2258
2259 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2260 ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>();
2261
2262 // Add new constraint.
2263 Constraints = CF.add(Constraints, Class, NewConstraint);
2264
2265 for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) {
2266 SymbolRangeMap DiscardedCache;
2267 RangeSet UpdatedConstraint = SymbolicRangeInferrer::inferRange(
2268 RangeFactory, State, DisequalClass, DiscardedCache);
2269
2270 UpdatedConstraint = RangeFactory.deletePoint(UpdatedConstraint, *Point);
2271
2272 // If we end up with at least one of the disequal classes to be
2273 // constrained with an empty range-set, the state is infeasible.
2274 if (UpdatedConstraint.isEmpty())
2275 return nullptr;
2276
2277 Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint);
2278 }
2279 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2280 "a state with infeasible constraints");
2281
2282 return setConstraints(State, Constraints);
2283 }
2284
2285 return setConstraint(State, Class, NewConstraint);
2286 }
2287
2288 ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS,
2289 SymbolRef RHS) {
2290 return EquivalenceClass::markDisequal(RangeFactory, State, LHS, RHS);
2291 }
2292
2293 ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS,
2294 SymbolRef RHS) {
2295 return EquivalenceClass::merge(RangeFactory, State, LHS, RHS);
2296 }
2297
2298 [[nodiscard]] std::optional<bool> interpreteAsBool(RangeSet Constraint) {
2299 assert(!Constraint.isEmpty() && "Empty ranges shouldn't get here");
2300
2301 if (Constraint.getConcreteValue())
2302 return !Constraint.getConcreteValue()->isZero();
2303
2304 if (!Constraint.containsZero())
2305 return true;
2306
2307 return std::nullopt;
2308 }
2309
2310 ProgramStateRef State;
2311 SValBuilder &Builder;
2312 RangeSet::Factory &RangeFactory;
2313};
2314
2315bool ConstraintAssignor::assignSymExprToConst(const SymExpr *Sym,
2316 const llvm::APSInt &Constraint) {
2317 llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses;
2318 // Iterate over all equivalence classes and try to simplify them.
2319 ClassMembersTy Members = State->get<ClassMembers>();
2320 for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) {
2321 EquivalenceClass Class = ClassToSymbolSet.first;
2322 State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2323 if (!State)
2324 return false;
2325 SimplifiedClasses.insert(Class);
2326 }
2327
2328 // Trivial equivalence classes (those that have only one symbol member) are
2329 // not stored in the State. Thus, we must skim through the constraints as
2330 // well. And we try to simplify symbols in the constraints.
2331 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2332 for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
2333 EquivalenceClass Class = ClassConstraint.first;
2334 if (SimplifiedClasses.count(Class)) // Already simplified.
2335 continue;
2336 State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2337 if (!State)
2338 return false;
2339 }
2340
2341 // We may have trivial equivalence classes in the disequality info as
2342 // well, and we need to simplify them.
2343 DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2344 for (std::pair<EquivalenceClass, ClassSet> DisequalityEntry :
2345 DisequalityInfo) {
2346 EquivalenceClass Class = DisequalityEntry.first;
2347 State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
2348 if (!State)
2349 return false;
2350 }
2351
2352 return true;
2353}
2354
2355bool ConstraintAssignor::assignSymSymExprToRangeSet(const SymSymExpr *Sym,
2356 RangeSet Constraint) {
2357 if (!handleRemainderOp(Sym, Constraint))
2358 return false;
2359
2360 std::optional<bool> ConstraintAsBool = interpreteAsBool(Constraint);
2361
2362 if (!ConstraintAsBool)
2363 return true;
2364
2365 if (std::optional<bool> Equality = meansEquality(Sym)) {
2366 // Here we cover two cases:
2367 // * if Sym is equality and the new constraint is true -> Sym's operands
2368 // should be marked as equal
2369 // * if Sym is disequality and the new constraint is false -> Sym's
2370 // operands should be also marked as equal
2371 if (*Equality == *ConstraintAsBool) {
2372 State = trackEquality(State, Sym->getLHS(), Sym->getRHS());
2373 } else {
2374 // Other combinations leave as with disequal operands.
2375 State = trackDisequality(State, Sym->getLHS(), Sym->getRHS());
2376 }
2377
2378 if (!State)
2379 return false;
2380 }
2381
2382 return true;
2383}
2384
2385} // end anonymous namespace
2386
2387std::unique_ptr<ConstraintManager>
2389 ExprEngine *Eng) {
2390 return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
2391}
2392
2394 ConstraintMap::Factory &F = State->get_context<ConstraintMap>();
2395 ConstraintMap Result = F.getEmptyMap();
2396
2397 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2398 for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
2399 EquivalenceClass Class = ClassConstraint.first;
2400 SymbolSet ClassMembers = Class.getClassMembers(State);
2401 assert(!ClassMembers.isEmpty() &&
2402 "Class must always have at least one member!");
2403
2404 SymbolRef Representative = *ClassMembers.begin();
2405 Result = F.add(Result, Representative, ClassConstraint.second);
2406 }
2407
2408 return Result;
2409}
2410
2411//===----------------------------------------------------------------------===//
2412// EqualityClass implementation details
2413//===----------------------------------------------------------------------===//
2414
2415LLVM_DUMP_METHOD void EquivalenceClass::dumpToStream(ProgramStateRef State,
2416 raw_ostream &os) const {
2417 SymbolSet ClassMembers = getClassMembers(State);
2418 for (const SymbolRef &MemberSym : ClassMembers) {
2419 MemberSym->dump();
2420 os << "\n";
2421 }
2422}
2423
2424inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
2425 SymbolRef Sym) {
2426 assert(State && "State should not be null");
2427 assert(Sym && "Symbol should not be null");
2428 // We store far from all Symbol -> Class mappings
2429 if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym))
2430 return *NontrivialClass;
2431
2432 // This is a trivial class of Sym.
2433 return Sym;
2434}
2435
2436inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
2437 ProgramStateRef State,
2439 SymbolRef Second) {
2440 EquivalenceClass FirstClass = find(State, First);
2441 EquivalenceClass SecondClass = find(State, Second);
2442
2443 return FirstClass.merge(F, State, SecondClass);
2444}
2445
2446inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
2447 ProgramStateRef State,
2448 EquivalenceClass Other) {
2449 // It is already the same class.
2450 if (*this == Other)
2451 return State;
2452
2453 // FIXME: As of now, we support only equivalence classes of the same type.
2454 // This limitation is connected to the lack of explicit casts in
2455 // our symbolic expression model.
2456 //
2457 // That means that for `int x` and `char y` we don't distinguish
2458 // between these two very different cases:
2459 // * `x == y`
2460 // * `(char)x == y`
2461 //
2462 // The moment we introduce symbolic casts, this restriction can be
2463 // lifted.
2464 if (getType()->getCanonicalTypeUnqualified() !=
2465 Other.getType()->getCanonicalTypeUnqualified())
2466 return State;
2467
2468 SymbolSet Members = getClassMembers(State);
2469 SymbolSet OtherMembers = Other.getClassMembers(State);
2470
2471 // We estimate the size of the class by the height of tree containing
2472 // its members. Merging is not a trivial operation, so it's easier to
2473 // merge the smaller class into the bigger one.
2474 if (Members.getHeight() >= OtherMembers.getHeight()) {
2475 return mergeImpl(F, State, Members, Other, OtherMembers);
2476 } else {
2477 return Other.mergeImpl(F, State, OtherMembers, *this, Members);
2478 }
2479}
2480
2481inline ProgramStateRef
2482EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory,
2483 ProgramStateRef State, SymbolSet MyMembers,
2484 EquivalenceClass Other, SymbolSet OtherMembers) {
2485 // Essentially what we try to recreate here is some kind of union-find
2486 // data structure. It does have certain limitations due to persistence
2487 // and the need to remove elements from classes.
2488 //
2489 // In this setting, EquialityClass object is the representative of the class
2490 // or the parent element. ClassMap is a mapping of class members to their
2491 // parent. Unlike the union-find structure, they all point directly to the
2492 // class representative because we don't have an opportunity to actually do
2493 // path compression when dealing with immutability. This means that we
2494 // compress paths every time we do merges. It also means that we lose
2495 // the main amortized complexity benefit from the original data structure.
2496 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2497 ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
2498
2499 // 1. If the merged classes have any constraints associated with them, we
2500 // need to transfer them to the class we have left.
2501 //
2502 // Intersection here makes perfect sense because both of these constraints
2503 // must hold for the whole new class.
2504 if (std::optional<RangeSet> NewClassConstraint =
2505 intersect(RangeFactory, getConstraint(State, *this),
2506 getConstraint(State, Other))) {
2507 // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because
2508 // range inferrer shouldn't generate ranges incompatible with
2509 // equivalence classes. However, at the moment, due to imperfections
2510 // in the solver, it is possible and the merge function can also
2511 // return infeasible states aka null states.
2512 if (NewClassConstraint->isEmpty())
2513 // Infeasible state
2514 return nullptr;
2515
2516 // No need in tracking constraints of a now-dissolved class.
2517 Constraints = CRF.remove(Constraints, Other);
2518 // Assign new constraints for this class.
2519 Constraints = CRF.add(Constraints, *this, *NewClassConstraint);
2520
2521 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2522 "a state with infeasible constraints");
2523
2524 State = State->set<ConstraintRange>(Constraints);
2525 }
2526
2527 // 2. Get ALL equivalence-related maps
2528 ClassMapTy Classes = State->get<ClassMap>();
2529 ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
2530
2531 ClassMembersTy Members = State->get<ClassMembers>();
2532 ClassMembersTy::Factory &MF = State->get_context<ClassMembers>();
2533
2534 DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2535 DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>();
2536
2537 ClassSet::Factory &CF = State->get_context<ClassSet>();
2538 SymbolSet::Factory &F = getMembersFactory(State);
2539
2540 // 2. Merge members of the Other class into the current class.
2541 SymbolSet NewClassMembers = MyMembers;
2542 for (SymbolRef Sym : OtherMembers) {
2543 NewClassMembers = F.add(NewClassMembers, Sym);
2544 // *this is now the class for all these new symbols.
2545 Classes = CMF.add(Classes, Sym, *this);
2546 }
2547
2548 // 3. Adjust member mapping.
2549 //
2550 // No need in tracking members of a now-dissolved class.
2551 Members = MF.remove(Members, Other);
2552 // Now only the current class is mapped to all the symbols.
2553 Members = MF.add(Members, *this, NewClassMembers);
2554
2555 // 4. Update disequality relations
2556 ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF);
2557 // We are about to merge two classes but they are already known to be
2558 // non-equal. This is a contradiction.
2559 if (DisequalToOther.contains(*this))
2560 return nullptr;
2561
2562 if (!DisequalToOther.isEmpty()) {
2563 ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF);
2564 DisequalityInfo = DF.remove(DisequalityInfo, Other);
2565
2566 for (EquivalenceClass DisequalClass : DisequalToOther) {
2567 DisequalToThis = CF.add(DisequalToThis, DisequalClass);
2568
2569 // Disequality is a symmetric relation meaning that if
2570 // DisequalToOther not null then the set for DisequalClass is not
2571 // empty and has at least Other.
2572 ClassSet OriginalSetLinkedToOther =
2573 *DisequalityInfo.lookup(DisequalClass);
2574
2575 // Other will be eliminated and we should replace it with the bigger
2576 // united class.
2577 ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other);
2578 NewSet = CF.add(NewSet, *this);
2579
2580 DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet);
2581 }
2582
2583 DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis);
2584 State = State->set<DisequalityMap>(DisequalityInfo);
2585 }
2586
2587 // 5. Update the state
2588 State = State->set<ClassMap>(Classes);
2589 State = State->set<ClassMembers>(Members);
2590
2591 return State;
2592}
2593
2594inline SymbolSet::Factory &
2595EquivalenceClass::getMembersFactory(ProgramStateRef State) {
2596 return State->get_context<SymbolSet>();
2597}
2598
2599SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const {
2600 if (const SymbolSet *Members = State->get<ClassMembers>(*this))
2601 return *Members;
2602
2603 // This class is trivial, so we need to construct a set
2604 // with just that one symbol from the class.
2605 SymbolSet::Factory &F = getMembersFactory(State);
2606 return F.add(F.getEmptySet(), getRepresentativeSymbol());
2607}
2608
2609bool EquivalenceClass::isTrivial(ProgramStateRef State) const {
2610 return State->get<ClassMembers>(*this) == nullptr;
2611}
2612
2613bool EquivalenceClass::isTriviallyDead(ProgramStateRef State,
2614 SymbolReaper &Reaper) const {
2615 return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol());
2616}
2617
2618inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
2619 ProgramStateRef State,
2621 SymbolRef Second) {
2622 return markDisequal(RF, State, find(State, First), find(State, Second));
2623}
2624
2625inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
2626 ProgramStateRef State,
2627 EquivalenceClass First,
2628 EquivalenceClass Second) {
2629 return First.markDisequal(RF, State, Second);
2630}
2631
2632inline ProgramStateRef
2633EquivalenceClass::markDisequal(RangeSet::Factory &RF, ProgramStateRef State,
2634 EquivalenceClass Other) const {
2635 // If we know that two classes are equal, we can only produce an infeasible
2636 // state.
2637 if (*this == Other) {
2638 return nullptr;
2639 }
2640
2641 DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2642 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2643
2644 // Disequality is a symmetric relation, so if we mark A as disequal to B,
2645 // we should also mark B as disequalt to A.
2646 if (!addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, *this,
2647 Other) ||
2648 !addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, Other,
2649 *this))
2650 return nullptr;
2651
2652 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2653 "a state with infeasible constraints");
2654
2655 State = State->set<DisequalityMap>(DisequalityInfo);
2656 State = State->set<ConstraintRange>(Constraints);
2657
2658 return State;
2659}
2660
2661inline bool EquivalenceClass::addToDisequalityInfo(
2662 DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
2663 RangeSet::Factory &RF, ProgramStateRef State, EquivalenceClass First,
2664 EquivalenceClass Second) {
2665
2666 // 1. Get all of the required factories.
2667 DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>();
2668 ClassSet::Factory &CF = State->get_context<ClassSet>();
2669 ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
2670
2671 // 2. Add Second to the set of classes disequal to First.
2672 const ClassSet *CurrentSet = Info.lookup(First);
2673 ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet();
2674 NewSet = CF.add(NewSet, Second);
2675
2676 Info = F.add(Info, First, NewSet);
2677
2678 // 3. If Second is known to be a constant, we can delete this point
2679 // from the constraint asociated with First.
2680 //
2681 // So, if Second == 10, it means that First != 10.
2682 // At the same time, the same logic does not apply to ranges.
2683 if (const RangeSet *SecondConstraint = Constraints.lookup(Second))
2684 if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) {
2685 SymbolRangeMap DiscardedCache;
2686 RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange(
2687 RF, State, First.getRepresentativeSymbol(), DiscardedCache);
2688
2689 FirstConstraint = RF.deletePoint(FirstConstraint, *Point);
2690
2691 // If the First class is about to be constrained with an empty
2692 // range-set, the state is infeasible.
2693 if (FirstConstraint.isEmpty())
2694 return false;
2695
2696 Constraints = CRF.add(Constraints, First, FirstConstraint);
2697 }
2698
2699 return true;
2700}
2701
2702inline std::optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2703 SymbolRef FirstSym,
2704 SymbolRef SecondSym) {
2705 return EquivalenceClass::areEqual(State, find(State, FirstSym),
2706 find(State, SecondSym));
2707}
2708
2709inline std::optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2710 EquivalenceClass First,
2711 EquivalenceClass Second) {
2712 // The same equivalence class => symbols are equal.
2713 if (First == Second)
2714 return true;
2715
2716 // Let's check if we know anything about these two classes being not equal to
2717 // each other.
2718 ClassSet DisequalToFirst = First.getDisequalClasses(State);
2719 if (DisequalToFirst.contains(Second))
2720 return false;
2721
2722 // It is not clear.
2723 return std::nullopt;
2724}
2725
2726[[nodiscard]] ProgramStateRef
2727EquivalenceClass::removeMember(ProgramStateRef State, const SymbolRef Old) {
2728
2729 SymbolSet ClsMembers = getClassMembers(State);
2730 assert(ClsMembers.contains(Old));
2731
2732 // Remove `Old`'s Class->Sym relation.
2733 SymbolSet::Factory &F = getMembersFactory(State);
2734 ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2735 ClsMembers = F.remove(ClsMembers, Old);
2736 // Ensure another precondition of the removeMember function (we can check
2737 // this only with isEmpty, thus we have to do the remove first).
2738 assert(!ClsMembers.isEmpty() &&
2739 "Class should have had at least two members before member removal");
2740 // Overwrite the existing members assigned to this class.
2741 ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2742 ClassMembersMap = EMFactory.add(ClassMembersMap, *this, ClsMembers);
2743 State = State->set<ClassMembers>(ClassMembersMap);
2744
2745 // Remove `Old`'s Sym->Class relation.
2746 ClassMapTy Classes = State->get<ClassMap>();
2747 ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
2748 Classes = CMF.remove(Classes, Old);
2749 State = State->set<ClassMap>(Classes);
2750
2751 return State;
2752}
2753
2754// Re-evaluate an SVal with top-level `State->assume` logic.
2755[[nodiscard]] static ProgramStateRef
2756reAssume(ProgramStateRef State, const RangeSet *Constraint, SVal TheValue) {
2757 if (!Constraint)
2758 return State;
2759
2760 const auto DefinedVal = TheValue.castAs<DefinedSVal>();
2761
2762 // If the SVal is 0, we can simply interpret that as `false`.
2763 if (Constraint->encodesFalseRange())
2764 return State->assume(DefinedVal, false);
2765
2766 // If the constraint does not encode 0 then we can interpret that as `true`
2767 // AND as a Range(Set).
2768 if (Constraint->encodesTrueRange()) {
2769 State = State->assume(DefinedVal, true);
2770 if (!State)
2771 return nullptr;
2772 // Fall through, re-assume based on the range values as well.
2773 }
2774 // Overestimate the individual Ranges with the RangeSet' lowest and
2775 // highest values.
2776 return State->assumeInclusiveRange(DefinedVal, Constraint->getMinValue(),
2777 Constraint->getMaxValue(), true);
2778}
2779
2780// Iterate over all symbols and try to simplify them. Once a symbol is
2781// simplified then we check if we can merge the simplified symbol's equivalence
2782// class to this class. This way, we simplify not just the symbols but the
2783// classes as well: we strive to keep the number of the classes to be the
2784// absolute minimum.
2785[[nodiscard]] ProgramStateRef
2786EquivalenceClass::simplify(SValBuilder &SVB, RangeSet::Factory &F,
2787 ProgramStateRef State, EquivalenceClass Class) {
2788 SymbolSet ClassMembers = Class.getClassMembers(State);
2789 for (const SymbolRef &MemberSym : ClassMembers) {
2790
2791 const SVal SimplifiedMemberVal = simplifyToSVal(State, MemberSym);
2792 const SymbolRef SimplifiedMemberSym = SimplifiedMemberVal.getAsSymbol();
2793
2794 // The symbol is collapsed to a constant, check if the current State is
2795 // still feasible.
2796 if (const auto CI = SimplifiedMemberVal.getAs<nonloc::ConcreteInt>()) {
2797 const llvm::APSInt &SV = CI->getValue();
2798 const RangeSet *ClassConstraint = getConstraint(State, Class);
2799 // We have found a contradiction.
2800 if (ClassConstraint && !ClassConstraint->contains(SV))
2801 return nullptr;
2802 }
2803
2804 if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) {
2805 // The simplified symbol should be the member of the original Class,
2806 // however, it might be in another existing class at the moment. We
2807 // have to merge these classes.
2808 ProgramStateRef OldState = State;
2809 State = merge(F, State, MemberSym, SimplifiedMemberSym);
2810 if (!State)
2811 return nullptr;
2812 // No state change, no merge happened actually.
2813 if (OldState == State)
2814 continue;
2815
2816 // Be aware that `SimplifiedMemberSym` might refer to an already dead
2817 // symbol. In that case, the eqclass of that might not be the same as the
2818 // eqclass of `MemberSym`. This is because the dead symbols are not
2819 // preserved in the `ClassMap`, hence
2820 // `find(State, SimplifiedMemberSym)` will result in a trivial eqclass
2821 // compared to the eqclass of `MemberSym`.
2822 // These eqclasses should be the same if `SimplifiedMemberSym` is alive.
2823 // --> assert(find(State, MemberSym) == find(State, SimplifiedMemberSym))
2824 //
2825 // Note that `MemberSym` must be alive here since that is from the
2826 // `ClassMembers` where all the symbols are alive.
2827
2828 // Remove the old and more complex symbol.
2829 State = find(State, MemberSym).removeMember(State, MemberSym);
2830
2831 // Query the class constraint again b/c that may have changed during the
2832 // merge above.
2833 const RangeSet *ClassConstraint = getConstraint(State, Class);
2834
2835 // Re-evaluate an SVal with top-level `State->assume`, this ignites
2836 // a RECURSIVE algorithm that will reach a FIXPOINT.
2837 //
2838 // About performance and complexity: Let us assume that in a State we
2839 // have N non-trivial equivalence classes and that all constraints and
2840 // disequality info is related to non-trivial classes. In the worst case,
2841 // we can simplify only one symbol of one class in each iteration. The
2842 // number of symbols in one class cannot grow b/c we replace the old
2843 // symbol with the simplified one. Also, the number of the equivalence
2844 // classes can decrease only, b/c the algorithm does a merge operation
2845 // optionally. We need N iterations in this case to reach the fixpoint.
2846 // Thus, the steps needed to be done in the worst case is proportional to
2847 // N*N.
2848 //
2849 // This worst case scenario can be extended to that case when we have
2850 // trivial classes in the constraints and in the disequality map. This
2851 // case can be reduced to the case with a State where there are only
2852 // non-trivial classes. This is because a merge operation on two trivial
2853 // classes results in one non-trivial class.
2854 State = reAssume(State, ClassConstraint, SimplifiedMemberVal);
2855 if (!State)
2856 return nullptr;
2857 }
2858 }
2859 return State;
2860}
2861
2862inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State,
2863 SymbolRef Sym) {
2864 return find(State, Sym).getDisequalClasses(State);
2865}
2866
2867inline ClassSet
2868EquivalenceClass::getDisequalClasses(ProgramStateRef State) const {
2869 return getDisequalClasses(State->get<DisequalityMap>(),
2870 State->get_context<ClassSet>());
2871}
2872
2873inline ClassSet
2874EquivalenceClass::getDisequalClasses(DisequalityMapTy Map,
2875 ClassSet::Factory &Factory) const {
2876 if (const ClassSet *DisequalClasses = Map.lookup(*this))
2877 return *DisequalClasses;
2878
2879 return Factory.getEmptySet();
2880}
2881
2882bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) {
2883 ClassMembersTy Members = State->get<ClassMembers>();
2884
2885 for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) {
2886 for (SymbolRef Member : ClassMembersPair.second) {
2887 // Every member of the class should have a mapping back to the class.
2888 if (find(State, Member) == ClassMembersPair.first) {
2889 continue;
2890 }
2891
2892 return false;
2893 }
2894 }
2895
2896 DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2897 for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) {
2898 EquivalenceClass Class = DisequalityInfo.first;
2899 ClassSet DisequalClasses = DisequalityInfo.second;
2900
2901 // There is no use in keeping empty sets in the map.
2902 if (DisequalClasses.isEmpty())
2903 return false;
2904
2905 // Disequality is symmetrical, i.e. for every Class A and B that A != B,
2906 // B != A should also be true.
2907 for (EquivalenceClass DisequalClass : DisequalClasses) {
2908 const ClassSet *DisequalToDisequalClasses =
2909 Disequalities.lookup(DisequalClass);
2910
2911 // It should be a set of at least one element: Class
2912 if (!DisequalToDisequalClasses ||
2913 !DisequalToDisequalClasses->contains(Class))
2914 return false;
2915 }
2916 }
2917
2918 return true;
2919}
2920
2921//===----------------------------------------------------------------------===//
2922// RangeConstraintManager implementation
2923//===----------------------------------------------------------------------===//
2924
2925bool RangeConstraintManager::canReasonAbout(SVal X) const {
2926 std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
2927 if (SymVal && SymVal->isExpression()) {
2928 const SymExpr *SE = SymVal->getSymbol();
2929
2930 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
2931 switch (SIE->getOpcode()) {
2932 // We don't reason yet about bitwise-constraints on symbolic values.
2933 case BO_And:
2934 case BO_Or:
2935 case BO_Xor:
2936 return false;
2937 // We don't reason yet about these arithmetic constraints on
2938 // symbolic values.
2939 case BO_Mul:
2940 case BO_Div:
2941 case BO_Rem:
2942 case BO_Shl:
2943 case BO_Shr:
2944 return false;
2945 // All other cases.
2946 default:
2947 return true;
2948 }
2949 }
2950
2951 if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
2952 // FIXME: Handle <=> here.
2955 // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
2956 // We've recently started producing Loc <> NonLoc comparisons (that
2957 // result from casts of one of the operands between eg. intptr_t and
2958 // void *), but we can't reason about them yet.
2959 if (Loc::isLocType(SSE->getLHS()->getType())) {
2960 return Loc::isLocType(SSE->getRHS()->getType());
2961 }
2962 }
2963 }
2964
2965 return false;
2966 }
2967
2968 return true;
2969}
2970
2971ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
2972 SymbolRef Sym) {
2973 const RangeSet *Ranges = getConstraint(State, Sym);
2974
2975 // If we don't have any information about this symbol, it's underconstrained.
2976 if (!Ranges)
2977 return ConditionTruthVal();
2978
2979 // If we have a concrete value, see if it's zero.
2980 if (const llvm::APSInt *Value = Ranges->getConcreteValue())
2981 return *Value == 0;
2982
2983 BasicValueFactory &BV = getBasicVals();
2984 APSIntType IntType = BV.getAPSIntType(Sym->getType());
2985 llvm::APSInt Zero = IntType.getZeroValue();
2986
2987 // Check if zero is in the set of possible values.
2988 if (!Ranges->contains(Zero))
2989 return false;
2990
2991 // Zero is a possible value, but it is not the /only/ possible value.
2992 return ConditionTruthVal();
2993}
2994
2995const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
2996 SymbolRef Sym) const {
2997 return getRange(St, Sym).getConcreteValue();
2998}
2999
3000const llvm::APSInt *RangeConstraintManager::getSymMinVal(ProgramStateRef St,
3001 SymbolRef Sym) const {
3002 RangeSet Range = getRange(St, Sym);
3003 return Range.isEmpty() ? nullptr : &Range.getMinValue();
3004}
3005
3006const llvm::APSInt *RangeConstraintManager::getSymMaxVal(ProgramStateRef St,
3007 SymbolRef Sym) const {
3008 RangeSet Range = getRange(St, Sym);
3009 return Range.isEmpty() ? nullptr : &Range.getMaxValue();
3010}
3011
3012//===----------------------------------------------------------------------===//
3013// Remove dead symbols from existing constraints
3014//===----------------------------------------------------------------------===//
3015
3016/// Scan all symbols referenced by the constraints. If the symbol is not alive
3017/// as marked in LSymbols, mark it as dead in DSymbols.
3019RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
3020 SymbolReaper &SymReaper) {
3021 ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
3022 ClassMembersTy NewClassMembersMap = ClassMembersMap;
3023 ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
3024 SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>();
3025
3026 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
3027 ConstraintRangeTy::Factory &ConstraintFactory =
3028 State->get_context<ConstraintRange>();
3029
3030 ClassMapTy Map = State->get<ClassMap>();
3031 ClassMapTy NewMap = Map;
3032 ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>();
3033
3034 DisequalityMapTy Disequalities = State->get<DisequalityMap>();
3035 DisequalityMapTy::Factory &DisequalityFactory =
3036 State->get_context<DisequalityMap>();
3037 ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>();
3038
3039 bool ClassMapChanged = false;
3040 bool MembersMapChanged = false;
3041 bool ConstraintMapChanged = false;
3042 bool DisequalitiesChanged = false;
3043
3044 auto removeDeadClass = [&](EquivalenceClass Class) {
3045 // Remove associated constraint ranges.
3046 Constraints = ConstraintFactory.remove(Constraints, Class);
3047 ConstraintMapChanged = true;
3048
3049 // Update disequality information to not hold any information on the
3050 // removed class.
3051 ClassSet DisequalClasses =
3052 Class.getDisequalClasses(Disequalities, ClassSetFactory);
3053 if (!DisequalClasses.isEmpty()) {
3054 for (EquivalenceClass DisequalClass : DisequalClasses) {
3055 ClassSet DisequalToDisequalSet =
3056 DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory);
3057 // DisequalToDisequalSet is guaranteed to be non-empty for consistent
3058 // disequality info.
3059 assert(!DisequalToDisequalSet.isEmpty());
3060 ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class);
3061
3062 // No need in keeping an empty set.
3063 if (NewSet.isEmpty()) {
3064 Disequalities =
3065 DisequalityFactory.remove(Disequalities, DisequalClass);
3066 } else {
3067 Disequalities =
3068 DisequalityFactory.add(Disequalities, DisequalClass, NewSet);
3069 }
3070 }
3071 // Remove the data for the class
3072 Disequalities = DisequalityFactory.remove(Disequalities, Class);
3073 DisequalitiesChanged = true;
3074 }
3075 };
3076
3077 // 1. Let's see if dead symbols are trivial and have associated constraints.
3078 for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair :
3079 Constraints) {
3080 EquivalenceClass Class = ClassConstraintPair.first;
3081 if (Class.isTriviallyDead(State, SymReaper)) {
3082 // If this class is trivial, we can remove its constraints right away.
3083 removeDeadClass(Class);
3084 }
3085 }
3086
3087 // 2. We don't need to track classes for dead symbols.
3088 NewMap = ClassFactory.filter(
3089 Map, [&](const auto &E) { return !SymReaper.isDead(E.first); });
3090 ClassMapChanged = NewMap != Map;
3091
3092 // 3. Remove dead members from classes and remove dead non-trivial classes
3093 // and their constraints.
3094 for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair :
3095 ClassMembersMap) {
3096 EquivalenceClass Class = ClassMembersPair.first;
3097 SymbolSet LiveMembers = ClassMembersPair.second;
3098 bool MembersChanged = false;
3099
3100 for (SymbolRef Member : ClassMembersPair.second) {
3101 if (SymReaper.isDead(Member)) {
3102 MembersChanged = true;
3103 LiveMembers = SetFactory.remove(LiveMembers, Member);
3104 }
3105 }
3106
3107 // Check if the class changed.
3108 if (!MembersChanged)
3109 continue;
3110
3111 MembersMapChanged = true;
3112
3113 if (LiveMembers.isEmpty()) {
3114 // The class is dead now, we need to wipe it out of the members map...
3115 NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class);
3116
3117 // ...and remove all of its constraints.
3118 removeDeadClass(Class);
3119 } else {
3120 // We need to change the members associated with the class.
3121 NewClassMembersMap =
3122 EMFactory.add(NewClassMembersMap, Class, LiveMembers);
3123 }
3124 }
3125
3126 // 4. Update the state with new maps.
3127 //
3128 // Here we try to be humble and update a map only if it really changed.
3129 if (ClassMapChanged)
3130 State = State->set<ClassMap>(NewMap);
3131
3132 if (MembersMapChanged)
3133 State = State->set<ClassMembers>(NewClassMembersMap);
3134
3135 if (ConstraintMapChanged)
3136 State = State->set<ConstraintRange>(Constraints);
3137
3138 if (DisequalitiesChanged)
3139 State = State->set<DisequalityMap>(Disequalities);
3140
3141 assert(EquivalenceClass::isClassDataConsistent(State));
3142
3143 return State;
3144}
3145
3146RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
3147 SymbolRef Sym) const {
3148 if (RangeCacheState != State) {
3149 RangeCache.clear();
3150 RangeCacheState = State;
3151 }
3152 return SymbolicRangeInferrer::inferRange(F, State, Sym, RangeCache);
3153}
3154
3155ProgramStateRef RangeConstraintManager::setRange(ProgramStateRef State,
3156 SymbolRef Sym,
3157 RangeSet Range) {
3158 return ConstraintAssignor::assign(State, getSValBuilder(), F, Sym, Range);
3159}
3160
3161//===------------------------------------------------------------------------===
3162// assumeSymX methods: protected interface for RangeConstraintManager.
3163//===------------------------------------------------------------------------===
3164
3165// The syntax for ranges below is mathematical, using [x, y] for closed ranges
3166// and (x, y) for open ranges. These ranges are modular, corresponding with
3167// a common treatment of C integer overflow. This means that these methods
3168// do not have to worry about overflow; RangeSet::Intersect can handle such a
3169// "wraparound" range.
3170// As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
3171// UINT_MAX, 0, 1, and 2.
3172
3174RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
3175 const llvm::APSInt &Int,
3176 const llvm::APSInt &Adjustment) {
3177 // Before we do any real work, see if the value can even show up.
3178 APSIntType AdjustmentType(Adjustment);
3179 if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
3180 return St;
3181
3182 llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment;
3183 RangeSet New = getRange(St, Sym);
3184 New = F.deletePoint(New, Point);
3185
3186 return setRange(St, Sym, New);
3187}
3188
3190RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
3191 const llvm::APSInt &Int,
3192 const llvm::APSInt &Adjustment) {
3193 // Before we do any real work, see if the value can even show up.
3194 APSIntType AdjustmentType(Adjustment);
3195 if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
3196 return nullptr;
3197
3198 // [Int-Adjustment, Int-Adjustment]
3199 llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
3200 RangeSet New = getRange(St, Sym);
3201 New = F.intersect(New, AdjInt);
3202
3203 return setRange(St, Sym, New);
3204}
3205
3207RangeConstraintManager::getSymLTRange(ProgramStateRef St, SymbolRef Sym,
3208 const llvm::APSInt &Int,
3209 const llvm::APSInt &Adjustment) const {
3210 // Before we do any real work, see if the value can even show up.
3211 APSIntType AdjustmentType(Adjustment);
3212 switch (AdjustmentType.testInRange(Int, true)) {
3214 return F.getEmptySet();
3216 break;
3218 return getRange(St, Sym);
3219 }
3220
3221 // Special case for Int == Min. This is always false.
3222 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3223 llvm::APSInt Min = AdjustmentType.getMinValue();
3224 if (ComparisonVal == Min)
3225 return F.getEmptySet();
3226
3227 llvm::APSInt Lower = Min - Adjustment;
3228 llvm::APSInt Upper = ComparisonVal - Adjustment;
3229 --Upper;
3230
3231 RangeSet Result = getRange(St, Sym);
3232 return F.intersect(Result, Lower, Upper);
3233}
3234
3236RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
3237 const llvm::APSInt &Int,
3238 const llvm::APSInt &Adjustment) {
3239 RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
3240 return setRange(St, Sym, New);
3241}
3242
3244RangeConstraintManager::getSymGTRange(ProgramStateRef St, SymbolRef Sym,
3245 const llvm::APSInt &Int,
3246 const llvm::APSInt &Adjustment) const {
3247 // Before we do any real work, see if the value can even show up.
3248 APSIntType AdjustmentType(Adjustment);
3249 switch (AdjustmentType.testInRange(Int, true)) {
3251 return getRange(St, Sym);
3253 break;
3255 return F.getEmptySet();
3256 }
3257
3258 // Special case for Int == Max. This is always false.
3259 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3260 llvm::APSInt Max = AdjustmentType.getMaxValue();
3261 if (ComparisonVal == Max)
3262 return F.getEmptySet();
3263
3264 llvm::APSInt Lower = ComparisonVal - Adjustment;
3265 llvm::APSInt Upper = Max - Adjustment;
3266 ++Lower;
3267
3268 RangeSet SymRange = getRange(St, Sym);
3269 return F.intersect(SymRange, Lower, Upper);
3270}
3271
3273RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
3274 const llvm::APSInt &Int,
3275 const llvm::APSInt &Adjustment) {
3276 RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
3277 return setRange(St, Sym, New);
3278}
3279
3281RangeConstraintManager::getSymGERange(ProgramStateRef St, SymbolRef Sym,
3282 const llvm::APSInt &Int,
3283 const llvm::APSInt &Adjustment) const {
3284 // Before we do any real work, see if the value can even show up.
3285 APSIntType AdjustmentType(Adjustment);
3286 switch (AdjustmentType.testInRange(Int, true)) {
3288 return getRange(St, Sym);
3290 break;
3292 return F.getEmptySet();
3293 }
3294
3295 // Special case for Int == Min. This is always feasible.
3296 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3297 llvm::APSInt Min = AdjustmentType.getMinValue();
3298 if (ComparisonVal == Min)
3299 return getRange(St, Sym);
3300
3301 llvm::APSInt Max = AdjustmentType.getMaxValue();
3302 llvm::APSInt Lower = ComparisonVal - Adjustment;
3303 llvm::APSInt Upper = Max - Adjustment;
3304
3305 RangeSet SymRange = getRange(St, Sym);
3306 return F.intersect(SymRange, Lower, Upper);
3307}
3308
3310RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
3311 const llvm::APSInt &Int,
3312 const llvm::APSInt &Adjustment) {
3313 RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
3314 return setRange(St, Sym, New);
3315}
3316
3318RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS,
3319 const llvm::APSInt &Int,
3320 const llvm::APSInt &Adjustment) const {
3321 // Before we do any real work, see if the value can even show up.
3322 APSIntType AdjustmentType(Adjustment);
3323 switch (AdjustmentType.testInRange(Int, true)) {
3325 return F.getEmptySet();
3327 break;
3329 return RS();
3330 }
3331
3332 // Special case for Int == Max. This is always feasible.
3333 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
3334 llvm::APSInt Max = AdjustmentType.getMaxValue();
3335 if (ComparisonVal == Max)
3336 return RS();
3337
3338 llvm::APSInt Min = AdjustmentType.getMinValue();
3339 llvm::APSInt Lower = Min - Adjustment;
3340 llvm::APSInt Upper = ComparisonVal - Adjustment;
3341
3342 RangeSet Default = RS();
3343 return F.intersect(Default, Lower, Upper);
3344}
3345
3347RangeConstraintManager::getSymLERange(ProgramStateRef St, SymbolRef Sym,
3348 const llvm::APSInt &Int,
3349 const llvm::APSInt &Adjustment) const {
3350 return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
3351}
3352
3354RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
3355 const llvm::APSInt &Int,
3356 const llvm::APSInt &Adjustment) {
3357 RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
3358 return setRange(St, Sym, New);
3359}
3360
3361ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
3362 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
3363 const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
3364 RangeSet New = getSymGERange(State, Sym, From, Adjustment);
3365 if (New.isEmpty())
3366 return nullptr;
3367 RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
3368 return setRange(State, Sym, Out);
3369}
3370
3371ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
3372 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
3373 const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
3374 RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
3375 RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
3376 RangeSet New(F.add(RangeLT, RangeGT));
3377 return setRange(State, Sym, New);
3378}
3379
3380//===----------------------------------------------------------------------===//
3381// Pretty-printing.
3382//===----------------------------------------------------------------------===//
3383
3384void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
3385 const char *NL, unsigned int Space,
3386 bool IsDot) const {
3387 printConstraints(Out, State, NL, Space, IsDot);
3388 printEquivalenceClasses(Out, State, NL, Space, IsDot);
3389 printDisequalities(Out, State, NL, Space, IsDot);
3390}
3391
3392void RangeConstraintManager::printValue(raw_ostream &Out, ProgramStateRef State,
3393 SymbolRef Sym) {
3394 const RangeSet RS = getRange(State, Sym);
3395 if (RS.isEmpty()) {
3396 Out << "<empty rangeset>";
3397 return;
3398 }
3399 Out << RS.getBitWidth() << (RS.isUnsigned() ? "u:" : "s:");
3400 RS.dump(Out);
3401}
3402
3403static std::string toString(const SymbolRef &Sym) {
3404 std::string S;
3405 llvm::raw_string_ostream O(S);
3406 Sym->dumpToStream(O);
3407 return S;
3408}
3409
3410void RangeConstraintManager::printConstraints(raw_ostream &Out,
3411 ProgramStateRef State,
3412 const char *NL,
3413 unsigned int Space,
3414 bool IsDot) const {
3415 ConstraintRangeTy Constraints = State->get<ConstraintRange>();
3416
3417 Indent(Out, Space, IsDot) << "\"constraints\": ";
3418 if (Constraints.isEmpty()) {
3419 Out << "null," << NL;
3420 return;
3421 }
3422
3423 std::map<std::string, RangeSet> OrderedConstraints;
3424 for (std::pair<EquivalenceClass, RangeSet> P : Constraints) {
3425 SymbolSet ClassMembers = P.first.getClassMembers(State);
3426 for (const SymbolRef &ClassMember : ClassMembers) {
3427 bool insertion_took_place;
3428 std::tie(std::ignore, insertion_took_place) =
3429 OrderedConstraints.insert({toString(ClassMember), P.second});
3430 assert(insertion_took_place &&
3431 "two symbols should not have the same dump");
3432 }
3433 }
3434
3435 ++Space;
3436 Out << '[' << NL;
3437 bool First = true;
3438 for (std::pair<std::string, RangeSet> P : OrderedConstraints) {
3439 if (First) {
3440 First = false;
3441 } else {
3442 Out << ',';
3443 Out << NL;
3444 }
3445 Indent(Out, Space, IsDot)
3446 << "{ \"symbol\": \"" << P.first << "\", \"range\": \"";
3447 P.second.dump(Out);
3448 Out << "\" }";
3449 }
3450 Out << NL;
3451
3452 --Space;
3453 Indent(Out, Space, IsDot) << "]," << NL;
3454}
3455
3456static std::string toString(ProgramStateRef State, EquivalenceClass Class) {
3457 SymbolSet ClassMembers = Class.getClassMembers(State);
3458 llvm::SmallVector<SymbolRef, 8> ClassMembersSorted(ClassMembers.begin(),
3459 ClassMembers.end());
3460 llvm::sort(ClassMembersSorted,
3461 [](const SymbolRef &LHS, const SymbolRef &RHS) {
3462 return toString(LHS) < toString(RHS);
3463 });
3464
3465 bool FirstMember = true;
3466
3467 std::string Str;
3468 llvm::raw_string_ostream Out(Str);
3469 Out << "[ ";
3470 for (SymbolRef ClassMember : ClassMembersSorted) {
3471 if (FirstMember)
3472 FirstMember = false;
3473 else
3474 Out << ", ";
3475 Out << "\"" << ClassMember << "\"";
3476 }
3477 Out << " ]";
3478 return Str;
3479}
3480
3481void RangeConstraintManager::printEquivalenceClasses(raw_ostream &Out,
3482 ProgramStateRef State,
3483 const char *NL,
3484 unsigned int Space,
3485 bool IsDot) const {
3486 ClassMembersTy Members = State->get<ClassMembers>();
3487
3488 Indent(Out, Space, IsDot) << "\"equivalence_classes\": ";
3489 if (Members.isEmpty()) {
3490 Out << "null," << NL;
3491 return;
3492 }
3493
3494 std::set<std::string> MembersStr;
3495 for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members)
3496 MembersStr.insert(toString(State, ClassToSymbolSet.first));
3497
3498 ++Space;
3499 Out << '[' << NL;
3500 bool FirstClass = true;
3501 for (const std::string &Str : MembersStr) {
3502 if (FirstClass) {
3503 FirstClass = false;
3504 } else {
3505 Out << ',';
3506 Out << NL;
3507 }
3508 Indent(Out, Space, IsDot);
3509 Out << Str;
3510 }
3511 Out << NL;
3512
3513 --Space;
3514 Indent(Out, Space, IsDot) << "]," << NL;
3515}
3516
3517void RangeConstraintManager::printDisequalities(raw_ostream &Out,
3518 ProgramStateRef State,
3519 const char *NL,
3520 unsigned int Space,
3521 bool IsDot) const {
3522 DisequalityMapTy Disequalities = State->get<DisequalityMap>();
3523
3524 Indent(Out, Space, IsDot) << "\"disequality_info\": ";
3525 if (Disequalities.isEmpty()) {
3526 Out << "null," << NL;
3527 return;
3528 }
3529
3530 // Transform the disequality info to an ordered map of
3531 // [string -> (ordered set of strings)]
3532 using EqClassesStrTy = std::set<std::string>;
3533 using DisequalityInfoStrTy = std::map<std::string, EqClassesStrTy>;
3534 DisequalityInfoStrTy DisequalityInfoStr;
3535 for (std::pair<EquivalenceClass, ClassSet> ClassToDisEqSet : Disequalities) {
3536 EquivalenceClass Class = ClassToDisEqSet.first;
3537 ClassSet DisequalClasses = ClassToDisEqSet.second;
3538 EqClassesStrTy MembersStr;
3539 for (EquivalenceClass DisEqClass : DisequalClasses)
3540 MembersStr.insert(toString(State, DisEqClass));
3541 DisequalityInfoStr.insert({toString(State, Class), MembersStr});
3542 }
3543
3544 ++Space;
3545 Out << '[' << NL;
3546 bool FirstClass = true;
3547 for (std::pair<std::string, EqClassesStrTy> ClassToDisEqSet :
3548 DisequalityInfoStr) {
3549 const std::string &Class = ClassToDisEqSet.first;
3550 if (FirstClass) {
3551 FirstClass = false;
3552 } else {
3553 Out << ',';
3554 Out << NL;
3555 }
3556 Indent(Out, Space, IsDot) << "{" << NL;
3557 unsigned int DisEqSpace = Space + 1;
3558 Indent(Out, DisEqSpace, IsDot) << "\"class\": ";
3559 Out << Class;
3560 const EqClassesStrTy &DisequalClasses = ClassToDisEqSet.second;
3561 if (!DisequalClasses.empty()) {
3562 Out << "," << NL;
3563 Indent(Out, DisEqSpace, IsDot) << "\"disequal_to\": [" << NL;
3564 unsigned int DisEqClassSpace = DisEqSpace + 1;
3565 Indent(Out, DisEqClassSpace, IsDot);
3566 bool FirstDisEqClass = true;
3567 for (const std::string &DisEqClass : DisequalClasses) {
3568 if (FirstDisEqClass) {
3569 FirstDisEqClass = false;
3570 } else {
3571 Out << ',' << NL;
3572 Indent(Out, DisEqClassSpace, IsDot);
3573 }
3574 Out << DisEqClass;
3575 }
3576 Out << "]" << NL;
3577 }
3578 Indent(Out, Space, IsDot) << "}";
3579 }
3580 Out << NL;
3581
3582 --Space;
3583 Indent(Out, Space, IsDot) << "]," << NL;
3584}
#define V(N, I)
static bool isTrivial(ASTContext &Ctx, const Expr *E)
Checks if the expression is constant or does not have non-trivial function calls.
llvm::APSInt APSInt
Definition Compiler.cpp:26
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
llvm::MachO::SymbolSet SymbolSet
Definition MachO.h:44
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set type Name and registers the factory for such sets in the program state,...
#define CONSTRAINT_DISPATCH(Id)
static void swapIterators(T &First, T &FirstEnd, T &Second, T &SecondEnd)
static ProgramStateRef reAssume(ProgramStateRef State, const RangeSet *Constraint, SVal TheValue)
#define DEFAULT_ASSIGN(Id)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static CharSourceRange getRange(const CharSourceRange &EditRange, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeMacroExpansion)
TypePropertyCache< Private > Cache
Definition Type.cpp:5115
static BinaryOperatorKind getOpFromIndex(size_t Index)
constexpr size_t getCmpOpCount() const
TriStateKind getCmpOpState(BinaryOperatorKind CurrentOP, BinaryOperatorKind QueriedOP) const
TriStateKind getCmpOpStateForUnknownX2(BinaryOperatorKind CurrentOP) const
bool isComparisonOp() const
Definition Expr.h:4208
bool isRelationalOp() const
Definition Expr.h:4202
static Opcode negateComparisonOp(Opcode Opc)
Definition Expr.h:4213
static Opcode reverseComparisonOp(Opcode Opc)
Definition Expr.h:4226
bool isEqualityOp() const
Definition Expr.h:4205
BinaryOperatorKind Opcode
Definition Expr.h:4112
A (possibly-)qualified type.
Definition TypeBase.h:938
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2433
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2501
bool isReferenceType() const
Definition TypeBase.h:8941
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9432
A record of the "type" of an APSInt, used for conversions.
Definition APSIntType.h:19
bool isUnsigned() const
Definition APSIntType.h:31
llvm::APSInt getZeroValue() const LLVM_READONLY
Returns an all-zero value for this type.
Definition APSIntType.h:55
RangeTestResultKind
Used to classify whether a value is representable using this type.
Definition APSIntType.h:76
@ RTR_Within
Value is representable using this type.
Definition APSIntType.h:78
@ RTR_Below
Value is less than the minimum representable value.
Definition APSIntType.h:77
@ RTR_Above
Value is greater than the maximum representable value.
Definition APSIntType.h:79
uint32_t getBitWidth() const
Definition APSIntType.h:30
RangeTestResultKind testInRange(const llvm::APSInt &Val, bool AllowMixedSign) const LLVM_READONLY
Tests whether a given value is losslessly representable using this type.
void apply(llvm::APSInt &Value) const
Convert a given APSInt, in place, to match this type.
Definition APSIntType.h:37
llvm::APSInt getMinValue() const LLVM_READONLY
Returns the minimum value for this type.
Definition APSIntType.h:60
llvm::APSInt convert(const llvm::APSInt &Value) const LLVM_READONLY
Convert and return a new APSInt with the given value, but this type's bit width and signedness.
Definition APSIntType.h:48
llvm::APSInt getValue(uint64_t RawValue) const LLVM_READONLY
Definition APSIntType.h:69
APSIntType getAPSIntType(QualType T) const
Returns the type of the APSInt used to store values of the given QualType.
QualType getType() const override
BinaryOperator::Opcode getOpcode() const
static bool isLocType(QualType T)
Definition SVals.h:265
RangeSet unite(RangeSet LHS, RangeSet RHS)
Create a new set which is a union of two given ranges.
RangeSet negate(RangeSet What)
Negate the given range set.
RangeSet intersect(RangeSet LHS, RangeSet RHS)
Intersect the given range sets.
RangeSet deletePoint(RangeSet From, const llvm::APSInt &Point)
Delete the given point from the range set.
RangeSet getRangeSet(Range Origin)
Create a new set with just one range.
RangeSet add(RangeSet LHS, RangeSet RHS)
Create a new set with all ranges from both LHS and RHS.
RangeSet castTo(RangeSet What, APSIntType Ty)
Performs promotions, truncations and conversions of the given set.
RangeSet getFullRangeSet(APSIntType Ty)
Create a set with all values of the given type.
persistent set of non-overlapping ranges.
const_iterator end() const
const llvm::APSInt & getMaxValue() const
Get the maximal value covered by the ranges in the set.
RangeSet(const RangeSet &)=default
bool encodesTrueRange() const
Test if the range doesn't contain zero.
bool encodesFalseRange() const
Test if the range is the [0,0] range.
const_iterator begin() const
const llvm::APSInt & getMinValue() const
Get the minimal value covered by the ranges in the set.
ImplType::const_iterator const_iterator
bool contains(llvm::APSInt Point) const
Test whether the given point is contained by any of the ranges.
void dump(raw_ostream &OS) const
const llvm::APSInt * getConcreteValue() const
getConcreteValue - If a symbol is constrained to equal a specific integer constant then this method r...
A Range represents the closed range [from, to].
const llvm::APSInt & From() const
bool Includes(const llvm::APSInt &Point) const
const llvm::APSInt & To() const
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition SVals.cpp:103
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
Symbolic value.
Definition SymExpr.h:33
virtual void dumpToStream(raw_ostream &os) const
Definition SymExpr.h:86
virtual QualType getType() const =0
Kind getKind() const
Definition SymExpr.h:74
const SymExprT * acquire(Args &&...args)
Create or retrieve a SymExpr of type SymExprT for the given arguments.
A class responsible for cleaning up unused symbols.
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
QualType getType() const override
UnaryOperator::Opcode getOpcode() const
const SymExpr * getOperand() const
SVal simplifyToSVal(ProgramStateRef State, SymbolRef Sym)
Try to simplify a given symbolic expression's associated SVal based on the constraints in State.
llvm::ImmutableMap< SymbolRef, RangeSet > ConstraintMap
BinarySymExprImpl< APSIntPtr, const SymExpr *, SymExpr::Kind::IntSymExprKind > IntSymExpr
Represents a symbolic expression like 3 - 'x'.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
BinarySymExprImpl< const SymExpr *, const SymExpr *, SymExpr::Kind::SymSymExprKind > SymSymExpr
Represents a symbolic expression like 'x' + 'y'.
BinarySymExprImpl< const SymExpr *, APSIntPtr, SymExpr::Kind::SymIntExprKind > SymIntExpr
Represents a symbolic expression like 'x' + 3.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ CF
Indicates that the tracked object is a CF object.
std::unique_ptr< ConstraintManager > CreateRangeConstraintManager(ProgramStateManager &statemgr, ExprEngine *exprengine)
ConstraintMap getConstraintMap(ProgramStateRef State)
bool Const(InterpState &S, const T &Arg)
Definition Interp.h:1569
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool operator!=(CanQual< T > x, CanQual< U > y)
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6259
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
#define false
Definition stdbool.h:26