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 static SymbolRef simplify(ProgramStateRef State, SymbolRef Sym) { 1388 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1389 SVal SimplifiedVal = SVB.simplifySVal(State, SVB.makeSymbolVal(Sym)); 1390 return SimplifiedVal.getAsSymbol(); 1391 } 1392 1393 class RangeConstraintManager : public RangedConstraintManager { 1394 public: 1395 RangeConstraintManager(ExprEngine *EE, SValBuilder &SVB) 1396 : RangedConstraintManager(EE, SVB), F(getBasicVals()) {} 1397 1398 //===------------------------------------------------------------------===// 1399 // Implementation for interface from ConstraintManager. 1400 //===------------------------------------------------------------------===// 1401 1402 bool haveEqualConstraints(ProgramStateRef S1, 1403 ProgramStateRef S2) const override { 1404 // NOTE: ClassMembers are as simple as back pointers for ClassMap, 1405 // so comparing constraint ranges and class maps should be 1406 // sufficient. 1407 return S1->get<ConstraintRange>() == S2->get<ConstraintRange>() && 1408 S1->get<ClassMap>() == S2->get<ClassMap>(); 1409 } 1410 1411 bool canReasonAbout(SVal X) const override; 1412 1413 ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override; 1414 1415 const llvm::APSInt *getSymVal(ProgramStateRef State, 1416 SymbolRef Sym) const override; 1417 1418 ProgramStateRef removeDeadBindings(ProgramStateRef State, 1419 SymbolReaper &SymReaper) override; 1420 1421 void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n", 1422 unsigned int Space = 0, bool IsDot = false) const override; 1423 1424 //===------------------------------------------------------------------===// 1425 // Implementation for interface from RangedConstraintManager. 1426 //===------------------------------------------------------------------===// 1427 1428 ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym, 1429 const llvm::APSInt &V, 1430 const llvm::APSInt &Adjustment) override; 1431 1432 ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym, 1433 const llvm::APSInt &V, 1434 const llvm::APSInt &Adjustment) override; 1435 1436 ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym, 1437 const llvm::APSInt &V, 1438 const llvm::APSInt &Adjustment) override; 1439 1440 ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym, 1441 const llvm::APSInt &V, 1442 const llvm::APSInt &Adjustment) override; 1443 1444 ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym, 1445 const llvm::APSInt &V, 1446 const llvm::APSInt &Adjustment) override; 1447 1448 ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym, 1449 const llvm::APSInt &V, 1450 const llvm::APSInt &Adjustment) override; 1451 1452 ProgramStateRef assumeSymWithinInclusiveRange( 1453 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, 1454 const llvm::APSInt &To, const llvm::APSInt &Adjustment) override; 1455 1456 ProgramStateRef assumeSymOutsideInclusiveRange( 1457 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, 1458 const llvm::APSInt &To, const llvm::APSInt &Adjustment) override; 1459 1460 private: 1461 RangeSet::Factory F; 1462 1463 RangeSet getRange(ProgramStateRef State, SymbolRef Sym); 1464 RangeSet getRange(ProgramStateRef State, EquivalenceClass Class); 1465 1466 RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym, 1467 const llvm::APSInt &Int, 1468 const llvm::APSInt &Adjustment); 1469 RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym, 1470 const llvm::APSInt &Int, 1471 const llvm::APSInt &Adjustment); 1472 RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym, 1473 const llvm::APSInt &Int, 1474 const llvm::APSInt &Adjustment); 1475 RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS, 1476 const llvm::APSInt &Int, 1477 const llvm::APSInt &Adjustment); 1478 RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym, 1479 const llvm::APSInt &Int, 1480 const llvm::APSInt &Adjustment); 1481 1482 //===------------------------------------------------------------------===// 1483 // Equality tracking implementation 1484 //===------------------------------------------------------------------===// 1485 1486 ProgramStateRef trackEQ(RangeSet NewConstraint, ProgramStateRef State, 1487 SymbolRef Sym, const llvm::APSInt &Int, 1488 const llvm::APSInt &Adjustment) { 1489 return track<true>(NewConstraint, State, Sym, Int, Adjustment); 1490 } 1491 1492 ProgramStateRef trackNE(RangeSet NewConstraint, ProgramStateRef State, 1493 SymbolRef Sym, const llvm::APSInt &Int, 1494 const llvm::APSInt &Adjustment) { 1495 return track<false>(NewConstraint, State, Sym, Int, Adjustment); 1496 } 1497 1498 template <bool EQ> 1499 ProgramStateRef track(RangeSet NewConstraint, ProgramStateRef State, 1500 SymbolRef Sym, const llvm::APSInt &Int, 1501 const llvm::APSInt &Adjustment) { 1502 if (NewConstraint.isEmpty()) 1503 // This is an infeasible assumption. 1504 return nullptr; 1505 1506 if (SymbolRef SimplifiedSym = simplify(State, Sym)) 1507 Sym = SimplifiedSym; 1508 1509 if (ProgramStateRef NewState = setConstraint(State, Sym, NewConstraint)) { 1510 if (auto Equality = EqualityInfo::extract(Sym, Int, Adjustment)) { 1511 // If the original assumption is not Sym + Adjustment !=/</> Int, 1512 // we should invert IsEquality flag. 1513 Equality->IsEquality = Equality->IsEquality != EQ; 1514 return track(NewState, *Equality); 1515 } 1516 1517 return NewState; 1518 } 1519 1520 return nullptr; 1521 } 1522 1523 ProgramStateRef track(ProgramStateRef State, EqualityInfo ToTrack) { 1524 if (ToTrack.IsEquality) { 1525 return trackEquality(State, ToTrack.Left, ToTrack.Right); 1526 } 1527 return trackDisequality(State, ToTrack.Left, ToTrack.Right); 1528 } 1529 1530 ProgramStateRef trackDisequality(ProgramStateRef State, SymbolRef LHS, 1531 SymbolRef RHS) { 1532 return EquivalenceClass::markDisequal(getBasicVals(), F, State, LHS, RHS); 1533 } 1534 1535 ProgramStateRef trackEquality(ProgramStateRef State, SymbolRef LHS, 1536 SymbolRef RHS) { 1537 return EquivalenceClass::merge(getBasicVals(), F, State, LHS, RHS); 1538 } 1539 1540 LLVM_NODISCARD ProgramStateRef setConstraint(ProgramStateRef State, 1541 EquivalenceClass Class, 1542 RangeSet Constraint) { 1543 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 1544 ConstraintRangeTy::Factory &CF = State->get_context<ConstraintRange>(); 1545 1546 assert(!Constraint.isEmpty() && "New constraint should not be empty"); 1547 1548 // Add new constraint. 1549 Constraints = CF.add(Constraints, Class, Constraint); 1550 1551 // There is a chance that we might need to update constraints for the 1552 // classes that are known to be disequal to Class. 1553 // 1554 // In order for this to be even possible, the new constraint should 1555 // be simply a constant because we can't reason about range disequalities. 1556 if (const llvm::APSInt *Point = Constraint.getConcreteValue()) 1557 for (EquivalenceClass DisequalClass : Class.getDisequalClasses(State)) { 1558 RangeSet UpdatedConstraint = getRange(State, DisequalClass); 1559 UpdatedConstraint = F.deletePoint(UpdatedConstraint, *Point); 1560 1561 // If we end up with at least one of the disequal classes to be 1562 // constrained with an empty range-set, the state is infeasible. 1563 if (UpdatedConstraint.isEmpty()) 1564 return nullptr; 1565 1566 Constraints = CF.add(Constraints, DisequalClass, UpdatedConstraint); 1567 } 1568 1569 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce " 1570 "a state with infeasible constraints"); 1571 1572 return State->set<ConstraintRange>(Constraints); 1573 } 1574 1575 // Associate a constraint to a symbolic expression. First, we set the 1576 // constraint in the State, then we try to simplify existing symbolic 1577 // expressions based on the newly set constraint. 1578 LLVM_NODISCARD inline ProgramStateRef 1579 setConstraint(ProgramStateRef State, SymbolRef Sym, RangeSet Constraint) { 1580 assert(State); 1581 1582 State = setConstraint(State, EquivalenceClass::find(State, Sym), Constraint); 1583 if (!State) 1584 return nullptr; 1585 1586 // We have a chance to simplify existing symbolic values if the new 1587 // constraint is a constant. 1588 if (!Constraint.getConcreteValue()) 1589 return State; 1590 1591 llvm::SmallSet<EquivalenceClass, 4> SimplifiedClasses; 1592 // Iterate over all equivalence classes and try to simplify them. 1593 ClassMembersTy Members = State->get<ClassMembers>(); 1594 for (std::pair<EquivalenceClass, SymbolSet> ClassToSymbolSet : Members) { 1595 EquivalenceClass Class = ClassToSymbolSet.first; 1596 State = Class.simplify(getSValBuilder(), F, State); 1597 if (!State) 1598 return nullptr; 1599 SimplifiedClasses.insert(Class); 1600 } 1601 1602 // Trivial equivalence classes (those that have only one symbol member) are 1603 // not stored in the State. Thus, we must skim through the constraints as 1604 // well. And we try to simplify symbols in the constraints. 1605 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 1606 for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) { 1607 EquivalenceClass Class = ClassConstraint.first; 1608 if (SimplifiedClasses.count(Class)) // Already simplified. 1609 continue; 1610 State = Class.simplify(getSValBuilder(), F, State); 1611 if (!State) 1612 return nullptr; 1613 } 1614 1615 return State; 1616 } 1617 }; 1618 1619 } // end anonymous namespace 1620 1621 std::unique_ptr<ConstraintManager> 1622 ento::CreateRangeConstraintManager(ProgramStateManager &StMgr, 1623 ExprEngine *Eng) { 1624 return std::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder()); 1625 } 1626 1627 ConstraintMap ento::getConstraintMap(ProgramStateRef State) { 1628 ConstraintMap::Factory &F = State->get_context<ConstraintMap>(); 1629 ConstraintMap Result = F.getEmptyMap(); 1630 1631 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 1632 for (std::pair<EquivalenceClass, RangeSet> ClassConstraint : Constraints) { 1633 EquivalenceClass Class = ClassConstraint.first; 1634 SymbolSet ClassMembers = Class.getClassMembers(State); 1635 assert(!ClassMembers.isEmpty() && 1636 "Class must always have at least one member!"); 1637 1638 SymbolRef Representative = *ClassMembers.begin(); 1639 Result = F.add(Result, Representative, ClassConstraint.second); 1640 } 1641 1642 return Result; 1643 } 1644 1645 //===----------------------------------------------------------------------===// 1646 // EqualityClass implementation details 1647 //===----------------------------------------------------------------------===// 1648 1649 inline EquivalenceClass EquivalenceClass::find(ProgramStateRef State, 1650 SymbolRef Sym) { 1651 assert(State && "State should not be null"); 1652 assert(Sym && "Symbol should not be null"); 1653 // We store far from all Symbol -> Class mappings 1654 if (const EquivalenceClass *NontrivialClass = State->get<ClassMap>(Sym)) 1655 return *NontrivialClass; 1656 1657 // This is a trivial class of Sym. 1658 return Sym; 1659 } 1660 1661 inline ProgramStateRef EquivalenceClass::merge(BasicValueFactory &BV, 1662 RangeSet::Factory &F, 1663 ProgramStateRef State, 1664 SymbolRef First, 1665 SymbolRef Second) { 1666 EquivalenceClass FirstClass = find(State, First); 1667 EquivalenceClass SecondClass = find(State, Second); 1668 1669 return FirstClass.merge(BV, F, State, SecondClass); 1670 } 1671 1672 inline ProgramStateRef EquivalenceClass::merge(BasicValueFactory &BV, 1673 RangeSet::Factory &F, 1674 ProgramStateRef State, 1675 EquivalenceClass Other) { 1676 // It is already the same class. 1677 if (*this == Other) 1678 return State; 1679 1680 // FIXME: As of now, we support only equivalence classes of the same type. 1681 // This limitation is connected to the lack of explicit casts in 1682 // our symbolic expression model. 1683 // 1684 // That means that for `int x` and `char y` we don't distinguish 1685 // between these two very different cases: 1686 // * `x == y` 1687 // * `(char)x == y` 1688 // 1689 // The moment we introduce symbolic casts, this restriction can be 1690 // lifted. 1691 if (getType() != Other.getType()) 1692 return State; 1693 1694 SymbolSet Members = getClassMembers(State); 1695 SymbolSet OtherMembers = Other.getClassMembers(State); 1696 1697 // We estimate the size of the class by the height of tree containing 1698 // its members. Merging is not a trivial operation, so it's easier to 1699 // merge the smaller class into the bigger one. 1700 if (Members.getHeight() >= OtherMembers.getHeight()) { 1701 return mergeImpl(BV, F, State, Members, Other, OtherMembers); 1702 } else { 1703 return Other.mergeImpl(BV, F, State, OtherMembers, *this, Members); 1704 } 1705 } 1706 1707 inline ProgramStateRef 1708 EquivalenceClass::mergeImpl(BasicValueFactory &ValueFactory, 1709 RangeSet::Factory &RangeFactory, 1710 ProgramStateRef State, SymbolSet MyMembers, 1711 EquivalenceClass Other, SymbolSet OtherMembers) { 1712 // Essentially what we try to recreate here is some kind of union-find 1713 // data structure. It does have certain limitations due to persistence 1714 // and the need to remove elements from classes. 1715 // 1716 // In this setting, EquialityClass object is the representative of the class 1717 // or the parent element. ClassMap is a mapping of class members to their 1718 // parent. Unlike the union-find structure, they all point directly to the 1719 // class representative because we don't have an opportunity to actually do 1720 // path compression when dealing with immutability. This means that we 1721 // compress paths every time we do merges. It also means that we lose 1722 // the main amortized complexity benefit from the original data structure. 1723 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 1724 ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>(); 1725 1726 // 1. If the merged classes have any constraints associated with them, we 1727 // need to transfer them to the class we have left. 1728 // 1729 // Intersection here makes perfect sense because both of these constraints 1730 // must hold for the whole new class. 1731 if (Optional<RangeSet> NewClassConstraint = 1732 intersect(ValueFactory, RangeFactory, getConstraint(State, *this), 1733 getConstraint(State, Other))) { 1734 // NOTE: Essentially, NewClassConstraint should NEVER be infeasible because 1735 // range inferrer shouldn't generate ranges incompatible with 1736 // equivalence classes. However, at the moment, due to imperfections 1737 // in the solver, it is possible and the merge function can also 1738 // return infeasible states aka null states. 1739 if (NewClassConstraint->isEmpty()) 1740 // Infeasible state 1741 return nullptr; 1742 1743 // No need in tracking constraints of a now-dissolved class. 1744 Constraints = CRF.remove(Constraints, Other); 1745 // Assign new constraints for this class. 1746 Constraints = CRF.add(Constraints, *this, *NewClassConstraint); 1747 1748 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce " 1749 "a state with infeasible constraints"); 1750 1751 State = State->set<ConstraintRange>(Constraints); 1752 } 1753 1754 // 2. Get ALL equivalence-related maps 1755 ClassMapTy Classes = State->get<ClassMap>(); 1756 ClassMapTy::Factory &CMF = State->get_context<ClassMap>(); 1757 1758 ClassMembersTy Members = State->get<ClassMembers>(); 1759 ClassMembersTy::Factory &MF = State->get_context<ClassMembers>(); 1760 1761 DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>(); 1762 DisequalityMapTy::Factory &DF = State->get_context<DisequalityMap>(); 1763 1764 ClassSet::Factory &CF = State->get_context<ClassSet>(); 1765 SymbolSet::Factory &F = getMembersFactory(State); 1766 1767 // 2. Merge members of the Other class into the current class. 1768 SymbolSet NewClassMembers = MyMembers; 1769 for (SymbolRef Sym : OtherMembers) { 1770 NewClassMembers = F.add(NewClassMembers, Sym); 1771 // *this is now the class for all these new symbols. 1772 Classes = CMF.add(Classes, Sym, *this); 1773 } 1774 1775 // 3. Adjust member mapping. 1776 // 1777 // No need in tracking members of a now-dissolved class. 1778 Members = MF.remove(Members, Other); 1779 // Now only the current class is mapped to all the symbols. 1780 Members = MF.add(Members, *this, NewClassMembers); 1781 1782 // 4. Update disequality relations 1783 ClassSet DisequalToOther = Other.getDisequalClasses(DisequalityInfo, CF); 1784 // We are about to merge two classes but they are already known to be 1785 // non-equal. This is a contradiction. 1786 if (DisequalToOther.contains(*this)) 1787 return nullptr; 1788 1789 if (!DisequalToOther.isEmpty()) { 1790 ClassSet DisequalToThis = getDisequalClasses(DisequalityInfo, CF); 1791 DisequalityInfo = DF.remove(DisequalityInfo, Other); 1792 1793 for (EquivalenceClass DisequalClass : DisequalToOther) { 1794 DisequalToThis = CF.add(DisequalToThis, DisequalClass); 1795 1796 // Disequality is a symmetric relation meaning that if 1797 // DisequalToOther not null then the set for DisequalClass is not 1798 // empty and has at least Other. 1799 ClassSet OriginalSetLinkedToOther = 1800 *DisequalityInfo.lookup(DisequalClass); 1801 1802 // Other will be eliminated and we should replace it with the bigger 1803 // united class. 1804 ClassSet NewSet = CF.remove(OriginalSetLinkedToOther, Other); 1805 NewSet = CF.add(NewSet, *this); 1806 1807 DisequalityInfo = DF.add(DisequalityInfo, DisequalClass, NewSet); 1808 } 1809 1810 DisequalityInfo = DF.add(DisequalityInfo, *this, DisequalToThis); 1811 State = State->set<DisequalityMap>(DisequalityInfo); 1812 } 1813 1814 // 5. Update the state 1815 State = State->set<ClassMap>(Classes); 1816 State = State->set<ClassMembers>(Members); 1817 1818 return State; 1819 } 1820 1821 inline SymbolSet::Factory & 1822 EquivalenceClass::getMembersFactory(ProgramStateRef State) { 1823 return State->get_context<SymbolSet>(); 1824 } 1825 1826 SymbolSet EquivalenceClass::getClassMembers(ProgramStateRef State) const { 1827 if (const SymbolSet *Members = State->get<ClassMembers>(*this)) 1828 return *Members; 1829 1830 // This class is trivial, so we need to construct a set 1831 // with just that one symbol from the class. 1832 SymbolSet::Factory &F = getMembersFactory(State); 1833 return F.add(F.getEmptySet(), getRepresentativeSymbol()); 1834 } 1835 1836 bool EquivalenceClass::isTrivial(ProgramStateRef State) const { 1837 return State->get<ClassMembers>(*this) == nullptr; 1838 } 1839 1840 bool EquivalenceClass::isTriviallyDead(ProgramStateRef State, 1841 SymbolReaper &Reaper) const { 1842 return isTrivial(State) && Reaper.isDead(getRepresentativeSymbol()); 1843 } 1844 1845 inline ProgramStateRef EquivalenceClass::markDisequal(BasicValueFactory &VF, 1846 RangeSet::Factory &RF, 1847 ProgramStateRef State, 1848 SymbolRef First, 1849 SymbolRef Second) { 1850 return markDisequal(VF, RF, State, find(State, First), find(State, Second)); 1851 } 1852 1853 inline ProgramStateRef EquivalenceClass::markDisequal(BasicValueFactory &VF, 1854 RangeSet::Factory &RF, 1855 ProgramStateRef State, 1856 EquivalenceClass First, 1857 EquivalenceClass Second) { 1858 return First.markDisequal(VF, RF, State, Second); 1859 } 1860 1861 inline ProgramStateRef 1862 EquivalenceClass::markDisequal(BasicValueFactory &VF, RangeSet::Factory &RF, 1863 ProgramStateRef State, 1864 EquivalenceClass Other) const { 1865 // If we know that two classes are equal, we can only produce an infeasible 1866 // state. 1867 if (*this == Other) { 1868 return nullptr; 1869 } 1870 1871 DisequalityMapTy DisequalityInfo = State->get<DisequalityMap>(); 1872 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 1873 1874 // Disequality is a symmetric relation, so if we mark A as disequal to B, 1875 // we should also mark B as disequalt to A. 1876 if (!addToDisequalityInfo(DisequalityInfo, Constraints, VF, RF, State, *this, 1877 Other) || 1878 !addToDisequalityInfo(DisequalityInfo, Constraints, VF, RF, State, Other, 1879 *this)) 1880 return nullptr; 1881 1882 assert(areFeasible(Constraints) && "Constraint manager shouldn't produce " 1883 "a state with infeasible constraints"); 1884 1885 State = State->set<DisequalityMap>(DisequalityInfo); 1886 State = State->set<ConstraintRange>(Constraints); 1887 1888 return State; 1889 } 1890 1891 inline bool EquivalenceClass::addToDisequalityInfo( 1892 DisequalityMapTy &Info, ConstraintRangeTy &Constraints, 1893 BasicValueFactory &VF, RangeSet::Factory &RF, ProgramStateRef State, 1894 EquivalenceClass First, EquivalenceClass Second) { 1895 1896 // 1. Get all of the required factories. 1897 DisequalityMapTy::Factory &F = State->get_context<DisequalityMap>(); 1898 ClassSet::Factory &CF = State->get_context<ClassSet>(); 1899 ConstraintRangeTy::Factory &CRF = State->get_context<ConstraintRange>(); 1900 1901 // 2. Add Second to the set of classes disequal to First. 1902 const ClassSet *CurrentSet = Info.lookup(First); 1903 ClassSet NewSet = CurrentSet ? *CurrentSet : CF.getEmptySet(); 1904 NewSet = CF.add(NewSet, Second); 1905 1906 Info = F.add(Info, First, NewSet); 1907 1908 // 3. If Second is known to be a constant, we can delete this point 1909 // from the constraint asociated with First. 1910 // 1911 // So, if Second == 10, it means that First != 10. 1912 // At the same time, the same logic does not apply to ranges. 1913 if (const RangeSet *SecondConstraint = Constraints.lookup(Second)) 1914 if (const llvm::APSInt *Point = SecondConstraint->getConcreteValue()) { 1915 1916 RangeSet FirstConstraint = SymbolicRangeInferrer::inferRange( 1917 VF, RF, State, First.getRepresentativeSymbol()); 1918 1919 FirstConstraint = RF.deletePoint(FirstConstraint, *Point); 1920 1921 // If the First class is about to be constrained with an empty 1922 // range-set, the state is infeasible. 1923 if (FirstConstraint.isEmpty()) 1924 return false; 1925 1926 Constraints = CRF.add(Constraints, First, FirstConstraint); 1927 } 1928 1929 return true; 1930 } 1931 1932 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, 1933 SymbolRef FirstSym, 1934 SymbolRef SecondSym) { 1935 return EquivalenceClass::areEqual(State, find(State, FirstSym), 1936 find(State, SecondSym)); 1937 } 1938 1939 inline Optional<bool> EquivalenceClass::areEqual(ProgramStateRef State, 1940 EquivalenceClass First, 1941 EquivalenceClass Second) { 1942 // The same equivalence class => symbols are equal. 1943 if (First == Second) 1944 return true; 1945 1946 // Let's check if we know anything about these two classes being not equal to 1947 // each other. 1948 ClassSet DisequalToFirst = First.getDisequalClasses(State); 1949 if (DisequalToFirst.contains(Second)) 1950 return false; 1951 1952 // It is not clear. 1953 return llvm::None; 1954 } 1955 1956 // Iterate over all symbols and try to simplify them. Once a symbol is 1957 // simplified then we check if we can merge the simplified symbol's equivalence 1958 // class to this class. This way, we simplify not just the symbols but the 1959 // classes as well: we strive to keep the number of the classes to be the 1960 // absolute minimum. 1961 LLVM_NODISCARD ProgramStateRef EquivalenceClass::simplify( 1962 SValBuilder &SVB, RangeSet::Factory &F, ProgramStateRef State) { 1963 SymbolSet ClassMembers = getClassMembers(State); 1964 for (const SymbolRef &MemberSym : ClassMembers) { 1965 SymbolRef SimplifiedMemberSym = ::simplify(State, MemberSym); 1966 if (SimplifiedMemberSym && MemberSym != SimplifiedMemberSym) { 1967 EquivalenceClass ClassOfSimplifiedSym = 1968 EquivalenceClass::find(State, SimplifiedMemberSym); 1969 // The simplified symbol should be the member of the original Class, 1970 // however, it might be in another existing class at the moment. We 1971 // have to merge these classes. 1972 State = merge(SVB.getBasicValueFactory(), F, State, ClassOfSimplifiedSym); 1973 if (!State) 1974 return nullptr; 1975 } 1976 } 1977 return State; 1978 } 1979 1980 inline ClassSet EquivalenceClass::getDisequalClasses(ProgramStateRef State, 1981 SymbolRef Sym) { 1982 return find(State, Sym).getDisequalClasses(State); 1983 } 1984 1985 inline ClassSet 1986 EquivalenceClass::getDisequalClasses(ProgramStateRef State) const { 1987 return getDisequalClasses(State->get<DisequalityMap>(), 1988 State->get_context<ClassSet>()); 1989 } 1990 1991 inline ClassSet 1992 EquivalenceClass::getDisequalClasses(DisequalityMapTy Map, 1993 ClassSet::Factory &Factory) const { 1994 if (const ClassSet *DisequalClasses = Map.lookup(*this)) 1995 return *DisequalClasses; 1996 1997 return Factory.getEmptySet(); 1998 } 1999 2000 bool EquivalenceClass::isClassDataConsistent(ProgramStateRef State) { 2001 ClassMembersTy Members = State->get<ClassMembers>(); 2002 2003 for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : Members) { 2004 for (SymbolRef Member : ClassMembersPair.second) { 2005 // Every member of the class should have a mapping back to the class. 2006 if (find(State, Member) == ClassMembersPair.first) { 2007 continue; 2008 } 2009 2010 return false; 2011 } 2012 } 2013 2014 DisequalityMapTy Disequalities = State->get<DisequalityMap>(); 2015 for (std::pair<EquivalenceClass, ClassSet> DisequalityInfo : Disequalities) { 2016 EquivalenceClass Class = DisequalityInfo.first; 2017 ClassSet DisequalClasses = DisequalityInfo.second; 2018 2019 // There is no use in keeping empty sets in the map. 2020 if (DisequalClasses.isEmpty()) 2021 return false; 2022 2023 // Disequality is symmetrical, i.e. for every Class A and B that A != B, 2024 // B != A should also be true. 2025 for (EquivalenceClass DisequalClass : DisequalClasses) { 2026 const ClassSet *DisequalToDisequalClasses = 2027 Disequalities.lookup(DisequalClass); 2028 2029 // It should be a set of at least one element: Class 2030 if (!DisequalToDisequalClasses || 2031 !DisequalToDisequalClasses->contains(Class)) 2032 return false; 2033 } 2034 } 2035 2036 return true; 2037 } 2038 2039 //===----------------------------------------------------------------------===// 2040 // RangeConstraintManager implementation 2041 //===----------------------------------------------------------------------===// 2042 2043 bool RangeConstraintManager::canReasonAbout(SVal X) const { 2044 Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>(); 2045 if (SymVal && SymVal->isExpression()) { 2046 const SymExpr *SE = SymVal->getSymbol(); 2047 2048 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) { 2049 switch (SIE->getOpcode()) { 2050 // We don't reason yet about bitwise-constraints on symbolic values. 2051 case BO_And: 2052 case BO_Or: 2053 case BO_Xor: 2054 return false; 2055 // We don't reason yet about these arithmetic constraints on 2056 // symbolic values. 2057 case BO_Mul: 2058 case BO_Div: 2059 case BO_Rem: 2060 case BO_Shl: 2061 case BO_Shr: 2062 return false; 2063 // All other cases. 2064 default: 2065 return true; 2066 } 2067 } 2068 2069 if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) { 2070 // FIXME: Handle <=> here. 2071 if (BinaryOperator::isEqualityOp(SSE->getOpcode()) || 2072 BinaryOperator::isRelationalOp(SSE->getOpcode())) { 2073 // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc. 2074 // We've recently started producing Loc <> NonLoc comparisons (that 2075 // result from casts of one of the operands between eg. intptr_t and 2076 // void *), but we can't reason about them yet. 2077 if (Loc::isLocType(SSE->getLHS()->getType())) { 2078 return Loc::isLocType(SSE->getRHS()->getType()); 2079 } 2080 } 2081 } 2082 2083 return false; 2084 } 2085 2086 return true; 2087 } 2088 2089 ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State, 2090 SymbolRef Sym) { 2091 const RangeSet *Ranges = getConstraint(State, Sym); 2092 2093 // If we don't have any information about this symbol, it's underconstrained. 2094 if (!Ranges) 2095 return ConditionTruthVal(); 2096 2097 // If we have a concrete value, see if it's zero. 2098 if (const llvm::APSInt *Value = Ranges->getConcreteValue()) 2099 return *Value == 0; 2100 2101 BasicValueFactory &BV = getBasicVals(); 2102 APSIntType IntType = BV.getAPSIntType(Sym->getType()); 2103 llvm::APSInt Zero = IntType.getZeroValue(); 2104 2105 // Check if zero is in the set of possible values. 2106 if (!Ranges->contains(Zero)) 2107 return false; 2108 2109 // Zero is a possible value, but it is not the /only/ possible value. 2110 return ConditionTruthVal(); 2111 } 2112 2113 const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St, 2114 SymbolRef Sym) const { 2115 const RangeSet *T = getConstraint(St, Sym); 2116 return T ? T->getConcreteValue() : nullptr; 2117 } 2118 2119 //===----------------------------------------------------------------------===// 2120 // Remove dead symbols from existing constraints 2121 //===----------------------------------------------------------------------===// 2122 2123 /// Scan all symbols referenced by the constraints. If the symbol is not alive 2124 /// as marked in LSymbols, mark it as dead in DSymbols. 2125 ProgramStateRef 2126 RangeConstraintManager::removeDeadBindings(ProgramStateRef State, 2127 SymbolReaper &SymReaper) { 2128 ClassMembersTy ClassMembersMap = State->get<ClassMembers>(); 2129 ClassMembersTy NewClassMembersMap = ClassMembersMap; 2130 ClassMembersTy::Factory &EMFactory = State->get_context<ClassMembers>(); 2131 SymbolSet::Factory &SetFactory = State->get_context<SymbolSet>(); 2132 2133 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 2134 ConstraintRangeTy NewConstraints = Constraints; 2135 ConstraintRangeTy::Factory &ConstraintFactory = 2136 State->get_context<ConstraintRange>(); 2137 2138 ClassMapTy Map = State->get<ClassMap>(); 2139 ClassMapTy NewMap = Map; 2140 ClassMapTy::Factory &ClassFactory = State->get_context<ClassMap>(); 2141 2142 DisequalityMapTy Disequalities = State->get<DisequalityMap>(); 2143 DisequalityMapTy::Factory &DisequalityFactory = 2144 State->get_context<DisequalityMap>(); 2145 ClassSet::Factory &ClassSetFactory = State->get_context<ClassSet>(); 2146 2147 bool ClassMapChanged = false; 2148 bool MembersMapChanged = false; 2149 bool ConstraintMapChanged = false; 2150 bool DisequalitiesChanged = false; 2151 2152 auto removeDeadClass = [&](EquivalenceClass Class) { 2153 // Remove associated constraint ranges. 2154 Constraints = ConstraintFactory.remove(Constraints, Class); 2155 ConstraintMapChanged = true; 2156 2157 // Update disequality information to not hold any information on the 2158 // removed class. 2159 ClassSet DisequalClasses = 2160 Class.getDisequalClasses(Disequalities, ClassSetFactory); 2161 if (!DisequalClasses.isEmpty()) { 2162 for (EquivalenceClass DisequalClass : DisequalClasses) { 2163 ClassSet DisequalToDisequalSet = 2164 DisequalClass.getDisequalClasses(Disequalities, ClassSetFactory); 2165 // DisequalToDisequalSet is guaranteed to be non-empty for consistent 2166 // disequality info. 2167 assert(!DisequalToDisequalSet.isEmpty()); 2168 ClassSet NewSet = ClassSetFactory.remove(DisequalToDisequalSet, Class); 2169 2170 // No need in keeping an empty set. 2171 if (NewSet.isEmpty()) { 2172 Disequalities = 2173 DisequalityFactory.remove(Disequalities, DisequalClass); 2174 } else { 2175 Disequalities = 2176 DisequalityFactory.add(Disequalities, DisequalClass, NewSet); 2177 } 2178 } 2179 // Remove the data for the class 2180 Disequalities = DisequalityFactory.remove(Disequalities, Class); 2181 DisequalitiesChanged = true; 2182 } 2183 }; 2184 2185 // 1. Let's see if dead symbols are trivial and have associated constraints. 2186 for (std::pair<EquivalenceClass, RangeSet> ClassConstraintPair : 2187 Constraints) { 2188 EquivalenceClass Class = ClassConstraintPair.first; 2189 if (Class.isTriviallyDead(State, SymReaper)) { 2190 // If this class is trivial, we can remove its constraints right away. 2191 removeDeadClass(Class); 2192 } 2193 } 2194 2195 // 2. We don't need to track classes for dead symbols. 2196 for (std::pair<SymbolRef, EquivalenceClass> SymbolClassPair : Map) { 2197 SymbolRef Sym = SymbolClassPair.first; 2198 2199 if (SymReaper.isDead(Sym)) { 2200 ClassMapChanged = true; 2201 NewMap = ClassFactory.remove(NewMap, Sym); 2202 } 2203 } 2204 2205 // 3. Remove dead members from classes and remove dead non-trivial classes 2206 // and their constraints. 2207 for (std::pair<EquivalenceClass, SymbolSet> ClassMembersPair : 2208 ClassMembersMap) { 2209 EquivalenceClass Class = ClassMembersPair.first; 2210 SymbolSet LiveMembers = ClassMembersPair.second; 2211 bool MembersChanged = false; 2212 2213 for (SymbolRef Member : ClassMembersPair.second) { 2214 if (SymReaper.isDead(Member)) { 2215 MembersChanged = true; 2216 LiveMembers = SetFactory.remove(LiveMembers, Member); 2217 } 2218 } 2219 2220 // Check if the class changed. 2221 if (!MembersChanged) 2222 continue; 2223 2224 MembersMapChanged = true; 2225 2226 if (LiveMembers.isEmpty()) { 2227 // The class is dead now, we need to wipe it out of the members map... 2228 NewClassMembersMap = EMFactory.remove(NewClassMembersMap, Class); 2229 2230 // ...and remove all of its constraints. 2231 removeDeadClass(Class); 2232 } else { 2233 // We need to change the members associated with the class. 2234 NewClassMembersMap = 2235 EMFactory.add(NewClassMembersMap, Class, LiveMembers); 2236 } 2237 } 2238 2239 // 4. Update the state with new maps. 2240 // 2241 // Here we try to be humble and update a map only if it really changed. 2242 if (ClassMapChanged) 2243 State = State->set<ClassMap>(NewMap); 2244 2245 if (MembersMapChanged) 2246 State = State->set<ClassMembers>(NewClassMembersMap); 2247 2248 if (ConstraintMapChanged) 2249 State = State->set<ConstraintRange>(Constraints); 2250 2251 if (DisequalitiesChanged) 2252 State = State->set<DisequalityMap>(Disequalities); 2253 2254 assert(EquivalenceClass::isClassDataConsistent(State)); 2255 2256 return State; 2257 } 2258 2259 RangeSet RangeConstraintManager::getRange(ProgramStateRef State, 2260 SymbolRef Sym) { 2261 return SymbolicRangeInferrer::inferRange(getBasicVals(), F, State, Sym); 2262 } 2263 2264 RangeSet RangeConstraintManager::getRange(ProgramStateRef State, 2265 EquivalenceClass Class) { 2266 return SymbolicRangeInferrer::inferRange(getBasicVals(), F, State, Class); 2267 } 2268 2269 //===------------------------------------------------------------------------=== 2270 // assumeSymX methods: protected interface for RangeConstraintManager. 2271 //===------------------------------------------------------------------------===/ 2272 2273 // The syntax for ranges below is mathematical, using [x, y] for closed ranges 2274 // and (x, y) for open ranges. These ranges are modular, corresponding with 2275 // a common treatment of C integer overflow. This means that these methods 2276 // do not have to worry about overflow; RangeSet::Intersect can handle such a 2277 // "wraparound" range. 2278 // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1, 2279 // UINT_MAX, 0, 1, and 2. 2280 2281 ProgramStateRef 2282 RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym, 2283 const llvm::APSInt &Int, 2284 const llvm::APSInt &Adjustment) { 2285 // Before we do any real work, see if the value can even show up. 2286 APSIntType AdjustmentType(Adjustment); 2287 if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within) 2288 return St; 2289 2290 llvm::APSInt Point = AdjustmentType.convert(Int) - Adjustment; 2291 2292 RangeSet New = getRange(St, Sym); 2293 New = F.deletePoint(New, Point); 2294 2295 return trackNE(New, St, Sym, Int, Adjustment); 2296 } 2297 2298 ProgramStateRef 2299 RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym, 2300 const llvm::APSInt &Int, 2301 const llvm::APSInt &Adjustment) { 2302 // Before we do any real work, see if the value can even show up. 2303 APSIntType AdjustmentType(Adjustment); 2304 if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within) 2305 return nullptr; 2306 2307 // [Int-Adjustment, Int-Adjustment] 2308 llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment; 2309 RangeSet New = getRange(St, Sym); 2310 New = F.intersect(New, AdjInt); 2311 2312 return trackEQ(New, St, Sym, Int, Adjustment); 2313 } 2314 2315 RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St, 2316 SymbolRef Sym, 2317 const llvm::APSInt &Int, 2318 const llvm::APSInt &Adjustment) { 2319 // Before we do any real work, see if the value can even show up. 2320 APSIntType AdjustmentType(Adjustment); 2321 switch (AdjustmentType.testInRange(Int, true)) { 2322 case APSIntType::RTR_Below: 2323 return F.getEmptySet(); 2324 case APSIntType::RTR_Within: 2325 break; 2326 case APSIntType::RTR_Above: 2327 return getRange(St, Sym); 2328 } 2329 2330 // Special case for Int == Min. This is always false. 2331 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int); 2332 llvm::APSInt Min = AdjustmentType.getMinValue(); 2333 if (ComparisonVal == Min) 2334 return F.getEmptySet(); 2335 2336 llvm::APSInt Lower = Min - Adjustment; 2337 llvm::APSInt Upper = ComparisonVal - Adjustment; 2338 --Upper; 2339 2340 RangeSet Result = getRange(St, Sym); 2341 return F.intersect(Result, Lower, Upper); 2342 } 2343 2344 ProgramStateRef 2345 RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym, 2346 const llvm::APSInt &Int, 2347 const llvm::APSInt &Adjustment) { 2348 RangeSet New = getSymLTRange(St, Sym, Int, Adjustment); 2349 return trackNE(New, St, Sym, Int, Adjustment); 2350 } 2351 2352 RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St, 2353 SymbolRef Sym, 2354 const llvm::APSInt &Int, 2355 const llvm::APSInt &Adjustment) { 2356 // Before we do any real work, see if the value can even show up. 2357 APSIntType AdjustmentType(Adjustment); 2358 switch (AdjustmentType.testInRange(Int, true)) { 2359 case APSIntType::RTR_Below: 2360 return getRange(St, Sym); 2361 case APSIntType::RTR_Within: 2362 break; 2363 case APSIntType::RTR_Above: 2364 return F.getEmptySet(); 2365 } 2366 2367 // Special case for Int == Max. This is always false. 2368 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int); 2369 llvm::APSInt Max = AdjustmentType.getMaxValue(); 2370 if (ComparisonVal == Max) 2371 return F.getEmptySet(); 2372 2373 llvm::APSInt Lower = ComparisonVal - Adjustment; 2374 llvm::APSInt Upper = Max - Adjustment; 2375 ++Lower; 2376 2377 RangeSet SymRange = getRange(St, Sym); 2378 return F.intersect(SymRange, Lower, Upper); 2379 } 2380 2381 ProgramStateRef 2382 RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym, 2383 const llvm::APSInt &Int, 2384 const llvm::APSInt &Adjustment) { 2385 RangeSet New = getSymGTRange(St, Sym, Int, Adjustment); 2386 return trackNE(New, St, Sym, Int, Adjustment); 2387 } 2388 2389 RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St, 2390 SymbolRef Sym, 2391 const llvm::APSInt &Int, 2392 const llvm::APSInt &Adjustment) { 2393 // Before we do any real work, see if the value can even show up. 2394 APSIntType AdjustmentType(Adjustment); 2395 switch (AdjustmentType.testInRange(Int, true)) { 2396 case APSIntType::RTR_Below: 2397 return getRange(St, Sym); 2398 case APSIntType::RTR_Within: 2399 break; 2400 case APSIntType::RTR_Above: 2401 return F.getEmptySet(); 2402 } 2403 2404 // Special case for Int == Min. This is always feasible. 2405 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int); 2406 llvm::APSInt Min = AdjustmentType.getMinValue(); 2407 if (ComparisonVal == Min) 2408 return getRange(St, Sym); 2409 2410 llvm::APSInt Max = AdjustmentType.getMaxValue(); 2411 llvm::APSInt Lower = ComparisonVal - Adjustment; 2412 llvm::APSInt Upper = Max - Adjustment; 2413 2414 RangeSet SymRange = getRange(St, Sym); 2415 return F.intersect(SymRange, Lower, Upper); 2416 } 2417 2418 ProgramStateRef 2419 RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym, 2420 const llvm::APSInt &Int, 2421 const llvm::APSInt &Adjustment) { 2422 RangeSet New = getSymGERange(St, Sym, Int, Adjustment); 2423 return New.isEmpty() ? nullptr : setConstraint(St, Sym, New); 2424 } 2425 2426 RangeSet 2427 RangeConstraintManager::getSymLERange(llvm::function_ref<RangeSet()> RS, 2428 const llvm::APSInt &Int, 2429 const llvm::APSInt &Adjustment) { 2430 // Before we do any real work, see if the value can even show up. 2431 APSIntType AdjustmentType(Adjustment); 2432 switch (AdjustmentType.testInRange(Int, true)) { 2433 case APSIntType::RTR_Below: 2434 return F.getEmptySet(); 2435 case APSIntType::RTR_Within: 2436 break; 2437 case APSIntType::RTR_Above: 2438 return RS(); 2439 } 2440 2441 // Special case for Int == Max. This is always feasible. 2442 llvm::APSInt ComparisonVal = AdjustmentType.convert(Int); 2443 llvm::APSInt Max = AdjustmentType.getMaxValue(); 2444 if (ComparisonVal == Max) 2445 return RS(); 2446 2447 llvm::APSInt Min = AdjustmentType.getMinValue(); 2448 llvm::APSInt Lower = Min - Adjustment; 2449 llvm::APSInt Upper = ComparisonVal - Adjustment; 2450 2451 RangeSet Default = RS(); 2452 return F.intersect(Default, Lower, Upper); 2453 } 2454 2455 RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St, 2456 SymbolRef Sym, 2457 const llvm::APSInt &Int, 2458 const llvm::APSInt &Adjustment) { 2459 return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment); 2460 } 2461 2462 ProgramStateRef 2463 RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym, 2464 const llvm::APSInt &Int, 2465 const llvm::APSInt &Adjustment) { 2466 RangeSet New = getSymLERange(St, Sym, Int, Adjustment); 2467 return New.isEmpty() ? nullptr : setConstraint(St, Sym, New); 2468 } 2469 2470 ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange( 2471 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, 2472 const llvm::APSInt &To, const llvm::APSInt &Adjustment) { 2473 RangeSet New = getSymGERange(State, Sym, From, Adjustment); 2474 if (New.isEmpty()) 2475 return nullptr; 2476 RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment); 2477 return Out.isEmpty() ? nullptr : setConstraint(State, Sym, Out); 2478 } 2479 2480 ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange( 2481 ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, 2482 const llvm::APSInt &To, const llvm::APSInt &Adjustment) { 2483 RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment); 2484 RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment); 2485 RangeSet New(F.add(RangeLT, RangeGT)); 2486 return New.isEmpty() ? nullptr : setConstraint(State, Sym, New); 2487 } 2488 2489 //===----------------------------------------------------------------------===// 2490 // Pretty-printing. 2491 //===----------------------------------------------------------------------===// 2492 2493 void RangeConstraintManager::printJson(raw_ostream &Out, ProgramStateRef State, 2494 const char *NL, unsigned int Space, 2495 bool IsDot) const { 2496 ConstraintRangeTy Constraints = State->get<ConstraintRange>(); 2497 2498 Indent(Out, Space, IsDot) << "\"constraints\": "; 2499 if (Constraints.isEmpty()) { 2500 Out << "null," << NL; 2501 return; 2502 } 2503 2504 ++Space; 2505 Out << '[' << NL; 2506 bool First = true; 2507 for (std::pair<EquivalenceClass, RangeSet> P : Constraints) { 2508 SymbolSet ClassMembers = P.first.getClassMembers(State); 2509 2510 // We can print the same constraint for every class member. 2511 for (SymbolRef ClassMember : ClassMembers) { 2512 if (First) { 2513 First = false; 2514 } else { 2515 Out << ','; 2516 Out << NL; 2517 } 2518 Indent(Out, Space, IsDot) 2519 << "{ \"symbol\": \"" << ClassMember << "\", \"range\": \""; 2520 P.second.dump(Out); 2521 Out << "\" }"; 2522 } 2523 } 2524 Out << NL; 2525 2526 --Space; 2527 Indent(Out, Space, IsDot) << "]," << NL; 2528 } 2529