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