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