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