RangeConstraintManager.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. //== RangeConstraintManager.cpp - Manage range constraints.------*- C++ -*--==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines RangeConstraintManager, a class that tracks simple
  11. // equality and inequality constraints on symbolic values of ProgramState.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "RangedConstraintManager.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 "llvm/ADT/FoldingSet.h"
  19. #include "llvm/ADT/ImmutableSet.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace clang;
  22. using namespace ento;
  23. /// A Range represents the closed range [from, to]. The caller must
  24. /// guarantee that from <= to. Note that Range is immutable, so as not
  25. /// to subvert RangeSet's immutability.
  26. namespace {
  27. class Range : public std::pair<const llvm::APSInt *, const llvm::APSInt *> {
  28. public:
  29. Range(const llvm::APSInt &from, const llvm::APSInt &to)
  30. : std::pair<const llvm::APSInt *, const llvm::APSInt *>(&from, &to) {
  31. assert(from <= to);
  32. }
  33. bool Includes(const llvm::APSInt &v) const {
  34. return *first <= v && v <= *second;
  35. }
  36. const llvm::APSInt &From() const { return *first; }
  37. const llvm::APSInt &To() const { return *second; }
  38. const llvm::APSInt *getConcreteValue() const {
  39. return &From() == &To() ? &From() : nullptr;
  40. }
  41. void Profile(llvm::FoldingSetNodeID &ID) const {
  42. ID.AddPointer(&From());
  43. ID.AddPointer(&To());
  44. }
  45. };
  46. class RangeTrait : public llvm::ImutContainerInfo<Range> {
  47. public:
  48. // When comparing if one Range is less than another, we should compare
  49. // the actual APSInt values instead of their pointers. This keeps the order
  50. // consistent (instead of comparing by pointer values) and can potentially
  51. // be used to speed up some of the operations in RangeSet.
  52. static inline bool isLess(key_type_ref lhs, key_type_ref rhs) {
  53. return *lhs.first < *rhs.first ||
  54. (!(*rhs.first < *lhs.first) && *lhs.second < *rhs.second);
  55. }
  56. };
  57. /// RangeSet contains a set of ranges. If the set is empty, then
  58. /// there the value of a symbol is overly constrained and there are no
  59. /// possible values for that symbol.
  60. class RangeSet {
  61. typedef llvm::ImmutableSet<Range, RangeTrait> PrimRangeSet;
  62. PrimRangeSet ranges; // no need to make const, since it is an
  63. // ImmutableSet - this allows default operator=
  64. // to work.
  65. public:
  66. typedef PrimRangeSet::Factory Factory;
  67. typedef PrimRangeSet::iterator iterator;
  68. RangeSet(PrimRangeSet RS) : ranges(RS) {}
  69. /// Create a new set with all ranges of this set and RS.
  70. /// Possible intersections are not checked here.
  71. RangeSet addRange(Factory &F, const RangeSet &RS) {
  72. PrimRangeSet Ranges(RS.ranges);
  73. for (const auto &range : ranges)
  74. Ranges = F.add(Ranges, range);
  75. return RangeSet(Ranges);
  76. }
  77. iterator begin() const { return ranges.begin(); }
  78. iterator end() const { return ranges.end(); }
  79. bool isEmpty() const { return ranges.isEmpty(); }
  80. /// Construct a new RangeSet representing '{ [from, to] }'.
  81. RangeSet(Factory &F, const llvm::APSInt &from, const llvm::APSInt &to)
  82. : ranges(F.add(F.getEmptySet(), Range(from, to))) {}
  83. /// Profile - Generates a hash profile of this RangeSet for use
  84. /// by FoldingSet.
  85. void Profile(llvm::FoldingSetNodeID &ID) const { ranges.Profile(ID); }
  86. /// getConcreteValue - If a symbol is contrained to equal a specific integer
  87. /// constant then this method returns that value. Otherwise, it returns
  88. /// NULL.
  89. const llvm::APSInt *getConcreteValue() const {
  90. return ranges.isSingleton() ? ranges.begin()->getConcreteValue() : nullptr;
  91. }
  92. private:
  93. void IntersectInRange(BasicValueFactory &BV, Factory &F,
  94. const llvm::APSInt &Lower, const llvm::APSInt &Upper,
  95. PrimRangeSet &newRanges, PrimRangeSet::iterator &i,
  96. PrimRangeSet::iterator &e) const {
  97. // There are six cases for each range R in the set:
  98. // 1. R is entirely before the intersection range.
  99. // 2. R is entirely after the intersection range.
  100. // 3. R contains the entire intersection range.
  101. // 4. R starts before the intersection range and ends in the middle.
  102. // 5. R starts in the middle of the intersection range and ends after it.
  103. // 6. R is entirely contained in the intersection range.
  104. // These correspond to each of the conditions below.
  105. for (/* i = begin(), e = end() */; i != e; ++i) {
  106. if (i->To() < Lower) {
  107. continue;
  108. }
  109. if (i->From() > Upper) {
  110. break;
  111. }
  112. if (i->Includes(Lower)) {
  113. if (i->Includes(Upper)) {
  114. newRanges =
  115. F.add(newRanges, Range(BV.getValue(Lower), BV.getValue(Upper)));
  116. break;
  117. } else
  118. newRanges = F.add(newRanges, Range(BV.getValue(Lower), i->To()));
  119. } else {
  120. if (i->Includes(Upper)) {
  121. newRanges = F.add(newRanges, Range(i->From(), BV.getValue(Upper)));
  122. break;
  123. } else
  124. newRanges = F.add(newRanges, *i);
  125. }
  126. }
  127. }
  128. const llvm::APSInt &getMinValue() const {
  129. assert(!isEmpty());
  130. return ranges.begin()->From();
  131. }
  132. bool pin(llvm::APSInt &Lower, llvm::APSInt &Upper) const {
  133. // This function has nine cases, the cartesian product of range-testing
  134. // both the upper and lower bounds against the symbol's type.
  135. // Each case requires a different pinning operation.
  136. // The function returns false if the described range is entirely outside
  137. // the range of values for the associated symbol.
  138. APSIntType Type(getMinValue());
  139. APSIntType::RangeTestResultKind LowerTest = Type.testInRange(Lower, true);
  140. APSIntType::RangeTestResultKind UpperTest = Type.testInRange(Upper, true);
  141. switch (LowerTest) {
  142. case APSIntType::RTR_Below:
  143. switch (UpperTest) {
  144. case APSIntType::RTR_Below:
  145. // The entire range is outside the symbol's set of possible values.
  146. // If this is a conventionally-ordered range, the state is infeasible.
  147. if (Lower <= Upper)
  148. return false;
  149. // However, if the range wraps around, it spans all possible values.
  150. Lower = Type.getMinValue();
  151. Upper = Type.getMaxValue();
  152. break;
  153. case APSIntType::RTR_Within:
  154. // The range starts below what's possible but ends within it. Pin.
  155. Lower = Type.getMinValue();
  156. Type.apply(Upper);
  157. break;
  158. case APSIntType::RTR_Above:
  159. // The range spans all possible values for the symbol. Pin.
  160. Lower = Type.getMinValue();
  161. Upper = Type.getMaxValue();
  162. break;
  163. }
  164. break;
  165. case APSIntType::RTR_Within:
  166. switch (UpperTest) {
  167. case APSIntType::RTR_Below:
  168. // The range wraps around, but all lower values are not possible.
  169. Type.apply(Lower);
  170. Upper = Type.getMaxValue();
  171. break;
  172. case APSIntType::RTR_Within:
  173. // The range may or may not wrap around, but both limits are valid.
  174. Type.apply(Lower);
  175. Type.apply(Upper);
  176. break;
  177. case APSIntType::RTR_Above:
  178. // The range starts within what's possible but ends above it. Pin.
  179. Type.apply(Lower);
  180. Upper = Type.getMaxValue();
  181. break;
  182. }
  183. break;
  184. case APSIntType::RTR_Above:
  185. switch (UpperTest) {
  186. case APSIntType::RTR_Below:
  187. // The range wraps but is outside the symbol's set of possible values.
  188. return false;
  189. case APSIntType::RTR_Within:
  190. // The range starts above what's possible but ends within it (wrap).
  191. Lower = Type.getMinValue();
  192. Type.apply(Upper);
  193. break;
  194. case APSIntType::RTR_Above:
  195. // The entire range is outside the symbol's set of possible values.
  196. // If this is a conventionally-ordered range, the state is infeasible.
  197. if (Lower <= Upper)
  198. return false;
  199. // However, if the range wraps around, it spans all possible values.
  200. Lower = Type.getMinValue();
  201. Upper = Type.getMaxValue();
  202. break;
  203. }
  204. break;
  205. }
  206. return true;
  207. }
  208. public:
  209. // Returns a set containing the values in the receiving set, intersected with
  210. // the closed range [Lower, Upper]. Unlike the Range type, this range uses
  211. // modular arithmetic, corresponding to the common treatment of C integer
  212. // overflow. Thus, if the Lower bound is greater than the Upper bound, the
  213. // range is taken to wrap around. This is equivalent to taking the
  214. // intersection with the two ranges [Min, Upper] and [Lower, Max],
  215. // or, alternatively, /removing/ all integers between Upper and Lower.
  216. RangeSet Intersect(BasicValueFactory &BV, Factory &F, llvm::APSInt Lower,
  217. llvm::APSInt Upper) const {
  218. if (!pin(Lower, Upper))
  219. return F.getEmptySet();
  220. PrimRangeSet newRanges = F.getEmptySet();
  221. PrimRangeSet::iterator i = begin(), e = end();
  222. if (Lower <= Upper)
  223. IntersectInRange(BV, F, Lower, Upper, newRanges, i, e);
  224. else {
  225. // The order of the next two statements is important!
  226. // IntersectInRange() does not reset the iteration state for i and e.
  227. // Therefore, the lower range most be handled first.
  228. IntersectInRange(BV, F, BV.getMinValue(Upper), Upper, newRanges, i, e);
  229. IntersectInRange(BV, F, Lower, BV.getMaxValue(Lower), newRanges, i, e);
  230. }
  231. return newRanges;
  232. }
  233. void print(raw_ostream &os) const {
  234. bool isFirst = true;
  235. os << "{ ";
  236. for (iterator i = begin(), e = end(); i != e; ++i) {
  237. if (isFirst)
  238. isFirst = false;
  239. else
  240. os << ", ";
  241. os << '[' << i->From().toString(10) << ", " << i->To().toString(10)
  242. << ']';
  243. }
  244. os << " }";
  245. }
  246. bool operator==(const RangeSet &other) const {
  247. return ranges == other.ranges;
  248. }
  249. };
  250. } // end anonymous namespace
  251. REGISTER_TRAIT_WITH_PROGRAMSTATE(ConstraintRange,
  252. CLANG_ENTO_PROGRAMSTATE_MAP(SymbolRef,
  253. RangeSet))
  254. namespace {
  255. class RangeConstraintManager : public RangedConstraintManager {
  256. public:
  257. RangeConstraintManager(SubEngine *SE, SValBuilder &SVB)
  258. : RangedConstraintManager(SE, SVB) {}
  259. //===------------------------------------------------------------------===//
  260. // Implementation for interface from ConstraintManager.
  261. //===------------------------------------------------------------------===//
  262. bool canReasonAbout(SVal X) const override;
  263. ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override;
  264. const llvm::APSInt *getSymVal(ProgramStateRef State,
  265. SymbolRef Sym) const override;
  266. ProgramStateRef removeDeadBindings(ProgramStateRef State,
  267. SymbolReaper &SymReaper) override;
  268. void print(ProgramStateRef State, raw_ostream &Out, const char *nl,
  269. const char *sep) override;
  270. //===------------------------------------------------------------------===//
  271. // Implementation for interface from RangedConstraintManager.
  272. //===------------------------------------------------------------------===//
  273. ProgramStateRef assumeSymNE(ProgramStateRef State, SymbolRef Sym,
  274. const llvm::APSInt &V,
  275. const llvm::APSInt &Adjustment) override;
  276. ProgramStateRef assumeSymEQ(ProgramStateRef State, SymbolRef Sym,
  277. const llvm::APSInt &V,
  278. const llvm::APSInt &Adjustment) override;
  279. ProgramStateRef assumeSymLT(ProgramStateRef State, SymbolRef Sym,
  280. const llvm::APSInt &V,
  281. const llvm::APSInt &Adjustment) override;
  282. ProgramStateRef assumeSymGT(ProgramStateRef State, SymbolRef Sym,
  283. const llvm::APSInt &V,
  284. const llvm::APSInt &Adjustment) override;
  285. ProgramStateRef assumeSymLE(ProgramStateRef State, SymbolRef Sym,
  286. const llvm::APSInt &V,
  287. const llvm::APSInt &Adjustment) override;
  288. ProgramStateRef assumeSymGE(ProgramStateRef State, SymbolRef Sym,
  289. const llvm::APSInt &V,
  290. const llvm::APSInt &Adjustment) override;
  291. ProgramStateRef assumeSymWithinInclusiveRange(
  292. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  293. const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
  294. ProgramStateRef assumeSymOutsideInclusiveRange(
  295. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  296. const llvm::APSInt &To, const llvm::APSInt &Adjustment) override;
  297. private:
  298. RangeSet::Factory F;
  299. RangeSet getRange(ProgramStateRef State, SymbolRef Sym);
  300. RangeSet getSymLTRange(ProgramStateRef St, SymbolRef Sym,
  301. const llvm::APSInt &Int,
  302. const llvm::APSInt &Adjustment);
  303. RangeSet getSymGTRange(ProgramStateRef St, SymbolRef Sym,
  304. const llvm::APSInt &Int,
  305. const llvm::APSInt &Adjustment);
  306. RangeSet getSymLERange(ProgramStateRef St, SymbolRef Sym,
  307. const llvm::APSInt &Int,
  308. const llvm::APSInt &Adjustment);
  309. RangeSet getSymLERange(llvm::function_ref<RangeSet()> RS,
  310. const llvm::APSInt &Int,
  311. const llvm::APSInt &Adjustment);
  312. RangeSet getSymGERange(ProgramStateRef St, SymbolRef Sym,
  313. const llvm::APSInt &Int,
  314. const llvm::APSInt &Adjustment);
  315. };
  316. } // end anonymous namespace
  317. std::unique_ptr<ConstraintManager>
  318. ento::CreateRangeConstraintManager(ProgramStateManager &StMgr, SubEngine *Eng) {
  319. return llvm::make_unique<RangeConstraintManager>(Eng, StMgr.getSValBuilder());
  320. }
  321. bool RangeConstraintManager::canReasonAbout(SVal X) const {
  322. Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
  323. if (SymVal && SymVal->isExpression()) {
  324. const SymExpr *SE = SymVal->getSymbol();
  325. if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
  326. switch (SIE->getOpcode()) {
  327. // We don't reason yet about bitwise-constraints on symbolic values.
  328. case BO_And:
  329. case BO_Or:
  330. case BO_Xor:
  331. return false;
  332. // We don't reason yet about these arithmetic constraints on
  333. // symbolic values.
  334. case BO_Mul:
  335. case BO_Div:
  336. case BO_Rem:
  337. case BO_Shl:
  338. case BO_Shr:
  339. return false;
  340. // All other cases.
  341. default:
  342. return true;
  343. }
  344. }
  345. if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
  346. if (BinaryOperator::isComparisonOp(SSE->getOpcode())) {
  347. // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
  348. if (Loc::isLocType(SSE->getLHS()->getType())) {
  349. assert(Loc::isLocType(SSE->getRHS()->getType()));
  350. return true;
  351. }
  352. }
  353. }
  354. return false;
  355. }
  356. return true;
  357. }
  358. ConditionTruthVal RangeConstraintManager::checkNull(ProgramStateRef State,
  359. SymbolRef Sym) {
  360. const RangeSet *Ranges = State->get<ConstraintRange>(Sym);
  361. // If we don't have any information about this symbol, it's underconstrained.
  362. if (!Ranges)
  363. return ConditionTruthVal();
  364. // If we have a concrete value, see if it's zero.
  365. if (const llvm::APSInt *Value = Ranges->getConcreteValue())
  366. return *Value == 0;
  367. BasicValueFactory &BV = getBasicVals();
  368. APSIntType IntType = BV.getAPSIntType(Sym->getType());
  369. llvm::APSInt Zero = IntType.getZeroValue();
  370. // Check if zero is in the set of possible values.
  371. if (Ranges->Intersect(BV, F, Zero, Zero).isEmpty())
  372. return false;
  373. // Zero is a possible value, but it is not the /only/ possible value.
  374. return ConditionTruthVal();
  375. }
  376. const llvm::APSInt *RangeConstraintManager::getSymVal(ProgramStateRef St,
  377. SymbolRef Sym) const {
  378. const ConstraintRangeTy::data_type *T = St->get<ConstraintRange>(Sym);
  379. return T ? T->getConcreteValue() : nullptr;
  380. }
  381. /// Scan all symbols referenced by the constraints. If the symbol is not alive
  382. /// as marked in LSymbols, mark it as dead in DSymbols.
  383. ProgramStateRef
  384. RangeConstraintManager::removeDeadBindings(ProgramStateRef State,
  385. SymbolReaper &SymReaper) {
  386. bool Changed = false;
  387. ConstraintRangeTy CR = State->get<ConstraintRange>();
  388. ConstraintRangeTy::Factory &CRFactory = State->get_context<ConstraintRange>();
  389. for (ConstraintRangeTy::iterator I = CR.begin(), E = CR.end(); I != E; ++I) {
  390. SymbolRef Sym = I.getKey();
  391. if (SymReaper.maybeDead(Sym)) {
  392. Changed = true;
  393. CR = CRFactory.remove(CR, Sym);
  394. }
  395. }
  396. return Changed ? State->set<ConstraintRange>(CR) : State;
  397. }
  398. /// Return a range set subtracting zero from \p Domain.
  399. static RangeSet assumeNonZero(
  400. BasicValueFactory &BV,
  401. RangeSet::Factory &F,
  402. SymbolRef Sym,
  403. RangeSet Domain) {
  404. APSIntType IntType = BV.getAPSIntType(Sym->getType());
  405. return Domain.Intersect(BV, F, ++IntType.getZeroValue(),
  406. --IntType.getZeroValue());
  407. }
  408. /// \brief Apply implicit constraints for bitwise OR- and AND-.
  409. /// For unsigned types, bitwise OR with a constant always returns
  410. /// a value greater-or-equal than the constant, and bitwise AND
  411. /// returns a value less-or-equal then the constant.
  412. ///
  413. /// Pattern matches the expression \p Sym against those rule,
  414. /// and applies the required constraints.
  415. /// \p Input Previously established expression range set
  416. static RangeSet applyBitwiseConstraints(
  417. BasicValueFactory &BV,
  418. RangeSet::Factory &F,
  419. RangeSet Input,
  420. const SymIntExpr* SIE) {
  421. QualType T = SIE->getType();
  422. bool IsUnsigned = T->isUnsignedIntegerType();
  423. const llvm::APSInt &RHS = SIE->getRHS();
  424. const llvm::APSInt &Zero = BV.getAPSIntType(T).getZeroValue();
  425. BinaryOperator::Opcode Operator = SIE->getOpcode();
  426. // For unsigned types, the output of bitwise-or is bigger-or-equal than RHS.
  427. if (Operator == BO_Or && IsUnsigned)
  428. return Input.Intersect(BV, F, RHS, BV.getMaxValue(T));
  429. // Bitwise-or with a non-zero constant is always non-zero.
  430. if (Operator == BO_Or && RHS != Zero)
  431. return assumeNonZero(BV, F, SIE, Input);
  432. // For unsigned types, or positive RHS,
  433. // bitwise-and output is always smaller-or-equal than RHS (assuming two's
  434. // complement representation of signed types).
  435. if (Operator == BO_And && (IsUnsigned || RHS >= Zero))
  436. return Input.Intersect(BV, F, BV.getMinValue(T), RHS);
  437. return Input;
  438. }
  439. RangeSet RangeConstraintManager::getRange(ProgramStateRef State,
  440. SymbolRef Sym) {
  441. if (ConstraintRangeTy::data_type *V = State->get<ConstraintRange>(Sym))
  442. return *V;
  443. // Lazily generate a new RangeSet representing all possible values for the
  444. // given symbol type.
  445. BasicValueFactory &BV = getBasicVals();
  446. QualType T = Sym->getType();
  447. RangeSet Result(F, BV.getMinValue(T), BV.getMaxValue(T));
  448. // References are known to be non-zero.
  449. if (T->isReferenceType())
  450. return assumeNonZero(BV, F, Sym, Result);
  451. // Known constraints on ranges of bitwise expressions.
  452. if (const SymIntExpr* SIE = dyn_cast<SymIntExpr>(Sym))
  453. return applyBitwiseConstraints(BV, F, Result, SIE);
  454. return Result;
  455. }
  456. //===------------------------------------------------------------------------===
  457. // assumeSymX methods: protected interface for RangeConstraintManager.
  458. //===------------------------------------------------------------------------===/
  459. // The syntax for ranges below is mathematical, using [x, y] for closed ranges
  460. // and (x, y) for open ranges. These ranges are modular, corresponding with
  461. // a common treatment of C integer overflow. This means that these methods
  462. // do not have to worry about overflow; RangeSet::Intersect can handle such a
  463. // "wraparound" range.
  464. // As an example, the range [UINT_MAX-1, 3) contains five values: UINT_MAX-1,
  465. // UINT_MAX, 0, 1, and 2.
  466. ProgramStateRef
  467. RangeConstraintManager::assumeSymNE(ProgramStateRef St, SymbolRef Sym,
  468. const llvm::APSInt &Int,
  469. const llvm::APSInt &Adjustment) {
  470. // Before we do any real work, see if the value can even show up.
  471. APSIntType AdjustmentType(Adjustment);
  472. if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
  473. return St;
  474. llvm::APSInt Lower = AdjustmentType.convert(Int) - Adjustment;
  475. llvm::APSInt Upper = Lower;
  476. --Lower;
  477. ++Upper;
  478. // [Int-Adjustment+1, Int-Adjustment-1]
  479. // Notice that the lower bound is greater than the upper bound.
  480. RangeSet New = getRange(St, Sym).Intersect(getBasicVals(), F, Upper, Lower);
  481. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  482. }
  483. ProgramStateRef
  484. RangeConstraintManager::assumeSymEQ(ProgramStateRef St, SymbolRef Sym,
  485. const llvm::APSInt &Int,
  486. const llvm::APSInt &Adjustment) {
  487. // Before we do any real work, see if the value can even show up.
  488. APSIntType AdjustmentType(Adjustment);
  489. if (AdjustmentType.testInRange(Int, true) != APSIntType::RTR_Within)
  490. return nullptr;
  491. // [Int-Adjustment, Int-Adjustment]
  492. llvm::APSInt AdjInt = AdjustmentType.convert(Int) - Adjustment;
  493. RangeSet New = getRange(St, Sym).Intersect(getBasicVals(), F, AdjInt, AdjInt);
  494. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  495. }
  496. RangeSet RangeConstraintManager::getSymLTRange(ProgramStateRef St,
  497. SymbolRef Sym,
  498. const llvm::APSInt &Int,
  499. const llvm::APSInt &Adjustment) {
  500. // Before we do any real work, see if the value can even show up.
  501. APSIntType AdjustmentType(Adjustment);
  502. switch (AdjustmentType.testInRange(Int, true)) {
  503. case APSIntType::RTR_Below:
  504. return F.getEmptySet();
  505. case APSIntType::RTR_Within:
  506. break;
  507. case APSIntType::RTR_Above:
  508. return getRange(St, Sym);
  509. }
  510. // Special case for Int == Min. This is always false.
  511. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  512. llvm::APSInt Min = AdjustmentType.getMinValue();
  513. if (ComparisonVal == Min)
  514. return F.getEmptySet();
  515. llvm::APSInt Lower = Min - Adjustment;
  516. llvm::APSInt Upper = ComparisonVal - Adjustment;
  517. --Upper;
  518. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  519. }
  520. ProgramStateRef
  521. RangeConstraintManager::assumeSymLT(ProgramStateRef St, SymbolRef Sym,
  522. const llvm::APSInt &Int,
  523. const llvm::APSInt &Adjustment) {
  524. RangeSet New = getSymLTRange(St, Sym, Int, Adjustment);
  525. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  526. }
  527. RangeSet RangeConstraintManager::getSymGTRange(ProgramStateRef St,
  528. SymbolRef Sym,
  529. const llvm::APSInt &Int,
  530. const llvm::APSInt &Adjustment) {
  531. // Before we do any real work, see if the value can even show up.
  532. APSIntType AdjustmentType(Adjustment);
  533. switch (AdjustmentType.testInRange(Int, true)) {
  534. case APSIntType::RTR_Below:
  535. return getRange(St, Sym);
  536. case APSIntType::RTR_Within:
  537. break;
  538. case APSIntType::RTR_Above:
  539. return F.getEmptySet();
  540. }
  541. // Special case for Int == Max. This is always false.
  542. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  543. llvm::APSInt Max = AdjustmentType.getMaxValue();
  544. if (ComparisonVal == Max)
  545. return F.getEmptySet();
  546. llvm::APSInt Lower = ComparisonVal - Adjustment;
  547. llvm::APSInt Upper = Max - Adjustment;
  548. ++Lower;
  549. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  550. }
  551. ProgramStateRef
  552. RangeConstraintManager::assumeSymGT(ProgramStateRef St, SymbolRef Sym,
  553. const llvm::APSInt &Int,
  554. const llvm::APSInt &Adjustment) {
  555. RangeSet New = getSymGTRange(St, Sym, Int, Adjustment);
  556. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  557. }
  558. RangeSet RangeConstraintManager::getSymGERange(ProgramStateRef St,
  559. SymbolRef Sym,
  560. const llvm::APSInt &Int,
  561. const llvm::APSInt &Adjustment) {
  562. // Before we do any real work, see if the value can even show up.
  563. APSIntType AdjustmentType(Adjustment);
  564. switch (AdjustmentType.testInRange(Int, true)) {
  565. case APSIntType::RTR_Below:
  566. return getRange(St, Sym);
  567. case APSIntType::RTR_Within:
  568. break;
  569. case APSIntType::RTR_Above:
  570. return F.getEmptySet();
  571. }
  572. // Special case for Int == Min. This is always feasible.
  573. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  574. llvm::APSInt Min = AdjustmentType.getMinValue();
  575. if (ComparisonVal == Min)
  576. return getRange(St, Sym);
  577. llvm::APSInt Max = AdjustmentType.getMaxValue();
  578. llvm::APSInt Lower = ComparisonVal - Adjustment;
  579. llvm::APSInt Upper = Max - Adjustment;
  580. return getRange(St, Sym).Intersect(getBasicVals(), F, Lower, Upper);
  581. }
  582. ProgramStateRef
  583. RangeConstraintManager::assumeSymGE(ProgramStateRef St, SymbolRef Sym,
  584. const llvm::APSInt &Int,
  585. const llvm::APSInt &Adjustment) {
  586. RangeSet New = getSymGERange(St, Sym, Int, Adjustment);
  587. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  588. }
  589. RangeSet RangeConstraintManager::getSymLERange(
  590. llvm::function_ref<RangeSet()> RS,
  591. const llvm::APSInt &Int,
  592. const llvm::APSInt &Adjustment) {
  593. // Before we do any real work, see if the value can even show up.
  594. APSIntType AdjustmentType(Adjustment);
  595. switch (AdjustmentType.testInRange(Int, true)) {
  596. case APSIntType::RTR_Below:
  597. return F.getEmptySet();
  598. case APSIntType::RTR_Within:
  599. break;
  600. case APSIntType::RTR_Above:
  601. return RS();
  602. }
  603. // Special case for Int == Max. This is always feasible.
  604. llvm::APSInt ComparisonVal = AdjustmentType.convert(Int);
  605. llvm::APSInt Max = AdjustmentType.getMaxValue();
  606. if (ComparisonVal == Max)
  607. return RS();
  608. llvm::APSInt Min = AdjustmentType.getMinValue();
  609. llvm::APSInt Lower = Min - Adjustment;
  610. llvm::APSInt Upper = ComparisonVal - Adjustment;
  611. return RS().Intersect(getBasicVals(), F, Lower, Upper);
  612. }
  613. RangeSet RangeConstraintManager::getSymLERange(ProgramStateRef St,
  614. SymbolRef Sym,
  615. const llvm::APSInt &Int,
  616. const llvm::APSInt &Adjustment) {
  617. return getSymLERange([&] { return getRange(St, Sym); }, Int, Adjustment);
  618. }
  619. ProgramStateRef
  620. RangeConstraintManager::assumeSymLE(ProgramStateRef St, SymbolRef Sym,
  621. const llvm::APSInt &Int,
  622. const llvm::APSInt &Adjustment) {
  623. RangeSet New = getSymLERange(St, Sym, Int, Adjustment);
  624. return New.isEmpty() ? nullptr : St->set<ConstraintRange>(Sym, New);
  625. }
  626. ProgramStateRef RangeConstraintManager::assumeSymWithinInclusiveRange(
  627. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  628. const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
  629. RangeSet New = getSymGERange(State, Sym, From, Adjustment);
  630. if (New.isEmpty())
  631. return nullptr;
  632. RangeSet Out = getSymLERange([&] { return New; }, To, Adjustment);
  633. return Out.isEmpty() ? nullptr : State->set<ConstraintRange>(Sym, Out);
  634. }
  635. ProgramStateRef RangeConstraintManager::assumeSymOutsideInclusiveRange(
  636. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  637. const llvm::APSInt &To, const llvm::APSInt &Adjustment) {
  638. RangeSet RangeLT = getSymLTRange(State, Sym, From, Adjustment);
  639. RangeSet RangeGT = getSymGTRange(State, Sym, To, Adjustment);
  640. RangeSet New(RangeLT.addRange(F, RangeGT));
  641. return New.isEmpty() ? nullptr : State->set<ConstraintRange>(Sym, New);
  642. }
  643. //===------------------------------------------------------------------------===
  644. // Pretty-printing.
  645. //===------------------------------------------------------------------------===/
  646. void RangeConstraintManager::print(ProgramStateRef St, raw_ostream &Out,
  647. const char *nl, const char *sep) {
  648. ConstraintRangeTy Ranges = St->get<ConstraintRange>();
  649. if (Ranges.isEmpty()) {
  650. Out << nl << sep << "Ranges are empty." << nl;
  651. return;
  652. }
  653. Out << nl << sep << "Ranges of symbol values:";
  654. for (ConstraintRangeTy::iterator I = Ranges.begin(), E = Ranges.end(); I != E;
  655. ++I) {
  656. Out << nl << ' ' << I.getKey() << " : ";
  657. I.getData().print(Out);
  658. }
  659. Out << nl;
  660. }