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