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