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 
14 #include "clang/Basic/JsonSupport.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/ImmutableSet.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <iterator>
29 
30 using namespace clang;
31 using namespace ento;
32 
33 // This class can be extended with other tables which will help to reason
34 // about ranges more precisely.
35 class OperatorRelationsTable {
36   static_assert(BO_LT < BO_GT && BO_GT < BO_LE && BO_LE < BO_GE &&
37                     BO_GE < BO_EQ && BO_EQ < BO_NE,
38                 "This class relies on operators order. Rework it otherwise.");
39 
40 public:
41   enum TriStateKind {
42     False = 0,
43     True,
44     Unknown,
45   };
46 
47 private:
48   // CmpOpTable holds states which represent the corresponding range for
49   // branching an exploded graph. We can reason about the branch if there is
50   // a previously known fact of the existence of a comparison expression with
51   // operands used in the current expression.
52   // E.g. assuming (x < y) is true that means (x != y) is surely true.
53   // if (x previous_operation y)  // <    | !=      | >
54   //   if (x operation y)         // !=   | >       | <
55   //     tristate                 // True | Unknown | False
56   //
57   // CmpOpTable represents next:
58   // __|< |> |<=|>=|==|!=|UnknownX2|
59   // < |1 |0 |* |0 |0 |* |1        |
60   // > |0 |1 |0 |* |0 |* |1        |
61   // <=|1 |0 |1 |* |1 |* |0        |
62   // >=|0 |1 |* |1 |1 |* |0        |
63   // ==|0 |0 |* |* |1 |0 |1        |
64   // !=|1 |1 |* |* |0 |1 |0        |
65   //
66   // Columns stands for a previous operator.
67   // Rows stands for a current operator.
68   // Each row has exactly two `Unknown` cases.
69   // UnknownX2 means that both `Unknown` previous operators are met in code,
70   // and there is a special column for that, for example:
71   // if (x >= y)
72   //   if (x != y)
73   //     if (x <= y)
74   //       False only
75   static constexpr size_t CmpOpCount = BO_NE - BO_LT + 1;
76   const TriStateKind CmpOpTable[CmpOpCount][CmpOpCount + 1] = {
77       // <      >      <=     >=     ==     !=    UnknownX2
78       {True, False, Unknown, False, False, Unknown, True}, // <
79       {False, True, False, Unknown, False, Unknown, True}, // >
80       {True, False, True, Unknown, True, Unknown, False},  // <=
81       {False, True, Unknown, True, True, Unknown, False},  // >=
82       {False, False, Unknown, Unknown, True, False, True}, // ==
83       {True, True, Unknown, Unknown, False, True, False},  // !=
84   };
85 
86   static size_t getIndexFromOp(BinaryOperatorKind OP) {
87     return static_cast<size_t>(OP - BO_LT);
88   }
89 
90 public:
91   constexpr size_t getCmpOpCount() const { return CmpOpCount; }
92 
93   static BinaryOperatorKind getOpFromIndex(size_t Index) {
94     return static_cast<BinaryOperatorKind>(Index + BO_LT);
95   }
96 
97   TriStateKind getCmpOpState(BinaryOperatorKind CurrentOP,
98                              BinaryOperatorKind QueriedOP) const {
99     return CmpOpTable[getIndexFromOp(CurrentOP)][getIndexFromOp(QueriedOP)];
100   }
101 
102   TriStateKind getCmpOpStateForUnknownX2(BinaryOperatorKind CurrentOP) const {
103     return CmpOpTable[getIndexFromOp(CurrentOP)][CmpOpCount];
104   }
105 };
106 
107 //===----------------------------------------------------------------------===//
108 //                           RangeSet implementation
109 //===----------------------------------------------------------------------===//
110 
111 RangeSet::ContainerType RangeSet::Factory::EmptySet{};
112 
113 RangeSet RangeSet::Factory::add(RangeSet Original, Range Element) {
114   ContainerType Result;
115   Result.reserve(Original.size() + 1);
116 
117   const_iterator Lower = llvm::lower_bound(Original, Element);
118   Result.insert(Result.end(), Original.begin(), Lower);
119   Result.push_back(Element);
120   Result.insert(Result.end(), Lower, Original.end());
121 
122   return makePersistent(std::move(Result));
123 }
124 
125 RangeSet RangeSet::Factory::add(RangeSet Original, const llvm::APSInt &Point) {
126   return add(Original, Range(Point));
127 }
128 
129 RangeSet RangeSet::Factory::getRangeSet(Range From) {
130   ContainerType Result;
131   Result.push_back(From);
132   return makePersistent(std::move(Result));
133 }
134 
135 RangeSet RangeSet::Factory::makePersistent(ContainerType &&From) {
136   llvm::FoldingSetNodeID ID;
137   void *InsertPos;
138 
139   From.Profile(ID);
140   ContainerType *Result = Cache.FindNodeOrInsertPos(ID, InsertPos);
141 
142   if (!Result) {
143     // It is cheaper to fully construct the resulting range on stack
144     // and move it to the freshly allocated buffer if we don't have
145     // a set like this already.
146     Result = construct(std::move(From));
147     Cache.InsertNode(Result, InsertPos);
148   }
149 
150   return Result;
151 }
152 
153 RangeSet::ContainerType *RangeSet::Factory::construct(ContainerType &&From) {
154   void *Buffer = Arena.Allocate();
155   return new (Buffer) ContainerType(std::move(From));
156 }
157 
158 RangeSet RangeSet::Factory::add(RangeSet LHS, RangeSet RHS) {
159   ContainerType Result;
160   std::merge(LHS.begin(), LHS.end(), RHS.begin(), RHS.end(),
161              std::back_inserter(Result));
162   return makePersistent(std::move(Result));
163 }
164 
165 const llvm::APSInt &RangeSet::getMinValue() const {
166   assert(!isEmpty());
167   return begin()->From();
168 }
169 
170 const llvm::APSInt &RangeSet::getMaxValue() const {
171   assert(!isEmpty());
172   return std::prev(end())->To();
173 }
174 
175 bool RangeSet::containsImpl(llvm::APSInt &Point) const {
176   if (isEmpty() || !pin(Point))
177     return false;
178 
179   Range Dummy(Point);
180   const_iterator It = llvm::upper_bound(*this, Dummy);
181   if (It == begin())
182     return false;
183 
184   return std::prev(It)->Includes(Point);
185 }
186 
187 bool RangeSet::pin(llvm::APSInt &Point) const {
188   APSIntType Type(getMinValue());
189   if (Type.testInRange(Point, true) != APSIntType::RTR_Within)
190     return false;
191 
192   Type.apply(Point);
193   return true;
194 }
195 
196 bool RangeSet::pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
197   // This function has nine cases, the cartesian product of range-testing
198   // both the upper and lower bounds against the symbol's type.
199   // Each case requires a different pinning operation.
200   // The function returns false if the described range is entirely outside
201   // the range of values for the associated symbol.
202   APSIntType Type(getMinValue());
203   APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
204   APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
205 
206   switch (LowerTest) {
207   case APSIntType::RTR_Below:
208     switch (UpperTest) {
209     case APSIntType::RTR_Below:
210       // The entire range is outside the symbol's set of possible values.
211       // If this is a conventionally-ordered range, the state is infeasible.
212       if (Lower <= Upper)
213         return false;
214 
215       // However, if the range wraps around, it spans all possible values.
216       Lower = Type.getMinValue();
217       Upper = Type.getMaxValue();
218       break;
219     case APSIntType::RTR_Within:
220       // The range starts below what's possible but ends within it. Pin.
221       Lower = Type.getMinValue();
222       Type.apply(Upper);
223       break;
224     case APSIntType::RTR_Above:
225       // The range spans all possible values for the symbol. Pin.
226       Lower = Type.getMinValue();
227       Upper = Type.getMaxValue();
228       break;
229     }
230     break;
231   case APSIntType::RTR_Within:
232     switch (UpperTest) {
233     case APSIntType::RTR_Below:
234       // The range wraps around, but all lower values are not possible.
235       Type.apply(Lower);
236       Upper = Type.getMaxValue();
237       break;
238     case APSIntType::RTR_Within:
239       // The range may or may not wrap around, but both limits are valid.
240       Type.apply(Lower);
241       Type.apply(Upper);
242       break;
243     case APSIntType::RTR_Above:
244       // The range starts within what's possible but ends above it. Pin.
245       Type.apply(Lower);
246       Upper = Type.getMaxValue();
247       break;
248     }
249     break;
250   case APSIntType::RTR_Above:
251     switch (UpperTest) {
252     case APSIntType::RTR_Below:
253       // The range wraps but is outside the symbol's set of possible values.
254       return false;
255     case APSIntType::RTR_Within:
256       // The range starts above what's possible but ends within it (wrap).
257       Lower = Type.getMinValue();
258       Type.apply(Upper);
259       break;
260     case APSIntType::RTR_Above:
261       // The entire range is outside the symbol's set of possible values.
262       // If this is a conventionally-ordered range, the state is infeasible.
263       if (Lower <= Upper)
264         return false;
265 
266       // However, if the range wraps around, it spans all possible values.
267       Lower = Type.getMinValue();
268       Upper = Type.getMaxValue();
269       break;
270     }
271     break;
272   }
273 
274   return true;
275 }
276 
277 RangeSet RangeSet::Factory::intersect(RangeSet What, llvm::APSInt Lower,
278                                       llvm::APSInt Upper) {
279   if (What.isEmpty() || !What.pin(Lower, Upper))
280     return getEmptySet();
281 
282   ContainerType DummyContainer;
283 
284   if (Lower <= Upper) {
285     // [Lower, Upper] is a regular range.
286     //
287     // Shortcut: check that there is even a possibility of the intersection
288     //           by checking the two following situations:
289     //
290     //               <---[  What  ]---[------]------>
291     //                              Lower  Upper
292     //                            -or-
293     //               <----[------]----[  What  ]---->
294     //                  Lower  Upper
295     if (What.getMaxValue() < Lower || Upper < What.getMinValue())
296       return getEmptySet();
297 
298     DummyContainer.push_back(
299         Range(ValueFactory.getValue(Lower), ValueFactory.getValue(Upper)));
300   } else {
301     // [Lower, Upper] is an inverted range, i.e. [MIN, Upper] U [Lower, MAX]
302     //
303     // Shortcut: check that there is even a possibility of the intersection
304     //           by checking the following situation:
305     //
306     //               <------]---[  What  ]---[------>
307     //                    Upper             Lower
308     if (What.getMaxValue() < Lower && Upper < What.getMinValue())
309       return getEmptySet();
310 
311     DummyContainer.push_back(
312         Range(ValueFactory.getMinValue(Upper), ValueFactory.getValue(Upper)));
313     DummyContainer.push_back(
314         Range(ValueFactory.getValue(Lower), ValueFactory.getMaxValue(Lower)));
315   }
316 
317   return intersect(*What.Impl, DummyContainer);
318 }
319 
320 RangeSet RangeSet::Factory::intersect(const RangeSet::ContainerType &LHS,
321                                       const RangeSet::ContainerType &RHS) {
322   ContainerType Result;
323   Result.reserve(std::max(LHS.size(), RHS.size()));
324 
325   const_iterator First = LHS.begin(), Second = RHS.begin(),
326                  FirstEnd = LHS.end(), SecondEnd = RHS.end();
327 
328   const auto SwapIterators = [&First, &FirstEnd, &Second, &SecondEnd]() {
329     std::swap(First, Second);
330     std::swap(FirstEnd, SecondEnd);
331   };
332 
333   // If we ran out of ranges in one set, but not in the other,
334   // it means that those elements are definitely not in the
335   // intersection.
336   while (First != FirstEnd && Second != SecondEnd) {
337     // We want to keep the following invariant at all times:
338     //
339     //    ----[ First ---------------------->
340     //    --------[ Second ----------------->
341     if (Second->From() < First->From())
342       SwapIterators();
343 
344     // Loop where the invariant holds:
345     do {
346       // Check for the following situation:
347       //
348       //    ----[ First ]--------------------->
349       //    ---------------[ Second ]--------->
350       //
351       // which means that...
352       if (Second->From() > First->To()) {
353         // ...First is not in the intersection.
354         //
355         // We should move on to the next range after First and break out of the
356         // loop because the invariant might not be true.
357         ++First;
358         break;
359       }
360 
361       // We have a guaranteed intersection at this point!
362       // And this is the current situation:
363       //
364       //    ----[   First   ]----------------->
365       //    -------[ Second ------------------>
366       //
367       // Additionally, it definitely starts with Second->From().
368       const llvm::APSInt &IntersectionStart = Second->From();
369 
370       // It is important to know which of the two ranges' ends
371       // is greater.  That "longer" range might have some other
372       // intersections, while the "shorter" range might not.
373       if (Second->To() > First->To()) {
374         // Here we make a decision to keep First as the "longer"
375         // range.
376         SwapIterators();
377       }
378 
379       // At this point, we have the following situation:
380       //
381       //    ---- First      ]-------------------->
382       //    ---- Second ]--[  Second+1 ---------->
383       //
384       // We don't know the relationship between First->From and
385       // Second->From and we don't know whether Second+1 intersects
386       // with First.
387       //
388       // However, we know that [IntersectionStart, Second->To] is
389       // a part of the intersection...
390       Result.push_back(Range(IntersectionStart, Second->To()));
391       ++Second;
392       // ...and that the invariant will hold for a valid Second+1
393       // because First->From <= Second->To < (Second+1)->From.
394     } while (Second != SecondEnd);
395   }
396 
397   if (Result.empty())
398     return getEmptySet();
399 
400   return makePersistent(std::move(Result));
401 }
402 
403 RangeSet RangeSet::Factory::intersect(RangeSet LHS, RangeSet RHS) {
404   // Shortcut: let's see if the intersection is even possible.
405   if (LHS.isEmpty() || RHS.isEmpty() || LHS.getMaxValue() < RHS.getMinValue() ||
406       RHS.getMaxValue() < LHS.getMinValue())
407     return getEmptySet();
408 
409   return intersect(*LHS.Impl, *RHS.Impl);
410 }
411 
412 RangeSet RangeSet::Factory::intersect(RangeSet LHS, llvm::APSInt Point) {
413   if (LHS.containsImpl(Point))
414     return getRangeSet(ValueFactory.getValue(Point));
415 
416   return getEmptySet();
417 }
418 
419 RangeSet RangeSet::Factory::negate(RangeSet What) {
420   if (What.isEmpty())
421     return getEmptySet();
422 
423   const llvm::APSInt SampleValue = What.getMinValue();
424   const llvm::APSInt &MIN = ValueFactory.getMinValue(SampleValue);
425   const llvm::APSInt &MAX = ValueFactory.getMaxValue(SampleValue);
426 
427   ContainerType Result;
428   Result.reserve(What.size() + (SampleValue == MIN));
429 
430   // Handle a special case for MIN value.
431   const_iterator It = What.begin();
432   const_iterator End = What.end();
433 
434   const llvm::APSInt &From = It->From();
435   const llvm::APSInt &To = It->To();
436 
437   if (From == MIN) {
438     // If the range [From, To] is [MIN, MAX], then result is also [MIN, MAX].
439     if (To == MAX) {
440       return What;
441     }
442 
443     const_iterator Last = std::prev(End);
444 
445     // Try to find and unite the following ranges:
446     // [MIN, MIN] & [MIN + 1, N] => [MIN, N].
447     if (Last->To() == MAX) {
448       // It means that in the original range we have ranges
449       //   [MIN, A], ... , [B, MAX]
450       // And the result should be [MIN, -B], ..., [-A, MAX]
451       Result.emplace_back(MIN, ValueFactory.getValue(-Last->From()));
452       // We already negated Last, so we can skip it.
453       End = Last;
454     } else {
455       // Add a separate range for the lowest value.
456       Result.emplace_back(MIN, MIN);
457     }
458 
459     // Skip adding the second range in case when [From, To] are [MIN, MIN].
460     if (To != MIN) {
461       Result.emplace_back(ValueFactory.getValue(-To), MAX);
462     }
463 
464     // Skip the first range in the loop.
465     ++It;
466   }
467 
468   // Negate all other ranges.
469   for (; It != End; ++It) {
470     // Negate int values.
471     const llvm::APSInt &NewFrom = ValueFactory.getValue(-It->To());
472     const llvm::APSInt &NewTo = ValueFactory.getValue(-It->From());
473 
474     // Add a negated range.
475     Result.emplace_back(NewFrom, NewTo);
476   }
477 
478   llvm::sort(Result);
479   return makePersistent(std::move(Result));
480 }
481 
482 RangeSet RangeSet::Factory::deletePoint(RangeSet From,
483                                         const llvm::APSInt &Point) {
484   if (!From.contains(Point))
485     return From;
486 
487   llvm::APSInt Upper = Point;
488   llvm::APSInt Lower = Point;
489 
490   ++Upper;
491   --Lower;
492 
493   // Notice that the lower bound is greater than the upper bound.
494   return intersect(From, Upper, Lower);
495 }
496 
497 void Range::dump(raw_ostream &OS) const {
498   OS << '[' << toString(From(), 10) << ", " << toString(To(), 10) << ']';
499 }
500 
501 void RangeSet::dump(raw_ostream &OS) const {
502   OS << "{ ";
503   llvm::interleaveComma(*this, OS, [&OS](const Range &R) { R.dump(OS); });
504   OS << " }";
505 }
506 
507 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(SymbolSet, SymbolRef)
508 
509 namespace {
510 class EquivalenceClass;
511 } // end anonymous namespace
512 
513 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMap, SymbolRef, EquivalenceClass)
514 REGISTER_MAP_WITH_PROGRAMSTATE(ClassMembers, EquivalenceClass, SymbolSet)
515 REGISTER_MAP_WITH_PROGRAMSTATE(ConstraintRange, EquivalenceClass, RangeSet)
516 
517 REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(ClassSet, EquivalenceClass)
518 REGISTER_MAP_WITH_PROGRAMSTATE(DisequalityMap, EquivalenceClass, ClassSet)
519 
520 namespace {
521 /// This class encapsulates a set of symbols equal to each other.
522 ///
523 /// The main idea of the approach requiring such classes is in narrowing
524 /// and sharing constraints between symbols within the class.  Also we can
525 /// conclude that there is no practical need in storing constraints for
526 /// every member of the class separately.
527 ///
528 /// Main terminology:
529 ///
530 ///   * "Equivalence class" is an object of this class, which can be efficiently
531 ///     compared to other classes.  It represents the whole class without
532 ///     storing the actual in it.  The members of the class however can be
533 ///     retrieved from the state.
534 ///
535 ///   * "Class members" are the symbols corresponding to the class.  This means
536 ///     that A == B for every member symbols A and B from the class.  Members of
537 ///     each class are stored in the state.
538 ///
539 ///   * "Trivial class" is a class that has and ever had only one same symbol.
540 ///
541 ///   * "Merge operation" merges two classes into one.  It is the main operation
542 ///     to produce non-trivial classes.
543 ///     If, at some point, we can assume that two symbols from two distinct
544 ///     classes are equal, we can merge these classes.
545 class EquivalenceClass : public llvm::FoldingSetNode {
546 public:
547   /// Find equivalence class for the given symbol in the given state.
548   LLVM_NODISCARD static inline EquivalenceClass find(ProgramStateRef State,
549                                                      SymbolRef Sym);
550 
551   /// Merge classes for the given symbols and return a new state.
552   LLVM_NODISCARD static inline ProgramStateRef merge(RangeSet::Factory &F,
553                                                      ProgramStateRef State,
554                                                      SymbolRef First,
555                                                      SymbolRef Second);
556   // Merge this class with the given class and return a new state.
557   LLVM_NODISCARD inline ProgramStateRef
558   merge(RangeSet::Factory &F, ProgramStateRef State, EquivalenceClass Other);
559 
560   /// Return a set of class members for the given state.
561   LLVM_NODISCARD inline SymbolSet getClassMembers(ProgramStateRef State) const;
562 
563   /// Return true if the current class is trivial in the given state.
564   /// A class is trivial if and only if there is not any member relations stored
565   /// to it in State/ClassMembers.
566   /// An equivalence class with one member might seem as it does not hold any
567   /// meaningful information, i.e. that is a tautology. However, during the
568   /// removal of dead symbols we do not remove classes with one member for
569   /// resource and performance reasons. Consequently, a class with one member is
570   /// not necessarily trivial. It could happen that we have a class with two
571   /// members and then during the removal of dead symbols we remove one of its
572   /// members. In this case, the class is still non-trivial (it still has the
573   /// mappings in ClassMembers), even though it has only one member.
574   LLVM_NODISCARD inline bool isTrivial(ProgramStateRef State) const;
575 
576   /// Return true if the current class is trivial and its only member is dead.
577   LLVM_NODISCARD inline bool isTriviallyDead(ProgramStateRef State,
578                                              SymbolReaper &Reaper) const;
579 
580   LLVM_NODISCARD static inline ProgramStateRef
581   markDisequal(RangeSet::Factory &F, ProgramStateRef State, SymbolRef First,
582                SymbolRef Second);
583   LLVM_NODISCARD static inline ProgramStateRef
584   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
585                EquivalenceClass First, EquivalenceClass Second);
586   LLVM_NODISCARD inline ProgramStateRef
587   markDisequal(RangeSet::Factory &F, ProgramStateRef State,
588                EquivalenceClass Other) const;
589   LLVM_NODISCARD static inline ClassSet
590   getDisequalClasses(ProgramStateRef State, SymbolRef Sym);
591   LLVM_NODISCARD inline ClassSet
592   getDisequalClasses(ProgramStateRef State) const;
593   LLVM_NODISCARD inline ClassSet
594   getDisequalClasses(DisequalityMapTy Map, ClassSet::Factory &Factory) const;
595 
596   LLVM_NODISCARD static inline Optional<bool> areEqual(ProgramStateRef State,
597                                                        EquivalenceClass First,
598                                                        EquivalenceClass Second);
599   LLVM_NODISCARD static inline Optional<bool>
600   areEqual(ProgramStateRef State, SymbolRef First, SymbolRef Second);
601 
602   /// Iterate over all symbols and try to simplify them.
603   LLVM_NODISCARD static inline ProgramStateRef simplify(SValBuilder &SVB,
604                                                         RangeSet::Factory &F,
605                                                         ProgramStateRef State,
606                                                         EquivalenceClass Class);
607 
608   void dumpToStream(ProgramStateRef State, raw_ostream &os) const;
609   LLVM_DUMP_METHOD void dump(ProgramStateRef State) const {
610     dumpToStream(State, llvm::errs());
611   }
612 
613   /// Check equivalence data for consistency.
614   LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED static bool
615   isClassDataConsistent(ProgramStateRef State);
616 
617   LLVM_NODISCARD QualType getType() const {
618     return getRepresentativeSymbol()->getType();
619   }
620 
621   EquivalenceClass() = delete;
622   EquivalenceClass(const EquivalenceClass &) = default;
623   EquivalenceClass &operator=(const EquivalenceClass &) = delete;
624   EquivalenceClass(EquivalenceClass &&) = default;
625   EquivalenceClass &operator=(EquivalenceClass &&) = delete;
626 
627   bool operator==(const EquivalenceClass &Other) const {
628     return ID == Other.ID;
629   }
630   bool operator<(const EquivalenceClass &Other) const { return ID < Other.ID; }
631   bool operator!=(const EquivalenceClass &Other) const {
632     return !operator==(Other);
633   }
634 
635   static void Profile(llvm::FoldingSetNodeID &ID, uintptr_t CID) {
636     ID.AddInteger(CID);
637   }
638 
639   void Profile(llvm::FoldingSetNodeID &ID) const { Profile(ID, this->ID); }
640 
641 private:
642   /* implicit */ EquivalenceClass(SymbolRef Sym)
643       : ID(reinterpret_cast<uintptr_t>(Sym)) {}
644 
645   /// This function is intended to be used ONLY within the class.
646   /// The fact that ID is a pointer to a symbol is an implementation detail
647   /// and should stay that way.
648   /// In the current implementation, we use it to retrieve the only member
649   /// of the trivial class.
650   SymbolRef getRepresentativeSymbol() const {
651     return reinterpret_cast<SymbolRef>(ID);
652   }
653   static inline SymbolSet::Factory &getMembersFactory(ProgramStateRef State);
654 
655   inline ProgramStateRef mergeImpl(RangeSet::Factory &F, ProgramStateRef State,
656                                    SymbolSet Members, EquivalenceClass Other,
657                                    SymbolSet OtherMembers);
658   static inline bool
659   addToDisequalityInfo(DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
660                        RangeSet::Factory &F, ProgramStateRef State,
661                        EquivalenceClass First, EquivalenceClass Second);
662 
663   /// This is a unique identifier of the class.
664   uintptr_t ID;
665 };
666 
667 //===----------------------------------------------------------------------===//
668 //                             Constraint functions
669 //===----------------------------------------------------------------------===//
670 
671 LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED bool
672 areFeasible(ConstraintRangeTy Constraints) {
673   return llvm::none_of(
674       Constraints,
675       [](const std::pair<EquivalenceClass, RangeSet> &ClassConstraint) {
676         return ClassConstraint.second.isEmpty();
677       });
678 }
679 
680 LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
681                                                     EquivalenceClass Class) {
682   return State->get<ConstraintRange>(Class);
683 }
684 
685 LLVM_NODISCARD inline const RangeSet *getConstraint(ProgramStateRef State,
686                                                     SymbolRef Sym) {
687   return getConstraint(State, EquivalenceClass::find(State, Sym));
688 }
689 
690 LLVM_NODISCARD ProgramStateRef setConstraint(ProgramStateRef State,
691                                              EquivalenceClass Class,
692                                              RangeSet Constraint) {
693   return State->set<ConstraintRange>(Class, Constraint);
694 }
695 
696 LLVM_NODISCARD ProgramStateRef setConstraints(ProgramStateRef State,
697                                               ConstraintRangeTy Constraints) {
698   return State->set<ConstraintRange>(Constraints);
699 }
700 
701 //===----------------------------------------------------------------------===//
702 //                       Equality/diseqiality abstraction
703 //===----------------------------------------------------------------------===//
704 
705 /// A small helper function for detecting symbolic (dis)equality.
706 ///
707 /// Equality check can have different forms (like a == b or a - b) and this
708 /// class encapsulates those away if the only thing the user wants to check -
709 /// whether it's equality/diseqiality or not.
710 ///
711 /// \returns true if assuming this Sym to be true means equality of operands
712 ///          false if it means disequality of operands
713 ///          None otherwise
714 Optional<bool> meansEquality(const SymSymExpr *Sym) {
715   switch (Sym->getOpcode()) {
716   case BO_Sub:
717     // This case is: A - B != 0 -> disequality check.
718     return false;
719   case BO_EQ:
720     // This case is: A == B != 0 -> equality check.
721     return true;
722   case BO_NE:
723     // This case is: A != B != 0 -> diseqiality check.
724     return false;
725   default:
726     return llvm::None;
727   }
728 }
729 
730 //===----------------------------------------------------------------------===//
731 //                            Intersection functions
732 //===----------------------------------------------------------------------===//
733 
734 template <class SecondTy, class... RestTy>
735 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
736                                          SecondTy Second, RestTy... Tail);
737 
738 template <class... RangeTy> struct IntersectionTraits;
739 
740 template <class... TailTy> struct IntersectionTraits<RangeSet, TailTy...> {
741   // Found RangeSet, no need to check any further
742   using Type = RangeSet;
743 };
744 
745 template <> struct IntersectionTraits<> {
746   // We ran out of types, and we didn't find any RangeSet, so the result should
747   // be optional.
748   using Type = Optional<RangeSet>;
749 };
750 
751 template <class OptionalOrPointer, class... TailTy>
752 struct IntersectionTraits<OptionalOrPointer, TailTy...> {
753   // If current type is Optional or a raw pointer, we should keep looking.
754   using Type = typename IntersectionTraits<TailTy...>::Type;
755 };
756 
757 template <class EndTy>
758 LLVM_NODISCARD inline EndTy intersect(RangeSet::Factory &F, EndTy End) {
759   // If the list contains only RangeSet or Optional<RangeSet>, simply return
760   // that range set.
761   return End;
762 }
763 
764 LLVM_NODISCARD LLVM_ATTRIBUTE_UNUSED inline Optional<RangeSet>
765 intersect(RangeSet::Factory &F, const RangeSet *End) {
766   // This is an extraneous conversion from a raw pointer into Optional<RangeSet>
767   if (End) {
768     return *End;
769   }
770   return llvm::None;
771 }
772 
773 template <class... RestTy>
774 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
775                                          RangeSet Second, RestTy... Tail) {
776   // Here we call either the <RangeSet,RangeSet,...> or <RangeSet,...> version
777   // of the function and can be sure that the result is RangeSet.
778   return intersect(F, F.intersect(Head, Second), Tail...);
779 }
780 
781 template <class SecondTy, class... RestTy>
782 LLVM_NODISCARD inline RangeSet intersect(RangeSet::Factory &F, RangeSet Head,
783                                          SecondTy Second, RestTy... Tail) {
784   if (Second) {
785     // Here we call the <RangeSet,RangeSet,...> version of the function...
786     return intersect(F, Head, *Second, Tail...);
787   }
788   // ...and here it is either <RangeSet,RangeSet,...> or <RangeSet,...>, which
789   // means that the result is definitely RangeSet.
790   return intersect(F, Head, Tail...);
791 }
792 
793 /// Main generic intersect function.
794 /// It intersects all of the given range sets.  If some of the given arguments
795 /// don't hold a range set (nullptr or llvm::None), the function will skip them.
796 ///
797 /// Available representations for the arguments are:
798 ///   * RangeSet
799 ///   * Optional<RangeSet>
800 ///   * RangeSet *
801 /// Pointer to a RangeSet is automatically assumed to be nullable and will get
802 /// checked as well as the optional version.  If this behaviour is undesired,
803 /// please dereference the pointer in the call.
804 ///
805 /// Return type depends on the arguments' types.  If we can be sure in compile
806 /// time that there will be a range set as a result, the returning type is
807 /// simply RangeSet, in other cases we have to back off to Optional<RangeSet>.
808 ///
809 /// Please, prefer optional range sets to raw pointers.  If the last argument is
810 /// a raw pointer and all previous arguments are None, it will cost one
811 /// additional check to convert RangeSet * into Optional<RangeSet>.
812 template <class HeadTy, class SecondTy, class... RestTy>
813 LLVM_NODISCARD inline
814     typename IntersectionTraits<HeadTy, SecondTy, RestTy...>::Type
815     intersect(RangeSet::Factory &F, HeadTy Head, SecondTy Second,
816               RestTy... Tail) {
817   if (Head) {
818     return intersect(F, *Head, Second, Tail...);
819   }
820   return intersect(F, Second, Tail...);
821 }
822 
823 //===----------------------------------------------------------------------===//
824 //                           Symbolic reasoning logic
825 //===----------------------------------------------------------------------===//
826 
827 /// A little component aggregating all of the reasoning we have about
828 /// the ranges of symbolic expressions.
829 ///
830 /// Even when we don't know the exact values of the operands, we still
831 /// can get a pretty good estimate of the result's range.
832 class SymbolicRangeInferrer
833     : public SymExprVisitor<SymbolicRangeInferrer, RangeSet> {
834 public:
835   template <class SourceType>
836   static RangeSet inferRange(RangeSet::Factory &F, ProgramStateRef State,
837                              SourceType Origin) {
838     SymbolicRangeInferrer Inferrer(F, State);
839     return Inferrer.infer(Origin);
840   }
841 
842   RangeSet VisitSymExpr(SymbolRef Sym) {
843     // If we got to this function, the actual type of the symbolic
844     // expression is not supported for advanced inference.
845     // In this case, we simply backoff to the default "let's simply
846     // infer the range from the expression's type".
847     return infer(Sym->getType());
848   }
849 
850   RangeSet VisitSymIntExpr(const SymIntExpr *Sym) {
851     return VisitBinaryOperator(Sym);
852   }
853 
854   RangeSet VisitIntSymExpr(const IntSymExpr *Sym) {
855     return VisitBinaryOperator(Sym);
856   }
857 
858   RangeSet VisitSymSymExpr(const SymSymExpr *Sym) {
859     return intersect(
860         RangeFactory,
861         // If Sym is (dis)equality, we might have some information
862         // on that in our equality classes data structure.
863         getRangeForEqualities(Sym),
864         // And we should always check what we can get from the operands.
865         VisitBinaryOperator(Sym));
866   }
867 
868 private:
869   SymbolicRangeInferrer(RangeSet::Factory &F, ProgramStateRef S)
870       : ValueFactory(F.getValueFactory()), RangeFactory(F), State(S) {}
871 
872   /// Infer range information from the given integer constant.
873   ///
874   /// It's not a real "inference", but is here for operating with
875   /// sub-expressions in a more polymorphic manner.
876   RangeSet inferAs(const llvm::APSInt &Val, QualType) {
877     return {RangeFactory, Val};
878   }
879 
880   /// Infer range information from symbol in the context of the given type.
881   RangeSet inferAs(SymbolRef Sym, QualType DestType) {
882     QualType ActualType = Sym->getType();
883     // Check that we can reason about the symbol at all.
884     if (ActualType->isIntegralOrEnumerationType() ||
885         Loc::isLocType(ActualType)) {
886       return infer(Sym);
887     }
888     // Otherwise, let's simply infer from the destination type.
889     // We couldn't figure out nothing else about that expression.
890     return infer(DestType);
891   }
892 
893   RangeSet infer(SymbolRef Sym) {
894     return intersect(
895         RangeFactory,
896         // Of course, we should take the constraint directly associated with
897         // this symbol into consideration.
898         getConstraint(State, Sym),
899         // If Sym is a difference of symbols A - B, then maybe we have range
900         // set stored for B - A.
901         //
902         // If we have range set stored for both A - B and B - A then
903         // calculate the effective range set by intersecting the range set
904         // for A - B and the negated range set of B - A.
905         getRangeForNegatedSub(Sym),
906         // If Sym is a comparison expression (except <=>),
907         // find any other comparisons with the same operands.
908         // See function description.
909         getRangeForComparisonSymbol(Sym),
910         // Apart from the Sym itself, we can infer quite a lot if we look
911         // into subexpressions of Sym.
912         Visit(Sym));
913   }
914 
915   RangeSet infer(EquivalenceClass Class) {
916     if (const RangeSet *AssociatedConstraint = getConstraint(State, Class))
917       return *AssociatedConstraint;
918 
919     return infer(Class.getType());
920   }
921 
922   /// Infer range information solely from the type.
923   RangeSet infer(QualType T) {
924     // Lazily generate a new RangeSet representing all possible values for the
925     // given symbol type.
926     RangeSet Result(RangeFactory, ValueFactory.getMinValue(T),
927                     ValueFactory.getMaxValue(T));
928 
929     // References are known to be non-zero.
930     if (T->isReferenceType())
931       return assumeNonZero(Result, T);
932 
933     return Result;
934   }
935 
936   template <class BinarySymExprTy>
937   RangeSet VisitBinaryOperator(const BinarySymExprTy *Sym) {
938     // TODO #1: VisitBinaryOperator implementation might not make a good
939     // use of the inferred ranges.  In this case, we might be calculating
940     // everything for nothing.  This being said, we should introduce some
941     // sort of laziness mechanism here.
942     //
943     // TODO #2: We didn't go into the nested expressions before, so it
944     // might cause us spending much more time doing the inference.
945     // This can be a problem for deeply nested expressions that are
946     // involved in conditions and get tested continuously.  We definitely
947     // need to address this issue and introduce some sort of caching
948     // in here.
949     QualType ResultType = Sym->getType();
950     return VisitBinaryOperator(inferAs(Sym->getLHS(), ResultType),
951                                Sym->getOpcode(),
952                                inferAs(Sym->getRHS(), ResultType), ResultType);
953   }
954 
955   RangeSet VisitBinaryOperator(RangeSet LHS, BinaryOperator::Opcode Op,
956                                RangeSet RHS, QualType T) {
957     switch (Op) {
958     case BO_Or:
959       return VisitBinaryOperator<BO_Or>(LHS, RHS, T);
960     case BO_And:
961       return VisitBinaryOperator<BO_And>(LHS, RHS, T);
962     case BO_Rem:
963       return VisitBinaryOperator<BO_Rem>(LHS, RHS, T);
964     default:
965       return infer(T);
966     }
967   }
968 
969   //===----------------------------------------------------------------------===//
970   //                         Ranges and operators
971   //===----------------------------------------------------------------------===//
972 
973   /// Return a rough approximation of the given range set.
974   ///
975   /// For the range set:
976   ///   { [x_0, y_0], [x_1, y_1], ... , [x_N, y_N] }
977   /// it will return the range [x_0, y_N].
978   static Range fillGaps(RangeSet Origin) {
979     assert(!Origin.isEmpty());
980     return {Origin.getMinValue(), Origin.getMaxValue()};
981   }
982 
983   /// Try to convert given range into the given type.
984   ///
985   /// It will return llvm::None only when the trivial conversion is possible.
986   llvm::Optional<Range> convert(const Range &Origin, APSIntType To) {
987     if (To.testInRange(Origin.From(), false) != APSIntType::RTR_Within ||
988         To.testInRange(Origin.To(), false) != APSIntType::RTR_Within) {
989       return llvm::None;
990     }
991     return Range(ValueFactory.Convert(To, Origin.From()),
992                  ValueFactory.Convert(To, Origin.To()));
993   }
994 
995   template <BinaryOperator::Opcode Op>
996   RangeSet VisitBinaryOperator(RangeSet LHS, RangeSet RHS, QualType T) {
997     // We should propagate information about unfeasbility of one of the
998     // operands to the resulting range.
999     if (LHS.isEmpty() || RHS.isEmpty()) {
1000       return RangeFactory.getEmptySet();
1001     }
1002 
1003     Range CoarseLHS = fillGaps(LHS);
1004     Range CoarseRHS = fillGaps(RHS);
1005 
1006     APSIntType ResultType = ValueFactory.getAPSIntType(T);
1007 
1008     // We need to convert ranges to the resulting type, so we can compare values
1009     // and combine them in a meaningful (in terms of the given operation) way.
1010     auto ConvertedCoarseLHS = convert(CoarseLHS, ResultType);
1011     auto ConvertedCoarseRHS = convert(CoarseRHS, ResultType);
1012 
1013     // It is hard to reason about ranges when conversion changes
1014     // borders of the ranges.
1015     if (!ConvertedCoarseLHS || !ConvertedCoarseRHS) {
1016       return infer(T);
1017     }
1018 
1019     return VisitBinaryOperator<Op>(*ConvertedCoarseLHS, *ConvertedCoarseRHS, T);
1020   }
1021 
1022   template <BinaryOperator::Opcode Op>
1023   RangeSet VisitBinaryOperator(Range LHS, Range RHS, QualType T) {
1024     return infer(T);
1025   }
1026 
1027   /// Return a symmetrical range for the given range and type.
1028   ///
1029   /// If T is signed, return the smallest range [-x..x] that covers the original
1030   /// range, or [-min(T), max(T)] if the aforementioned symmetric range doesn't
1031   /// exist due to original range covering min(T)).
1032   ///
1033   /// If T is unsigned, return the smallest range [0..x] that covers the
1034   /// original range.
1035   Range getSymmetricalRange(Range Origin, QualType T) {
1036     APSIntType RangeType = ValueFactory.getAPSIntType(T);
1037 
1038     if (RangeType.isUnsigned()) {
1039       return Range(ValueFactory.getMinValue(RangeType), Origin.To());
1040     }
1041 
1042     if (Origin.From().isMinSignedValue()) {
1043       // If mini is a minimal signed value, absolute value of it is greater
1044       // than the maximal signed value.  In order to avoid these
1045       // complications, we simply return the whole range.
1046       return {ValueFactory.getMinValue(RangeType),
1047               ValueFactory.getMaxValue(RangeType)};
1048     }
1049 
1050     // At this point, we are sure that the type is signed and we can safely
1051     // use unary - operator.
1052     //
1053     // While calculating absolute maximum, we can use the following formula
1054     // because of these reasons:
1055     //   * If From >= 0 then To >= From and To >= -From.
1056     //     AbsMax == To == max(To, -From)
1057     //   * If To <= 0 then -From >= -To and -From >= From.
1058     //     AbsMax == -From == max(-From, To)
1059     //   * Otherwise, From <= 0, To >= 0, and
1060     //     AbsMax == max(abs(From), abs(To))
1061     llvm::APSInt AbsMax = std::max(-Origin.From(), Origin.To());
1062 
1063     // Intersection is guaranteed to be non-empty.
1064     return {ValueFactory.getValue(-AbsMax), ValueFactory.getValue(AbsMax)};
1065   }
1066 
1067   /// Return a range set subtracting zero from \p Domain.
1068   RangeSet assumeNonZero(RangeSet Domain, QualType T) {
1069     APSIntType IntType = ValueFactory.getAPSIntType(T);
1070     return RangeFactory.deletePoint(Domain, IntType.getZeroValue());
1071   }
1072 
1073   // FIXME: Once SValBuilder supports unary minus, we should use SValBuilder to
1074   //        obtain the negated symbolic expression instead of constructing the
1075   //        symbol manually. This will allow us to support finding ranges of not
1076   //        only negated SymSymExpr-type expressions, but also of other, simpler
1077   //        expressions which we currently do not know how to negate.
1078   Optional<RangeSet> getRangeForNegatedSub(SymbolRef Sym) {
1079     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(Sym)) {
1080       if (SSE->getOpcode() == BO_Sub) {
1081         QualType T = Sym->getType();
1082 
1083         // Do not negate unsigned ranges
1084         if (!T->isUnsignedIntegerOrEnumerationType() &&
1085             !T->isSignedIntegerOrEnumerationType())
1086           return llvm::None;
1087 
1088         SymbolManager &SymMgr = State->getSymbolManager();
1089         SymbolRef NegatedSym =
1090             SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), T);
1091 
1092         if (const RangeSet *NegatedRange = getConstraint(State, NegatedSym)) {
1093           return RangeFactory.negate(*NegatedRange);
1094         }
1095       }
1096     }
1097     return llvm::None;
1098   }
1099 
1100   // Returns ranges only for binary comparison operators (except <=>)
1101   // when left and right operands are symbolic values.
1102   // Finds any other comparisons with the same operands.
1103   // Then do logical calculations and refuse impossible branches.
1104   // E.g. (x < y) and (x > y) at the same time are impossible.
1105   // E.g. (x >= y) and (x != y) at the same time makes (x > y) true only.
1106   // E.g. (x == y) and (y == x) are just reversed but the same.
1107   // It covers all possible combinations (see CmpOpTable description).
1108   // Note that `x` and `y` can also stand for subexpressions,
1109   // not only for actual symbols.
1110   Optional<RangeSet> getRangeForComparisonSymbol(SymbolRef Sym) {
1111     const auto *SSE = dyn_cast<SymSymExpr>(Sym);
1112     if (!SSE)
1113       return llvm::None;
1114 
1115     const BinaryOperatorKind CurrentOP = SSE->getOpcode();
1116 
1117     // We currently do not support <=> (C++20).
1118     if (!BinaryOperator::isComparisonOp(CurrentOP) || (CurrentOP == BO_Cmp))
1119       return llvm::None;
1120 
1121     static const OperatorRelationsTable CmpOpTable{};
1122 
1123     const SymExpr *LHS = SSE->getLHS();
1124     const SymExpr *RHS = SSE->getRHS();
1125     QualType T = SSE->getType();
1126 
1127     SymbolManager &SymMgr = State->getSymbolManager();
1128 
1129     // We use this variable to store the last queried operator (`QueriedOP`)
1130     // for which the `getCmpOpState` returned with `Unknown`. If there are two
1131     // different OPs that returned `Unknown` then we have to query the special
1132     // `UnknownX2` column. We assume that `getCmpOpState(CurrentOP, CurrentOP)`
1133     // never returns `Unknown`, so `CurrentOP` is a good initial value.
1134     BinaryOperatorKind LastQueriedOpToUnknown = CurrentOP;
1135 
1136     // Loop goes through all of the columns exept the last one ('UnknownX2').
1137     // We treat `UnknownX2` column separately at the end of the loop body.
1138     for (size_t i = 0; i < CmpOpTable.getCmpOpCount(); ++i) {
1139 
1140       // Let's find an expression e.g. (x < y).
1141       BinaryOperatorKind QueriedOP = OperatorRelationsTable::getOpFromIndex(i);
1142       const SymSymExpr *SymSym = SymMgr.getSymSymExpr(LHS, QueriedOP, RHS, T);
1143       const RangeSet *QueriedRangeSet = getConstraint(State, SymSym);
1144 
1145       // If ranges were not previously found,
1146       // try to find a reversed expression (y > x).
1147       if (!QueriedRangeSet) {
1148         const BinaryOperatorKind ROP =
1149             BinaryOperator::reverseComparisonOp(QueriedOP);
1150         SymSym = SymMgr.getSymSymExpr(RHS, ROP, LHS, T);
1151         QueriedRangeSet = getConstraint(State, SymSym);
1152       }
1153 
1154       if (!QueriedRangeSet || QueriedRangeSet->isEmpty())
1155         continue;
1156 
1157       const llvm::APSInt *ConcreteValue = QueriedRangeSet->getConcreteValue();
1158       const bool isInFalseBranch =
1159           ConcreteValue ? (*ConcreteValue == 0) : false;
1160 
1161       // If it is a false branch, we shall be guided by opposite operator,
1162       // because the table is made assuming we are in the true branch.
1163       // E.g. when (x <= y) is false, then (x > y) is true.
1164       if (isInFalseBranch)
1165         QueriedOP = BinaryOperator::negateComparisonOp(QueriedOP);
1166 
1167       OperatorRelationsTable::TriStateKind BranchState =
1168           CmpOpTable.getCmpOpState(CurrentOP, QueriedOP);
1169 
1170       if (BranchState == OperatorRelationsTable::Unknown) {
1171         if (LastQueriedOpToUnknown != CurrentOP &&
1172             LastQueriedOpToUnknown != QueriedOP) {
1173           // If we got the Unknown state for both different operators.
1174           // if (x <= y)    // assume true
1175           //   if (x != y)  // assume true
1176           //     if (x < y) // would be also true
1177           // Get a state from `UnknownX2` column.
1178           BranchState = CmpOpTable.getCmpOpStateForUnknownX2(CurrentOP);
1179         } else {
1180           LastQueriedOpToUnknown = QueriedOP;
1181           continue;
1182         }
1183       }
1184 
1185       return (BranchState == OperatorRelationsTable::True) ? getTrueRange(T)
1186                                                            : getFalseRange(T);
1187     }
1188 
1189     return llvm::None;
1190   }
1191 
1192   Optional<RangeSet> getRangeForEqualities(const SymSymExpr *Sym) {
1193     Optional<bool> Equality = meansEquality(Sym);
1194 
1195     if (!Equality)
1196       return llvm::None;
1197 
1198     if (Optional<bool> AreEqual =
1199             EquivalenceClass::areEqual(State, Sym->getLHS(), Sym->getRHS())) {
1200       // Here we cover two cases at once:
1201       //   * if Sym is equality and its operands are known to be equal -> true
1202       //   * if Sym is disequality and its operands are disequal -> true
1203       if (*AreEqual == *Equality) {
1204         return getTrueRange(Sym->getType());
1205       }
1206       // Opposite combinations result in false.
1207       return getFalseRange(Sym->getType());
1208     }
1209 
1210     return llvm::None;
1211   }
1212 
1213   RangeSet getTrueRange(QualType T) {
1214     RangeSet TypeRange = infer(T);
1215     return assumeNonZero(TypeRange, T);
1216   }
1217 
1218   RangeSet getFalseRange(QualType T) {
1219     const llvm::APSInt &Zero = ValueFactory.getValue(0, T);
1220     return RangeSet(RangeFactory, Zero);
1221   }
1222 
1223   BasicValueFactory &ValueFactory;
1224   RangeSet::Factory &RangeFactory;
1225   ProgramStateRef State;
1226 };
1227 
1228 //===----------------------------------------------------------------------===//
1229 //               Range-based reasoning about symbolic operations
1230 //===----------------------------------------------------------------------===//
1231 
1232 template <>
1233 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Or>(Range LHS, Range RHS,
1234                                                            QualType T) {
1235   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1236   llvm::APSInt Zero = ResultType.getZeroValue();
1237 
1238   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1239   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1240 
1241   bool IsLHSNegative = LHS.To() < Zero;
1242   bool IsRHSNegative = RHS.To() < Zero;
1243 
1244   // Check if both ranges have the same sign.
1245   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1246       (IsLHSNegative && IsRHSNegative)) {
1247     // The result is definitely greater or equal than any of the operands.
1248     const llvm::APSInt &Min = std::max(LHS.From(), RHS.From());
1249 
1250     // We estimate maximal value for positives as the maximal value for the
1251     // given type.  For negatives, we estimate it with -1 (e.g. 0x11111111).
1252     //
1253     // TODO: We basically, limit the resulting range from below, but don't do
1254     //       anything with the upper bound.
1255     //
1256     //       For positive operands, it can be done as follows: for the upper
1257     //       bound of LHS and RHS we calculate the most significant bit set.
1258     //       Let's call it the N-th bit.  Then we can estimate the maximal
1259     //       number to be 2^(N+1)-1, i.e. the number with all the bits up to
1260     //       the N-th bit set.
1261     const llvm::APSInt &Max = IsLHSNegative
1262                                   ? ValueFactory.getValue(--Zero)
1263                                   : ValueFactory.getMaxValue(ResultType);
1264 
1265     return {RangeFactory, ValueFactory.getValue(Min), Max};
1266   }
1267 
1268   // Otherwise, let's check if at least one of the operands is negative.
1269   if (IsLHSNegative || IsRHSNegative) {
1270     // This means that the result is definitely negative as well.
1271     return {RangeFactory, ValueFactory.getMinValue(ResultType),
1272             ValueFactory.getValue(--Zero)};
1273   }
1274 
1275   RangeSet DefaultRange = infer(T);
1276 
1277   // It is pretty hard to reason about operands with different signs
1278   // (and especially with possibly different signs).  We simply check if it
1279   // can be zero.  In order to conclude that the result could not be zero,
1280   // at least one of the operands should be definitely not zero itself.
1281   if (!LHS.Includes(Zero) || !RHS.Includes(Zero)) {
1282     return assumeNonZero(DefaultRange, T);
1283   }
1284 
1285   // Nothing much else to do here.
1286   return DefaultRange;
1287 }
1288 
1289 template <>
1290 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_And>(Range LHS,
1291                                                             Range RHS,
1292                                                             QualType T) {
1293   APSIntType ResultType = ValueFactory.getAPSIntType(T);
1294   llvm::APSInt Zero = ResultType.getZeroValue();
1295 
1296   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1297   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1298 
1299   bool IsLHSNegative = LHS.To() < Zero;
1300   bool IsRHSNegative = RHS.To() < Zero;
1301 
1302   // Check if both ranges have the same sign.
1303   if ((IsLHSPositiveOrZero && IsRHSPositiveOrZero) ||
1304       (IsLHSNegative && IsRHSNegative)) {
1305     // The result is definitely less or equal than any of the operands.
1306     const llvm::APSInt &Max = std::min(LHS.To(), RHS.To());
1307 
1308     // We conservatively estimate lower bound to be the smallest positive
1309     // or negative value corresponding to the sign of the operands.
1310     const llvm::APSInt &Min = IsLHSNegative
1311                                   ? ValueFactory.getMinValue(ResultType)
1312                                   : ValueFactory.getValue(Zero);
1313 
1314     return {RangeFactory, Min, Max};
1315   }
1316 
1317   // Otherwise, let's check if at least one of the operands is positive.
1318   if (IsLHSPositiveOrZero || IsRHSPositiveOrZero) {
1319     // This makes result definitely positive.
1320     //
1321     // We can also reason about a maximal value by finding the maximal
1322     // value of the positive operand.
1323     const llvm::APSInt &Max = IsLHSPositiveOrZero ? LHS.To() : RHS.To();
1324 
1325     // The minimal value on the other hand is much harder to reason about.
1326     // The only thing we know for sure is that the result is positive.
1327     return {RangeFactory, ValueFactory.getValue(Zero),
1328             ValueFactory.getValue(Max)};
1329   }
1330 
1331   // Nothing much else to do here.
1332   return infer(T);
1333 }
1334 
1335 template <>
1336 RangeSet SymbolicRangeInferrer::VisitBinaryOperator<BO_Rem>(Range LHS,
1337                                                             Range RHS,
1338                                                             QualType T) {
1339   llvm::APSInt Zero = ValueFactory.getAPSIntType(T).getZeroValue();
1340 
1341   Range ConservativeRange = getSymmetricalRange(RHS, T);
1342 
1343   llvm::APSInt Max = ConservativeRange.To();
1344   llvm::APSInt Min = ConservativeRange.From();
1345 
1346   if (Max == Zero) {
1347     // It's an undefined behaviour to divide by 0 and it seems like we know
1348     // for sure that RHS is 0.  Let's say that the resulting range is
1349     // simply infeasible for that matter.
1350     return RangeFactory.getEmptySet();
1351   }
1352 
1353   // At this point, our conservative range is closed.  The result, however,
1354   // couldn't be greater than the RHS' maximal absolute value.  Because of
1355   // this reason, we turn the range into open (or half-open in case of
1356   // unsigned integers).
1357   //
1358   // While we operate on integer values, an open interval (a, b) can be easily
1359   // represented by the closed interval [a + 1, b - 1].  And this is exactly
1360   // what we do next.
1361   //
1362   // If we are dealing with unsigned case, we shouldn't move the lower bound.
1363   if (Min.isSigned()) {
1364     ++Min;
1365   }
1366   --Max;
1367 
1368   bool IsLHSPositiveOrZero = LHS.From() >= Zero;
1369   bool IsRHSPositiveOrZero = RHS.From() >= Zero;
1370 
1371   // Remainder operator results with negative operands is implementation
1372   // defined.  Positive cases are much easier to reason about though.
1373   if (IsLHSPositiveOrZero && IsRHSPositiveOrZero) {
1374     // If maximal value of LHS is less than maximal value of RHS,
1375     // the result won't get greater than LHS.To().
1376     Max = std::min(LHS.To(), Max);
1377     // We want to check if it is a situation similar to the following:
1378     //
1379     // <------------|---[  LHS  ]--------[  RHS  ]----->
1380     //  -INF        0                              +INF
1381     //
1382     // In this situation, we can conclude that (LHS / RHS) == 0 and
1383     // (LHS % RHS) == LHS.
1384     Min = LHS.To() < RHS.From() ? LHS.From() : Zero;
1385   }
1386 
1387   // Nevertheless, the symmetrical range for RHS is a conservative estimate
1388   // for any sign of either LHS, or RHS.
1389   return {RangeFactory, ValueFactory.getValue(Min), ValueFactory.getValue(Max)};
1390 }
1391 
1392 //===----------------------------------------------------------------------===//
1393 //                         Constraint assignment logic
1394 //===----------------------------------------------------------------------===//
1395 
1396 /// ConstraintAssignorBase is a small utility class that unifies visitor
1397 /// for ranges with a visitor for constraints (rangeset/range/constant).
1398 ///
1399 /// It is designed to have one derived class, but generally it can have more.
1400 /// Derived class can control which types we handle by defining methods of the
1401 /// following form:
1402 ///
1403 ///   bool handle${SYMBOL}To${CONSTRAINT}(const SYMBOL *Sym,
1404 ///                                       CONSTRAINT Constraint);
1405 ///
1406 /// where SYMBOL is the type of the symbol (e.g. SymSymExpr, SymbolCast, etc.)
1407 ///       CONSTRAINT is the type of constraint (RangeSet/Range/Const)
1408 ///       return value signifies whether we should try other handle methods
1409 ///          (i.e. false would mean to stop right after calling this method)
1410 template <class Derived> class ConstraintAssignorBase {
1411 public:
1412   using Const = const llvm::APSInt &;
1413 
1414 #define DISPATCH(CLASS) return assign##CLASS##Impl(cast<CLASS>(Sym), Constraint)
1415 
1416 #define ASSIGN(CLASS, TO, SYM, CONSTRAINT)                                     \
1417   if (!static_cast<Derived *>(this)->assign##CLASS##To##TO(SYM, CONSTRAINT))   \
1418   return false
1419 
1420   void assign(SymbolRef Sym, RangeSet Constraint) {
1421     assignImpl(Sym, Constraint);
1422   }
1423 
1424   bool assignImpl(SymbolRef Sym, RangeSet Constraint) {
1425     switch (Sym->getKind()) {
1426 #define SYMBOL(Id, Parent)                                                     \
1427   case SymExpr::Id##Kind:                                                      \
1428     DISPATCH(Id);
1429 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
1430     }
1431     llvm_unreachable("Unknown SymExpr kind!");
1432   }
1433 
1434 #define DEFAULT_ASSIGN(Id)                                                     \
1435   bool assign##Id##To##RangeSet(const Id *Sym, RangeSet Constraint) {          \
1436     return true;                                                               \
1437   }                                                                            \
1438   bool assign##Id##To##Range(const Id *Sym, Range Constraint) { return true; } \
1439   bool assign##Id##To##Const(const Id *Sym, Const Constraint) { return true; }
1440 
1441   // When we dispatch for constraint types, we first try to check
1442   // if the new constraint is the constant and try the corresponding
1443   // assignor methods.  If it didn't interrupt, we can proceed to the
1444   // range, and finally to the range set.
1445 #define CONSTRAINT_DISPATCH(Id)                                                \
1446   if (const llvm::APSInt *Const = Constraint.getConcreteValue()) {             \
1447     ASSIGN(Id, Const, Sym, *Const);                                            \
1448   }                                                                            \
1449   if (Constraint.size() == 1) {                                                \
1450     ASSIGN(Id, Range, Sym, *Constraint.begin());                               \
1451   }                                                                            \
1452   ASSIGN(Id, RangeSet, Sym, Constraint)
1453 
1454   // Our internal assign method first tries to call assignor methods for all
1455   // constraint types that apply.  And if not interrupted, continues with its
1456   // parent class.
1457 #define SYMBOL(Id, Parent)                                                     \
1458   bool assign##Id##Impl(const Id *Sym, RangeSet Constraint) {                  \
1459     CONSTRAINT_DISPATCH(Id);                                                   \
1460     DISPATCH(Parent);                                                          \
1461   }                                                                            \
1462   DEFAULT_ASSIGN(Id)
1463 #define ABSTRACT_SYMBOL(Id, Parent) SYMBOL(Id, Parent)
1464 #include "clang/StaticAnalyzer/Core/PathSensitive/Symbols.def"
1465 
1466   // Default implementations for the top class that doesn't have parents.
1467   bool assignSymExprImpl(const SymExpr *Sym, RangeSet Constraint) {
1468     CONSTRAINT_DISPATCH(SymExpr);
1469     return true;
1470   }
1471   DEFAULT_ASSIGN(SymExpr);
1472 
1473 #undef DISPATCH
1474 #undef CONSTRAINT_DISPATCH
1475 #undef DEFAULT_ASSIGN
1476 #undef ASSIGN
1477 };
1478 
1479 /// A little component aggregating all of the reasoning we have about
1480 /// assigning new constraints to symbols.
1481 ///
1482 /// The main purpose of this class is to associate constraints to symbols,
1483 /// and impose additional constraints on other symbols, when we can imply
1484 /// them.
1485 ///
1486 /// It has a nice symmetry with SymbolicRangeInferrer.  When the latter
1487 /// can provide more precise ranges by looking into the operands of the
1488 /// expression in question, ConstraintAssignor looks into the operands
1489 /// to see if we can imply more from the new constraint.
1490 class ConstraintAssignor : public ConstraintAssignorBase<ConstraintAssignor> {
1491 public:
1492   template <class ClassOrSymbol>
1493   LLVM_NODISCARD static ProgramStateRef
1494   assign(ProgramStateRef State, SValBuilder &Builder, RangeSet::Factory &F,
1495          ClassOrSymbol CoS, RangeSet NewConstraint) {
1496     if (!State || NewConstraint.isEmpty())
1497       return nullptr;
1498 
1499     ConstraintAssignor Assignor{State, Builder, F};
1500     return Assignor.assign(CoS, NewConstraint);
1501   }
1502 
1503   inline bool assignSymExprToConst(const SymExpr *Sym, Const Constraint);
1504   inline bool assignSymSymExprToRangeSet(const SymSymExpr *Sym,
1505                                          RangeSet Constraint);
1506 
1507 private:
1508   ConstraintAssignor(ProgramStateRef State, SValBuilder &Builder,
1509                      RangeSet::Factory &F)
1510       : State(State), Builder(Builder), RangeFactory(F) {}
1511   using Base = ConstraintAssignorBase<ConstraintAssignor>;
1512 
1513   /// Base method for handling new constraints for symbols.
1514   LLVM_NODISCARD ProgramStateRef assign(SymbolRef Sym, RangeSet NewConstraint) {
1515     // All constraints are actually associated with equivalence classes, and
1516     // that's what we are going to do first.
1517     State = assign(EquivalenceClass::find(State, Sym), NewConstraint);
1518     if (!State)
1519       return nullptr;
1520 
1521     // And after that we can check what other things we can get from this
1522     // constraint.
1523     Base::assign(Sym, NewConstraint);
1524     return State;
1525   }
1526 
1527   /// Base method for handling new constraints for classes.
1528   LLVM_NODISCARD ProgramStateRef assign(EquivalenceClass Class,
1529                                         RangeSet NewConstraint) {
1530     // There is a chance that we might need to update constraints for the
1531     // classes that are known to be disequal to Class.
1532     //
1533     // In order for this to be even possible, the new constraint should
1534     // be simply a constant because we can't reason about range disequalities.
1535     if (const llvm::APSInt *Point = NewConstraint.getConcreteValue()) {
1536 
1537       ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1538       ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>();
1539 
1540       // Add new constraint.
1541       Constraints = CF.add(Constraints, Class, NewConstraint);
1542 
1543       for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) {
1544         RangeSet UpdatedConstraint = SymbolicRangeInferrer::inferRange(
1545             RangeFactory, State, DisequalClass);
1546 
1547         UpdatedConstraint = RangeFactory.deletePoint(UpdatedConstraint, *Point);
1548 
1549         // If we end up with at least one of the disequal classes to be
1550         // constrained with an empty range-set, the state is infeasible.
1551         if (UpdatedConstraint.isEmpty())
1552           return nullptr;
1553 
1554         Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint);
1555       }
1556       assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1557                                          "a state with infeasible constraints");
1558 
1559       return setConstraints(State, Constraints);
1560     }
1561 
1562     return setConstraint(State, Class, NewConstraint);
1563   }
1564 
1565   ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS,
1566                                    SymbolRef RHS) {
1567     return EquivalenceClass::markDisequal(RangeFactory, State, LHS, RHS);
1568   }
1569 
1570   ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS,
1571                                 SymbolRef RHS) {
1572     return EquivalenceClass::merge(RangeFactory, State, LHS, RHS);
1573   }
1574 
1575   LLVM_NODISCARD Optional<bool> interpreteAsBool(RangeSet Constraint) {
1576     assert(!Constraint.isEmpty() && "Empty ranges shouldn't get here");
1577 
1578     if (Constraint.getConcreteValue())
1579       return !Constraint.getConcreteValue()->isZero();
1580 
1581     APSIntType T{Constraint.getMinValue()};
1582     Const Zero = T.getZeroValue();
1583     if (!Constraint.contains(Zero))
1584       return true;
1585 
1586     return llvm::None;
1587   }
1588 
1589   ProgramStateRef State;
1590   SValBuilder &Builder;
1591   RangeSet::Factory &RangeFactory;
1592 };
1593 
1594 //===----------------------------------------------------------------------===//
1595 //                  Constraint manager implementation details
1596 //===----------------------------------------------------------------------===//
1597 
1598 class RangeConstraintManager : public RangedConstraintManager {
1599 public:
1600   RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB)
1601       : RangedConstraintManager(EE, SVB), F(getBasicVals()) {}
1602 
1603   //===------------------------------------------------------------------===//
1604   // Implementation for interface from ConstraintManager.
1605   //===------------------------------------------------------------------===//
1606 
1607   bool haveEqualConstraints(ProgramStateRef S1,
1608                             ProgramStateRef S2) const override {
1609     // NOTE: ClassMembers are as simple as back pointers for ClassMap,
1610     //       so comparing constraint ranges and class maps should be
1611     //       sufficient.
1612     return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() &&
1613            S1->get<ClassMap>() == S2->get<ClassMap>();
1614   }
1615 
1616   bool canReasonAbout(SVal X) const override;
1617 
1618   ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
1619 
1620   const llvm::APSInt *getSymVal(ProgramStateRef State,
1621                                 SymbolRef Sym) const override;
1622 
1623   ProgramStateRef removeDeadBindings(ProgramStateRef State,
1624                                      SymbolReaper &SymReaper) override;
1625 
1626   void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
1627                  unsigned int Space = 0, bool IsDot = false) const override;
1628   void printConstraints(raw_ostream &Out, ProgramStateRef State,
1629                         const char *NL = "\n", unsigned int Space = 0,
1630                         bool IsDot = false) const;
1631   void printEquivalenceClasses(raw_ostream &Out, ProgramStateRef State,
1632                                const char *NL = "\n", unsigned int Space = 0,
1633                                bool IsDot = false) const;
1634   void printDisequalities(raw_ostream &Out, ProgramStateRef State,
1635                           const char *NL = "\n", unsigned int Space = 0,
1636                           bool IsDot = false) const;
1637 
1638   //===------------------------------------------------------------------===//
1639   // Implementation for interface from RangedConstraintManager.
1640   //===------------------------------------------------------------------===//
1641 
1642   ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
1643                               const llvm::APSInt &V,
1644                               const llvm::APSInt &Adjustment) override;
1645 
1646   ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
1647                               const llvm::APSInt &V,
1648                               const llvm::APSInt &Adjustment) override;
1649 
1650   ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
1651                               const llvm::APSInt &V,
1652                               const llvm::APSInt &Adjustment) override;
1653 
1654   ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
1655                               const llvm::APSInt &V,
1656                               const llvm::APSInt &Adjustment) override;
1657 
1658   ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
1659                               const llvm::APSInt &V,
1660                               const llvm::APSInt &Adjustment) override;
1661 
1662   ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
1663                               const llvm::APSInt &V,
1664                               const llvm::APSInt &Adjustment) override;
1665 
1666   ProgramStateRef assumeSymWithinInclusiveRange(
1667       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1668       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1669 
1670   ProgramStateRef assumeSymOutsideInclusiveRange(
1671       ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
1672       const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
1673 
1674 private:
1675   RangeSet::Factory F;
1676 
1677   RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
1678   RangeSet getRange(ProgramStateRef State, EquivalenceClass Class);
1679   ProgramStateRef setRange(ProgramStateRef State, SymbolRef Sym,
1680                            RangeSet Range);
1681   ProgramStateRef setRange(ProgramStateRef State, EquivalenceClass Class,
1682                            RangeSet Range);
1683 
1684   RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
1685                          const llvm::APSInt &Int,
1686                          const llvm::APSInt &Adjustment);
1687   RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
1688                          const llvm::APSInt &Int,
1689                          const llvm::APSInt &Adjustment);
1690   RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
1691                          const llvm::APSInt &Int,
1692                          const llvm::APSInt &Adjustment);
1693   RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
1694                          const llvm::APSInt &Int,
1695                          const llvm::APSInt &Adjustment);
1696   RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
1697                          const llvm::APSInt &Int,
1698                          const llvm::APSInt &Adjustment);
1699 };
1700 
1701 bool ConstraintAssignor::assignSymExprToConst(const SymExpr *Sym,
1702                                               const llvm::APSInt &Constraint) {
1703   llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses;
1704   // Iterate over all equivalence classes and try to simplify them.
1705   ClassMembersTy Members = State->get<ClassMembers>();
1706   for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) {
1707     EquivalenceClass Class = ClassToSymbolSet.first;
1708     State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
1709     if (!State)
1710       return false;
1711     SimplifiedClasses.insert(Class);
1712   }
1713 
1714   // Trivial equivalence classes (those that have only one symbol member) are
1715   // not stored in the State. Thus, we must skim through the constraints as
1716   // well. And we try to simplify symbols in the constraints.
1717   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1718   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1719     EquivalenceClass Class = ClassConstraint.first;
1720     if (SimplifiedClasses.count(Class)) // Already simplified.
1721       continue;
1722     State = EquivalenceClass::simplify(Builder, RangeFactory, State, Class);
1723     if (!State)
1724       return false;
1725   }
1726 
1727   return true;
1728 }
1729 
1730 bool ConstraintAssignor::assignSymSymExprToRangeSet(const SymSymExpr *Sym,
1731                                                     RangeSet Constraint) {
1732   Optional<bool> ConstraintAsBool = interpreteAsBool(Constraint);
1733 
1734   if (!ConstraintAsBool)
1735     return true;
1736 
1737   if (Optional<bool> Equality = meansEquality(Sym)) {
1738     // Here we cover two cases:
1739     //   * if Sym is equality and the new constraint is true -> Sym's operands
1740     //     should be marked as equal
1741     //   * if Sym is disequality and the new constraint is false -> Sym's
1742     //     operands should be also marked as equal
1743     if (*Equality == *ConstraintAsBool) {
1744       State = trackEquality(State, Sym->getLHS(), Sym->getRHS());
1745     } else {
1746       // Other combinations leave as with disequal operands.
1747       State = trackDisequality(State, Sym->getLHS(), Sym->getRHS());
1748     }
1749 
1750     if (!State)
1751       return false;
1752   }
1753 
1754   return true;
1755 }
1756 
1757 } // end anonymous namespace
1758 
1759 std::unique_ptr<ConstraintManager>
1760 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr,
1761                                    ExprEngine *Eng) {
1762   return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
1763 }
1764 
1765 ConstraintMap ento::getConstraintMap(ProgramStateRef State) {
1766   ConstraintMap::Factory &F = State->get_context<ConstraintMap>();
1767   ConstraintMap Result = F.getEmptyMap();
1768 
1769   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1770   for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) {
1771     EquivalenceClass Class = ClassConstraint.first;
1772     SymbolSet ClassMembers = Class.getClassMembers(State);
1773     assert(!ClassMembers.isEmpty() &&
1774            "Class must always have at least one member!");
1775 
1776     SymbolRef Representative = *ClassMembers.begin();
1777     Result = F.add(Result, Representative, ClassConstraint.second);
1778   }
1779 
1780   return Result;
1781 }
1782 
1783 //===----------------------------------------------------------------------===//
1784 //                     EqualityClass implementation details
1785 //===----------------------------------------------------------------------===//
1786 
1787 LLVM_DUMP_METHOD void EquivalenceClass::dumpToStream(ProgramStateRef State,
1788                                                      raw_ostream &os) const {
1789   SymbolSet ClassMembers = getClassMembers(State);
1790   for (const SymbolRef &MemberSym : ClassMembers) {
1791     MemberSym->dump();
1792     os << "\n";
1793   }
1794 }
1795 
1796 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State,
1797                                                SymbolRef Sym) {
1798   assert(State && "State should not be null");
1799   assert(Sym && "Symbol should not be null");
1800   // We store far from all Symbol -> Class mappings
1801   if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym))
1802     return *NontrivialClass;
1803 
1804   // This is a trivial class of Sym.
1805   return Sym;
1806 }
1807 
1808 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1809                                                ProgramStateRef State,
1810                                                SymbolRef First,
1811                                                SymbolRef Second) {
1812   EquivalenceClass FirstClass = find(State, First);
1813   EquivalenceClass SecondClass = find(State, Second);
1814 
1815   return FirstClass.merge(F, State, SecondClass);
1816 }
1817 
1818 inline ProgramStateRef EquivalenceClass::merge(RangeSet::Factory &F,
1819                                                ProgramStateRef State,
1820                                                EquivalenceClass Other) {
1821   // It is already the same class.
1822   if (*this == Other)
1823     return State;
1824 
1825   // FIXME: As of now, we support only equivalence classes of the same type.
1826   //        This limitation is connected to the lack of explicit casts in
1827   //        our symbolic expression model.
1828   //
1829   //        That means that for `int x` and `char y` we don't distinguish
1830   //        between these two very different cases:
1831   //          * `x == y`
1832   //          * `(char)x == y`
1833   //
1834   //        The moment we introduce symbolic casts, this restriction can be
1835   //        lifted.
1836   if (getType() != Other.getType())
1837     return State;
1838 
1839   SymbolSet Members = getClassMembers(State);
1840   SymbolSet OtherMembers = Other.getClassMembers(State);
1841 
1842   // We estimate the size of the class by the height of tree containing
1843   // its members.  Merging is not a trivial operation, so it's easier to
1844   // merge the smaller class into the bigger one.
1845   if (Members.getHeight() >= OtherMembers.getHeight()) {
1846     return mergeImpl(F, State, Members, Other, OtherMembers);
1847   } else {
1848     return Other.mergeImpl(F, State, OtherMembers, *this, Members);
1849   }
1850 }
1851 
1852 inline ProgramStateRef
1853 EquivalenceClass::mergeImpl(RangeSet::Factory &RangeFactory,
1854                             ProgramStateRef State, SymbolSet MyMembers,
1855                             EquivalenceClass Other, SymbolSet OtherMembers) {
1856   // Essentially what we try to recreate here is some kind of union-find
1857   // data structure.  It does have certain limitations due to persistence
1858   // and the need to remove elements from classes.
1859   //
1860   // In this setting, EquialityClass object is the representative of the class
1861   // or the parent element.  ClassMap is a mapping of class members to their
1862   // parent. Unlike the union-find structure, they all point directly to the
1863   // class representative because we don't have an opportunity to actually do
1864   // path compression when dealing with immutability.  This means that we
1865   // compress paths every time we do merges.  It also means that we lose
1866   // the main amortized complexity benefit from the original data structure.
1867   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
1868   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
1869 
1870   // 1. If the merged classes have any constraints associated with them, we
1871   //    need to transfer them to the class we have left.
1872   //
1873   // Intersection here makes perfect sense because both of these constraints
1874   // must hold for the whole new class.
1875   if (Optional<RangeSet> NewClassConstraint =
1876           intersect(RangeFactory, getConstraint(State, *this),
1877                     getConstraint(State, Other))) {
1878     // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because
1879     //       range inferrer shouldn't generate ranges incompatible with
1880     //       equivalence classes. However, at the moment, due to imperfections
1881     //       in the solver, it is possible and the merge function can also
1882     //       return infeasible states aka null states.
1883     if (NewClassConstraint->isEmpty())
1884       // Infeasible state
1885       return nullptr;
1886 
1887     // No need in tracking constraints of a now-dissolved class.
1888     Constraints = CRF.remove(Constraints, Other);
1889     // Assign new constraints for this class.
1890     Constraints = CRF.add(Constraints, *this, *NewClassConstraint);
1891 
1892     assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
1893                                        "a state with infeasible constraints");
1894 
1895     State = State->set<ConstraintRange>(Constraints);
1896   }
1897 
1898   // 2. Get ALL equivalence-related maps
1899   ClassMapTy Classes = State->get<ClassMap>();
1900   ClassMapTy::Factory &CMF = State->get_context<ClassMap>();
1901 
1902   ClassMembersTy Members = State->get<ClassMembers>();
1903   ClassMembersTy::Factory &MF = State->get_context<ClassMembers>();
1904 
1905   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
1906   DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>();
1907 
1908   ClassSet::Factory &CF = State->get_context<ClassSet>();
1909   SymbolSet::Factory &F = getMembersFactory(State);
1910 
1911   // 2. Merge members of the Other class into the current class.
1912   SymbolSet NewClassMembers = MyMembers;
1913   for (SymbolRef Sym : OtherMembers) {
1914     NewClassMembers = F.add(NewClassMembers, Sym);
1915     // *this is now the class for all these new symbols.
1916     Classes = CMF.add(Classes, Sym, *this);
1917   }
1918 
1919   // 3. Adjust member mapping.
1920   //
1921   // No need in tracking members of a now-dissolved class.
1922   Members = MF.remove(Members, Other);
1923   // Now only the current class is mapped to all the symbols.
1924   Members = MF.add(Members, *this, NewClassMembers);
1925 
1926   // 4. Update disequality relations
1927   ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF);
1928   // We are about to merge two classes but they are already known to be
1929   // non-equal. This is a contradiction.
1930   if (DisequalToOther.contains(*this))
1931     return nullptr;
1932 
1933   if (!DisequalToOther.isEmpty()) {
1934     ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF);
1935     DisequalityInfo = DF.remove(DisequalityInfo, Other);
1936 
1937     for (EquivalenceClass DisequalClass : DisequalToOther) {
1938       DisequalToThis = CF.add(DisequalToThis, DisequalClass);
1939 
1940       // Disequality is a symmetric relation meaning that if
1941       // DisequalToOther not null then the set for DisequalClass is not
1942       // empty and has at least Other.
1943       ClassSet OriginalSetLinkedToOther =
1944           *DisequalityInfo.lookup(DisequalClass);
1945 
1946       // Other will be eliminated and we should replace it with the bigger
1947       // united class.
1948       ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other);
1949       NewSet = CF.add(NewSet, *this);
1950 
1951       DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet);
1952     }
1953 
1954     DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis);
1955     State = State->set<DisequalityMap>(DisequalityInfo);
1956   }
1957 
1958   // 5. Update the state
1959   State = State->set<ClassMap>(Classes);
1960   State = State->set<ClassMembers>(Members);
1961 
1962   return State;
1963 }
1964 
1965 inline SymbolSet::Factory &
1966 EquivalenceClass::getMembersFactory(ProgramStateRef State) {
1967   return State->get_context<SymbolSet>();
1968 }
1969 
1970 SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const {
1971   if (const SymbolSet *Members = State->get<ClassMembers>(*this))
1972     return *Members;
1973 
1974   // This class is trivial, so we need to construct a set
1975   // with just that one symbol from the class.
1976   SymbolSet::Factory &F = getMembersFactory(State);
1977   return F.add(F.getEmptySet(), getRepresentativeSymbol());
1978 }
1979 
1980 bool EquivalenceClass::isTrivial(ProgramStateRef State) const {
1981   return State->get<ClassMembers>(*this) == nullptr;
1982 }
1983 
1984 bool EquivalenceClass::isTriviallyDead(ProgramStateRef State,
1985                                        SymbolReaper &Reaper) const {
1986   return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol());
1987 }
1988 
1989 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1990                                                       ProgramStateRef State,
1991                                                       SymbolRef First,
1992                                                       SymbolRef Second) {
1993   return markDisequal(RF, State, find(State, First), find(State, Second));
1994 }
1995 
1996 inline ProgramStateRef EquivalenceClass::markDisequal(RangeSet::Factory &RF,
1997                                                       ProgramStateRef State,
1998                                                       EquivalenceClass First,
1999                                                       EquivalenceClass Second) {
2000   return First.markDisequal(RF, State, Second);
2001 }
2002 
2003 inline ProgramStateRef
2004 EquivalenceClass::markDisequal(RangeSet::Factory &RF, ProgramStateRef State,
2005                                EquivalenceClass Other) const {
2006   // If we know that two classes are equal, we can only produce an infeasible
2007   // state.
2008   if (*this == Other) {
2009     return nullptr;
2010   }
2011 
2012   DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>();
2013   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2014 
2015   // Disequality is a symmetric relation, so if we mark A as disequal to B,
2016   // we should also mark B as disequalt to A.
2017   if (!addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, *this,
2018                             Other) ||
2019       !addToDisequalityInfo(DisequalityInfo, Constraints, RF, State, Other,
2020                             *this))
2021     return nullptr;
2022 
2023   assert(areFeasible(Constraints) && "Constraint manager shouldn't produce "
2024                                      "a state with infeasible constraints");
2025 
2026   State = State->set<DisequalityMap>(DisequalityInfo);
2027   State = State->set<ConstraintRange>(Constraints);
2028 
2029   return State;
2030 }
2031 
2032 inline bool EquivalenceClass::addToDisequalityInfo(
2033     DisequalityMapTy &Info, ConstraintRangeTy &Constraints,
2034     RangeSet::Factory &RF, ProgramStateRef State, EquivalenceClass First,
2035     EquivalenceClass Second) {
2036 
2037   // 1. Get all of the required factories.
2038   DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>();
2039   ClassSet::Factory &CF = State->get_context<ClassSet>();
2040   ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>();
2041 
2042   // 2. Add Second to the set of classes disequal to First.
2043   const ClassSet *CurrentSet = Info.lookup(First);
2044   ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet();
2045   NewSet = CF.add(NewSet, Second);
2046 
2047   Info = F.add(Info, First, NewSet);
2048 
2049   // 3. If Second is known to be a constant, we can delete this point
2050   //    from the constraint asociated with First.
2051   //
2052   //    So, if Second == 10, it means that First != 10.
2053   //    At the same time, the same logic does not apply to ranges.
2054   if (const RangeSet *SecondConstraint = Constraints.lookup(Second))
2055     if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) {
2056 
2057       RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange(
2058           RF, State, First.getRepresentativeSymbol());
2059 
2060       FirstConstraint = RF.deletePoint(FirstConstraint, *Point);
2061 
2062       // If the First class is about to be constrained with an empty
2063       // range-set, the state is infeasible.
2064       if (FirstConstraint.isEmpty())
2065         return false;
2066 
2067       Constraints = CRF.add(Constraints, First, FirstConstraint);
2068     }
2069 
2070   return true;
2071 }
2072 
2073 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2074                                                  SymbolRef FirstSym,
2075                                                  SymbolRef SecondSym) {
2076   return EquivalenceClass::areEqual(State, find(State, FirstSym),
2077                                     find(State, SecondSym));
2078 }
2079 
2080 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State,
2081                                                  EquivalenceClass First,
2082                                                  EquivalenceClass Second) {
2083   // The same equivalence class => symbols are equal.
2084   if (First == Second)
2085     return true;
2086 
2087   // Let's check if we know anything about these two classes being not equal to
2088   // each other.
2089   ClassSet DisequalToFirst = First.getDisequalClasses(State);
2090   if (DisequalToFirst.contains(Second))
2091     return false;
2092 
2093   // It is not clear.
2094   return llvm::None;
2095 }
2096 
2097 // Iterate over all symbols and try to simplify them. Once a symbol is
2098 // simplified then we check if we can merge the simplified symbol's equivalence
2099 // class to this class. This way, we simplify not just the symbols but the
2100 // classes as well: we strive to keep the number of the classes to be the
2101 // absolute minimum.
2102 LLVM_NODISCARD ProgramStateRef
2103 EquivalenceClass::simplify(SValBuilder &SVB, RangeSet::Factory &F,
2104                            ProgramStateRef State, EquivalenceClass Class) {
2105   SymbolSet ClassMembers = Class.getClassMembers(State);
2106   for (const SymbolRef &MemberSym : ClassMembers) {
2107     SymbolRef SimplifiedMemberSym = ento::simplify(State, MemberSym);
2108     if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) {
2109       // The simplified symbol should be the member of the original Class,
2110       // however, it might be in another existing class at the moment. We
2111       // have to merge these classes.
2112       State = merge(F, State, MemberSym, SimplifiedMemberSym);
2113       if (!State)
2114         return nullptr;
2115     }
2116   }
2117   return State;
2118 }
2119 
2120 inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State,
2121                                                      SymbolRef Sym) {
2122   return find(State, Sym).getDisequalClasses(State);
2123 }
2124 
2125 inline ClassSet
2126 EquivalenceClass::getDisequalClasses(ProgramStateRef State) const {
2127   return getDisequalClasses(State->get<DisequalityMap>(),
2128                             State->get_context<ClassSet>());
2129 }
2130 
2131 inline ClassSet
2132 EquivalenceClass::getDisequalClasses(DisequalityMapTy Map,
2133                                      ClassSet::Factory &Factory) const {
2134   if (const ClassSet *DisequalClasses = Map.lookup(*this))
2135     return *DisequalClasses;
2136 
2137   return Factory.getEmptySet();
2138 }
2139 
2140 bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) {
2141   ClassMembersTy Members = State->get<ClassMembers>();
2142 
2143   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) {
2144     for (SymbolRef Member : ClassMembersPair.second) {
2145       // Every member of the class should have a mapping back to the class.
2146       if (find(State, Member) == ClassMembersPair.first) {
2147         continue;
2148       }
2149 
2150       return false;
2151     }
2152   }
2153 
2154   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2155   for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) {
2156     EquivalenceClass Class = DisequalityInfo.first;
2157     ClassSet DisequalClasses = DisequalityInfo.second;
2158 
2159     // There is no use in keeping empty sets in the map.
2160     if (DisequalClasses.isEmpty())
2161       return false;
2162 
2163     // Disequality is symmetrical, i.e. for every Class A and B that A != B,
2164     // B != A should also be true.
2165     for (EquivalenceClass DisequalClass : DisequalClasses) {
2166       const ClassSet *DisequalToDisequalClasses =
2167           Disequalities.lookup(DisequalClass);
2168 
2169       // It should be a set of at least one element: Class
2170       if (!DisequalToDisequalClasses ||
2171           !DisequalToDisequalClasses->contains(Class))
2172         return false;
2173     }
2174   }
2175 
2176   return true;
2177 }
2178 
2179 //===----------------------------------------------------------------------===//
2180 //                    RangeConstraintManager implementation
2181 //===----------------------------------------------------------------------===//
2182 
2183 bool RangeConstraintManager::canReasonAbout(SVal X) const {
2184   Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
2185   if (SymVal && SymVal->isExpression()) {
2186     const SymExpr *SE = SymVal->getSymbol();
2187 
2188     if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
2189       switch (SIE->getOpcode()) {
2190       // We don't reason yet about bitwise-constraints on symbolic values.
2191       case BO_And:
2192       case BO_Or:
2193       case BO_Xor:
2194         return false;
2195       // We don't reason yet about these arithmetic constraints on
2196       // symbolic values.
2197       case BO_Mul:
2198       case BO_Div:
2199       case BO_Rem:
2200       case BO_Shl:
2201       case BO_Shr:
2202         return false;
2203       // All other cases.
2204       default:
2205         return true;
2206       }
2207     }
2208 
2209     if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
2210       // FIXME: Handle <=> here.
2211       if (BinaryOperator::isEqualityOp(SSE->getOpcode()) ||
2212           BinaryOperator::isRelationalOp(SSE->getOpcode())) {
2213         // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
2214         // We've recently started producing Loc <> NonLoc comparisons (that
2215         // result from casts of one of the operands between eg. intptr_t and
2216         // void *), but we can't reason about them yet.
2217         if (Loc::isLocType(SSE->getLHS()->getType())) {
2218           return Loc::isLocType(SSE->getRHS()->getType());
2219         }
2220       }
2221     }
2222 
2223     return false;
2224   }
2225 
2226   return true;
2227 }
2228 
2229 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
2230                                                     SymbolRef Sym) {
2231   const RangeSet *Ranges = getConstraint(State, Sym);
2232 
2233   // If we don't have any information about this symbol, it's underconstrained.
2234   if (!Ranges)
2235     return ConditionTruthVal();
2236 
2237   // If we have a concrete value, see if it's zero.
2238   if (const llvm::APSInt *Value = Ranges->getConcreteValue())
2239     return *Value == 0;
2240 
2241   BasicValueFactory &BV = getBasicVals();
2242   APSIntType IntType = BV.getAPSIntType(Sym->getType());
2243   llvm::APSInt Zero = IntType.getZeroValue();
2244 
2245   // Check if zero is in the set of possible values.
2246   if (!Ranges->contains(Zero))
2247     return false;
2248 
2249   // Zero is a possible value, but it is not the /only/ possible value.
2250   return ConditionTruthVal();
2251 }
2252 
2253 const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
2254                                                       SymbolRef Sym) const {
2255   const RangeSet *T = getConstraint(St, Sym);
2256   return T ? T->getConcreteValue() : nullptr;
2257 }
2258 
2259 //===----------------------------------------------------------------------===//
2260 //                Remove dead symbols from existing constraints
2261 //===----------------------------------------------------------------------===//
2262 
2263 /// Scan all symbols referenced by the constraints. If the symbol is not alive
2264 /// as marked in LSymbols, mark it as dead in DSymbols.
2265 ProgramStateRef
2266 RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
2267                                            SymbolReaper &SymReaper) {
2268   ClassMembersTy ClassMembersMap = State->get<ClassMembers>();
2269   ClassMembersTy NewClassMembersMap = ClassMembersMap;
2270   ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>();
2271   SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>();
2272 
2273   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2274   ConstraintRangeTy NewConstraints = Constraints;
2275   ConstraintRangeTy::Factory &ConstraintFactory =
2276       State->get_context<ConstraintRange>();
2277 
2278   ClassMapTy Map = State->get<ClassMap>();
2279   ClassMapTy NewMap = Map;
2280   ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>();
2281 
2282   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2283   DisequalityMapTy::Factory &DisequalityFactory =
2284       State->get_context<DisequalityMap>();
2285   ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>();
2286 
2287   bool ClassMapChanged = false;
2288   bool MembersMapChanged = false;
2289   bool ConstraintMapChanged = false;
2290   bool DisequalitiesChanged = false;
2291 
2292   auto removeDeadClass = [&](EquivalenceClass Class) {
2293     // Remove associated constraint ranges.
2294     Constraints = ConstraintFactory.remove(Constraints, Class);
2295     ConstraintMapChanged = true;
2296 
2297     // Update disequality information to not hold any information on the
2298     // removed class.
2299     ClassSet DisequalClasses =
2300         Class.getDisequalClasses(Disequalities, ClassSetFactory);
2301     if (!DisequalClasses.isEmpty()) {
2302       for (EquivalenceClass DisequalClass : DisequalClasses) {
2303         ClassSet DisequalToDisequalSet =
2304             DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory);
2305         // DisequalToDisequalSet is guaranteed to be non-empty for consistent
2306         // disequality info.
2307         assert(!DisequalToDisequalSet.isEmpty());
2308         ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class);
2309 
2310         // No need in keeping an empty set.
2311         if (NewSet.isEmpty()) {
2312           Disequalities =
2313               DisequalityFactory.remove(Disequalities, DisequalClass);
2314         } else {
2315           Disequalities =
2316               DisequalityFactory.add(Disequalities, DisequalClass, NewSet);
2317         }
2318       }
2319       // Remove the data for the class
2320       Disequalities = DisequalityFactory.remove(Disequalities, Class);
2321       DisequalitiesChanged = true;
2322     }
2323   };
2324 
2325   // 1. Let's see if dead symbols are trivial and have associated constraints.
2326   for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair :
2327        Constraints) {
2328     EquivalenceClass Class = ClassConstraintPair.first;
2329     if (Class.isTriviallyDead(State, SymReaper)) {
2330       // If this class is trivial, we can remove its constraints right away.
2331       removeDeadClass(Class);
2332     }
2333   }
2334 
2335   // 2. We don't need to track classes for dead symbols.
2336   for (std::pair<SymbolRef, EquivalenceClass> SymbolClassPair : Map) {
2337     SymbolRef Sym = SymbolClassPair.first;
2338 
2339     if (SymReaper.isDead(Sym)) {
2340       ClassMapChanged = true;
2341       NewMap = ClassFactory.remove(NewMap, Sym);
2342     }
2343   }
2344 
2345   // 3. Remove dead members from classes and remove dead non-trivial classes
2346   //    and their constraints.
2347   for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair :
2348        ClassMembersMap) {
2349     EquivalenceClass Class = ClassMembersPair.first;
2350     SymbolSet LiveMembers = ClassMembersPair.second;
2351     bool MembersChanged = false;
2352 
2353     for (SymbolRef Member : ClassMembersPair.second) {
2354       if (SymReaper.isDead(Member)) {
2355         MembersChanged = true;
2356         LiveMembers = SetFactory.remove(LiveMembers, Member);
2357       }
2358     }
2359 
2360     // Check if the class changed.
2361     if (!MembersChanged)
2362       continue;
2363 
2364     MembersMapChanged = true;
2365 
2366     if (LiveMembers.isEmpty()) {
2367       // The class is dead now, we need to wipe it out of the members map...
2368       NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class);
2369 
2370       // ...and remove all of its constraints.
2371       removeDeadClass(Class);
2372     } else {
2373       // We need to change the members associated with the class.
2374       NewClassMembersMap =
2375           EMFactory.add(NewClassMembersMap, Class, LiveMembers);
2376     }
2377   }
2378 
2379   // 4. Update the state with new maps.
2380   //
2381   // Here we try to be humble and update a map only if it really changed.
2382   if (ClassMapChanged)
2383     State = State->set<ClassMap>(NewMap);
2384 
2385   if (MembersMapChanged)
2386     State = State->set<ClassMembers>(NewClassMembersMap);
2387 
2388   if (ConstraintMapChanged)
2389     State = State->set<ConstraintRange>(Constraints);
2390 
2391   if (DisequalitiesChanged)
2392     State = State->set<DisequalityMap>(Disequalities);
2393 
2394   assert(EquivalenceClass::isClassDataConsistent(State));
2395 
2396   return State;
2397 }
2398 
2399 RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
2400                                           SymbolRef Sym) {
2401   return SymbolicRangeInferrer::inferRange(F, State, Sym);
2402 }
2403 
2404 ProgramStateRef RangeConstraintManager::setRange(ProgramStateRef State,
2405                                                  SymbolRef Sym,
2406                                                  RangeSet Range) {
2407   return ConstraintAssignor::assign(State, getSValBuilder(), F, Sym, Range);
2408 }
2409 
2410 //===------------------------------------------------------------------------===
2411 // assumeSymX methods: protected interface for RangeConstraintManager.
2412 //===------------------------------------------------------------------------===/
2413 
2414 // The syntax for ranges below is mathematical, using [x, y] for closed ranges
2415 // and (x, y) for open ranges. These ranges are modular, corresponding with
2416 // a common treatment of C integer overflow. This means that these methods
2417 // do not have to worry about overflow; RangeSet::Intersect can handle such a
2418 // "wraparound" range.
2419 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
2420 // UINT_MAX, 0, 1, and 2.
2421 
2422 ProgramStateRef
2423 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
2424                                     const llvm::APSInt &Int,
2425                                     const llvm::APSInt &Adjustment) {
2426   // Before we do any real work, see if the value can even show up.
2427   APSIntType AdjustmentType(Adjustment);
2428   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2429     return St;
2430 
2431   llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment;
2432   RangeSet New = getRange(St, Sym);
2433   New = F.deletePoint(New, Point);
2434 
2435   return setRange(St, Sym, New);
2436 }
2437 
2438 ProgramStateRef
2439 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
2440                                     const llvm::APSInt &Int,
2441                                     const llvm::APSInt &Adjustment) {
2442   // Before we do any real work, see if the value can even show up.
2443   APSIntType AdjustmentType(Adjustment);
2444   if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
2445     return nullptr;
2446 
2447   // [Int-Adjustment, Int-Adjustment]
2448   llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
2449   RangeSet New = getRange(St, Sym);
2450   New = F.intersect(New, AdjInt);
2451 
2452   return setRange(St, Sym, New);
2453 }
2454 
2455 RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
2456                                                SymbolRef Sym,
2457                                                const llvm::APSInt &Int,
2458                                                const llvm::APSInt &Adjustment) {
2459   // Before we do any real work, see if the value can even show up.
2460   APSIntType AdjustmentType(Adjustment);
2461   switch (AdjustmentType.testInRange(Int, true)) {
2462   case APSIntType::RTR_Below:
2463     return F.getEmptySet();
2464   case APSIntType::RTR_Within:
2465     break;
2466   case APSIntType::RTR_Above:
2467     return getRange(St, Sym);
2468   }
2469 
2470   // Special case for Int == Min. This is always false.
2471   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2472   llvm::APSInt Min = AdjustmentType.getMinValue();
2473   if (ComparisonVal == Min)
2474     return F.getEmptySet();
2475 
2476   llvm::APSInt Lower = Min - Adjustment;
2477   llvm::APSInt Upper = ComparisonVal - Adjustment;
2478   --Upper;
2479 
2480   RangeSet Result = getRange(St, Sym);
2481   return F.intersect(Result, Lower, Upper);
2482 }
2483 
2484 ProgramStateRef
2485 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
2486                                     const llvm::APSInt &Int,
2487                                     const llvm::APSInt &Adjustment) {
2488   RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
2489   return setRange(St, Sym, New);
2490 }
2491 
2492 RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
2493                                                SymbolRef Sym,
2494                                                const llvm::APSInt &Int,
2495                                                const llvm::APSInt &Adjustment) {
2496   // Before we do any real work, see if the value can even show up.
2497   APSIntType AdjustmentType(Adjustment);
2498   switch (AdjustmentType.testInRange(Int, true)) {
2499   case APSIntType::RTR_Below:
2500     return getRange(St, Sym);
2501   case APSIntType::RTR_Within:
2502     break;
2503   case APSIntType::RTR_Above:
2504     return F.getEmptySet();
2505   }
2506 
2507   // Special case for Int == Max. This is always false.
2508   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2509   llvm::APSInt Max = AdjustmentType.getMaxValue();
2510   if (ComparisonVal == Max)
2511     return F.getEmptySet();
2512 
2513   llvm::APSInt Lower = ComparisonVal - Adjustment;
2514   llvm::APSInt Upper = Max - Adjustment;
2515   ++Lower;
2516 
2517   RangeSet SymRange = getRange(St, Sym);
2518   return F.intersect(SymRange, Lower, Upper);
2519 }
2520 
2521 ProgramStateRef
2522 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
2523                                     const llvm::APSInt &Int,
2524                                     const llvm::APSInt &Adjustment) {
2525   RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
2526   return setRange(St, Sym, New);
2527 }
2528 
2529 RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
2530                                                SymbolRef Sym,
2531                                                const llvm::APSInt &Int,
2532                                                const llvm::APSInt &Adjustment) {
2533   // Before we do any real work, see if the value can even show up.
2534   APSIntType AdjustmentType(Adjustment);
2535   switch (AdjustmentType.testInRange(Int, true)) {
2536   case APSIntType::RTR_Below:
2537     return getRange(St, Sym);
2538   case APSIntType::RTR_Within:
2539     break;
2540   case APSIntType::RTR_Above:
2541     return F.getEmptySet();
2542   }
2543 
2544   // Special case for Int == Min. This is always feasible.
2545   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2546   llvm::APSInt Min = AdjustmentType.getMinValue();
2547   if (ComparisonVal == Min)
2548     return getRange(St, Sym);
2549 
2550   llvm::APSInt Max = AdjustmentType.getMaxValue();
2551   llvm::APSInt Lower = ComparisonVal - Adjustment;
2552   llvm::APSInt Upper = Max - Adjustment;
2553 
2554   RangeSet SymRange = getRange(St, Sym);
2555   return F.intersect(SymRange, Lower, Upper);
2556 }
2557 
2558 ProgramStateRef
2559 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
2560                                     const llvm::APSInt &Int,
2561                                     const llvm::APSInt &Adjustment) {
2562   RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
2563   return setRange(St, Sym, New);
2564 }
2565 
2566 RangeSet
2567 RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS,
2568                                       const llvm::APSInt &Int,
2569                                       const llvm::APSInt &Adjustment) {
2570   // Before we do any real work, see if the value can even show up.
2571   APSIntType AdjustmentType(Adjustment);
2572   switch (AdjustmentType.testInRange(Int, true)) {
2573   case APSIntType::RTR_Below:
2574     return F.getEmptySet();
2575   case APSIntType::RTR_Within:
2576     break;
2577   case APSIntType::RTR_Above:
2578     return RS();
2579   }
2580 
2581   // Special case for Int == Max. This is always feasible.
2582   llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
2583   llvm::APSInt Max = AdjustmentType.getMaxValue();
2584   if (ComparisonVal == Max)
2585     return RS();
2586 
2587   llvm::APSInt Min = AdjustmentType.getMinValue();
2588   llvm::APSInt Lower = Min - Adjustment;
2589   llvm::APSInt Upper = ComparisonVal - Adjustment;
2590 
2591   RangeSet Default = RS();
2592   return F.intersect(Default, Lower, Upper);
2593 }
2594 
2595 RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
2596                                                SymbolRef Sym,
2597                                                const llvm::APSInt &Int,
2598                                                const llvm::APSInt &Adjustment) {
2599   return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
2600 }
2601 
2602 ProgramStateRef
2603 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
2604                                     const llvm::APSInt &Int,
2605                                     const llvm::APSInt &Adjustment) {
2606   RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
2607   return setRange(St, Sym, New);
2608 }
2609 
2610 ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
2611     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2612     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2613   RangeSet New = getSymGERange(State, Sym, From, Adjustment);
2614   if (New.isEmpty())
2615     return nullptr;
2616   RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
2617   return setRange(State, Sym, Out);
2618 }
2619 
2620 ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
2621     ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
2622     const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
2623   RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
2624   RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
2625   RangeSet New(F.add(RangeLT, RangeGT));
2626   return setRange(State, Sym, New);
2627 }
2628 
2629 //===----------------------------------------------------------------------===//
2630 // Pretty-printing.
2631 //===----------------------------------------------------------------------===//
2632 
2633 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State,
2634                                        const char *NL, unsigned int Space,
2635                                        bool IsDot) const {
2636   printConstraints(Out, State, NL, Space, IsDot);
2637   printEquivalenceClasses(Out, State, NL, Space, IsDot);
2638   printDisequalities(Out, State, NL, Space, IsDot);
2639 }
2640 
2641 static std::string toString(const SymbolRef &Sym) {
2642   std::string S;
2643   llvm::raw_string_ostream O(S);
2644   Sym->dumpToStream(O);
2645   return O.str();
2646 }
2647 
2648 void RangeConstraintManager::printConstraints(raw_ostream &Out,
2649                                               ProgramStateRef State,
2650                                               const char *NL,
2651                                               unsigned int Space,
2652                                               bool IsDot) const {
2653   ConstraintRangeTy Constraints = State->get<ConstraintRange>();
2654 
2655   Indent(Out, Space, IsDot) << "\"constraints\": ";
2656   if (Constraints.isEmpty()) {
2657     Out << "null," << NL;
2658     return;
2659   }
2660 
2661   std::map<std::string, RangeSet> OrderedConstraints;
2662   for (std::pair<EquivalenceClass, RangeSet> P : Constraints) {
2663     SymbolSet ClassMembers = P.first.getClassMembers(State);
2664     for (const SymbolRef &ClassMember : ClassMembers) {
2665       bool insertion_took_place;
2666       std::tie(std::ignore, insertion_took_place) =
2667           OrderedConstraints.insert({toString(ClassMember), P.second});
2668       assert(insertion_took_place &&
2669              "two symbols should not have the same dump");
2670     }
2671   }
2672 
2673   ++Space;
2674   Out << '[' << NL;
2675   bool First = true;
2676   for (std::pair<std::string, RangeSet> P : OrderedConstraints) {
2677     if (First) {
2678       First = false;
2679     } else {
2680       Out << ',';
2681       Out << NL;
2682     }
2683     Indent(Out, Space, IsDot)
2684         << "{ \"symbol\": \"" << P.first << "\", \"range\": \"";
2685     P.second.dump(Out);
2686     Out << "\" }";
2687   }
2688   Out << NL;
2689 
2690   --Space;
2691   Indent(Out, Space, IsDot) << "]," << NL;
2692 }
2693 
2694 static std::string toString(ProgramStateRef State, EquivalenceClass Class) {
2695   SymbolSet ClassMembers = Class.getClassMembers(State);
2696   llvm::SmallVector<SymbolRef, 8> ClassMembersSorted(ClassMembers.begin(),
2697                                                      ClassMembers.end());
2698   llvm::sort(ClassMembersSorted,
2699              [](const SymbolRef &LHS, const SymbolRef &RHS) {
2700                return toString(LHS) < toString(RHS);
2701              });
2702 
2703   bool FirstMember = true;
2704 
2705   std::string Str;
2706   llvm::raw_string_ostream Out(Str);
2707   Out << "[ ";
2708   for (SymbolRef ClassMember : ClassMembersSorted) {
2709     if (FirstMember)
2710       FirstMember = false;
2711     else
2712       Out << ", ";
2713     Out << "\"" << ClassMember << "\"";
2714   }
2715   Out << " ]";
2716   return Out.str();
2717 }
2718 
2719 void RangeConstraintManager::printEquivalenceClasses(raw_ostream &Out,
2720                                                      ProgramStateRef State,
2721                                                      const char *NL,
2722                                                      unsigned int Space,
2723                                                      bool IsDot) const {
2724   ClassMembersTy Members = State->get<ClassMembers>();
2725 
2726   Indent(Out, Space, IsDot) << "\"equivalence_classes\": ";
2727   if (Members.isEmpty()) {
2728     Out << "null," << NL;
2729     return;
2730   }
2731 
2732   std::set<std::string> MembersStr;
2733   for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members)
2734     MembersStr.insert(toString(State, ClassToSymbolSet.first));
2735 
2736   ++Space;
2737   Out << '[' << NL;
2738   bool FirstClass = true;
2739   for (const std::string &Str : MembersStr) {
2740     if (FirstClass) {
2741       FirstClass = false;
2742     } else {
2743       Out << ',';
2744       Out << NL;
2745     }
2746     Indent(Out, Space, IsDot);
2747     Out << Str;
2748   }
2749   Out << NL;
2750 
2751   --Space;
2752   Indent(Out, Space, IsDot) << "]," << NL;
2753 }
2754 
2755 void RangeConstraintManager::printDisequalities(raw_ostream &Out,
2756                                                 ProgramStateRef State,
2757                                                 const char *NL,
2758                                                 unsigned int Space,
2759                                                 bool IsDot) const {
2760   DisequalityMapTy Disequalities = State->get<DisequalityMap>();
2761 
2762   Indent(Out, Space, IsDot) << "\"disequality_info\": ";
2763   if (Disequalities.isEmpty()) {
2764     Out << "null," << NL;
2765     return;
2766   }
2767 
2768   // Transform the disequality info to an ordered map of
2769   // [string -> (ordered set of strings)]
2770   using EqClassesStrTy = std::set<std::string>;
2771   using DisequalityInfoStrTy = std::map<std::string, EqClassesStrTy>;
2772   DisequalityInfoStrTy DisequalityInfoStr;
2773   for (std::pair<EquivalenceClass, ClassSet> ClassToDisEqSet : Disequalities) {
2774     EquivalenceClass Class = ClassToDisEqSet.first;
2775     ClassSet DisequalClasses = ClassToDisEqSet.second;
2776     EqClassesStrTy MembersStr;
2777     for (EquivalenceClass DisEqClass : DisequalClasses)
2778       MembersStr.insert(toString(State, DisEqClass));
2779     DisequalityInfoStr.insert({toString(State, Class), MembersStr});
2780   }
2781 
2782   ++Space;
2783   Out << '[' << NL;
2784   bool FirstClass = true;
2785   for (std::pair<std::string, EqClassesStrTy> ClassToDisEqSet :
2786        DisequalityInfoStr) {
2787     const std::string &Class = ClassToDisEqSet.first;
2788     if (FirstClass) {
2789       FirstClass = false;
2790     } else {
2791       Out << ',';
2792       Out << NL;
2793     }
2794     Indent(Out, Space, IsDot) << "{" << NL;
2795     unsigned int DisEqSpace = Space + 1;
2796     Indent(Out, DisEqSpace, IsDot) << "\"class\": ";
2797     Out << Class;
2798     const EqClassesStrTy &DisequalClasses = ClassToDisEqSet.second;
2799     if (!DisequalClasses.empty()) {
2800       Out << "," << NL;
2801       Indent(Out, DisEqSpace, IsDot) << "\"disequal_to\": [" << NL;
2802       unsigned int DisEqClassSpace = DisEqSpace + 1;
2803       Indent(Out, DisEqClassSpace, IsDot);
2804       bool FirstDisEqClass = true;
2805       for (const std::string &DisEqClass : DisequalClasses) {
2806         if (FirstDisEqClass) {
2807           FirstDisEqClass = false;
2808         } else {
2809           Out << ',' << NL;
2810           Indent(Out, DisEqClassSpace, IsDot);
2811         }
2812         Out << DisEqClass;
2813       }
2814       Out << "]" << NL;
2815     }
2816     Indent(Out, Space, IsDot) << "}";
2817   }
2818   Out << NL;
2819 
2820   --Space;
2821   Indent(Out, Space, IsDot) << "]," << NL;
2822 }
2823