RangedConstraintManager.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. //== RangedConstraintManager.cpp --------------------------------*- 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 RangedConstraintManager, a class that provides a
  10. // range-based constraint manager interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/RangedConstraintManager.h"
  15. namespace clang {
  16. namespace ento {
  17. RangedConstraintManager::~RangedConstraintManager() {}
  18. ProgramStateRef RangedConstraintManager::assumeSym(ProgramStateRef State,
  19. SymbolRef Sym,
  20. bool Assumption) {
  21. Sym = simplify(State, Sym);
  22. // Handle SymbolData.
  23. if (isa<SymbolData>(Sym))
  24. return assumeSymUnsupported(State, Sym, Assumption);
  25. // Handle symbolic expression.
  26. if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(Sym)) {
  27. // We can only simplify expressions whose RHS is an integer.
  28. BinaryOperator::Opcode op = SIE->getOpcode();
  29. if (BinaryOperator::isComparisonOp(op) && op != BO_Cmp) {
  30. if (!Assumption)
  31. op = BinaryOperator::negateComparisonOp(op);
  32. return assumeSymRel(State, SIE->getLHS(), op, SIE->getRHS());
  33. }
  34. // Handle adjustment with non-comparison ops.
  35. const llvm::APSInt &Zero = getBasicVals().getValue(0, SIE->getType());
  36. return assumeSymRel(State, SIE, (Assumption ? BO_NE : BO_EQ), Zero);
  37. }
  38. if (const auto *SSE = dyn_cast<SymSymExpr>(Sym)) {
  39. BinaryOperator::Opcode Op = SSE->getOpcode();
  40. assert(BinaryOperator::isComparisonOp(Op));
  41. // We convert equality operations for pointers only.
  42. if (Loc::isLocType(SSE->getLHS()->getType()) &&
  43. Loc::isLocType(SSE->getRHS()->getType())) {
  44. // Translate "a != b" to "(b - a) != 0".
  45. // We invert the order of the operands as a heuristic for how loop
  46. // conditions are usually written ("begin != end") as compared to length
  47. // calculations ("end - begin"). The more correct thing to do would be to
  48. // canonicalize "a - b" and "b - a", which would allow us to treat
  49. // "a != b" and "b != a" the same.
  50. SymbolManager &SymMgr = getSymbolManager();
  51. QualType DiffTy = SymMgr.getContext().getPointerDiffType();
  52. SymbolRef Subtraction =
  53. SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub, SSE->getLHS(), DiffTy);
  54. const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
  55. Op = BinaryOperator::reverseComparisonOp(Op);
  56. if (!Assumption)
  57. Op = BinaryOperator::negateComparisonOp(Op);
  58. return assumeSymRel(State, Subtraction, Op, Zero);
  59. }
  60. if (BinaryOperator::isEqualityOp(Op)) {
  61. SymbolManager &SymMgr = getSymbolManager();
  62. QualType ExprType = SSE->getType();
  63. SymbolRef CanonicalEquality =
  64. SymMgr.getSymSymExpr(SSE->getLHS(), BO_EQ, SSE->getRHS(), ExprType);
  65. bool WasEqual = SSE->getOpcode() == BO_EQ;
  66. bool IsExpectedEqual = WasEqual == Assumption;
  67. const llvm::APSInt &Zero = getBasicVals().getValue(0, ExprType);
  68. if (IsExpectedEqual) {
  69. return assumeSymNE(State, CanonicalEquality, Zero, Zero);
  70. }
  71. return assumeSymEQ(State, CanonicalEquality, Zero, Zero);
  72. }
  73. }
  74. // If we get here, there's nothing else we can do but treat the symbol as
  75. // opaque.
  76. return assumeSymUnsupported(State, Sym, Assumption);
  77. }
  78. ProgramStateRef RangedConstraintManager::assumeSymInclusiveRange(
  79. ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From,
  80. const llvm::APSInt &To, bool InRange) {
  81. Sym = simplify(State, Sym);
  82. // Get the type used for calculating wraparound.
  83. BasicValueFactory &BVF = getBasicVals();
  84. APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
  85. llvm::APSInt Adjustment = WraparoundType.getZeroValue();
  86. SymbolRef AdjustedSym = Sym;
  87. computeAdjustment(AdjustedSym, Adjustment);
  88. // Convert the right-hand side integer as necessary.
  89. APSIntType ComparisonType = std::max(WraparoundType, APSIntType(From));
  90. llvm::APSInt ConvertedFrom = ComparisonType.convert(From);
  91. llvm::APSInt ConvertedTo = ComparisonType.convert(To);
  92. // Prefer unsigned comparisons.
  93. if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
  94. ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
  95. Adjustment.setIsSigned(false);
  96. if (InRange)
  97. return assumeSymWithinInclusiveRange(State, AdjustedSym, ConvertedFrom,
  98. ConvertedTo, Adjustment);
  99. return assumeSymOutsideInclusiveRange(State, AdjustedSym, ConvertedFrom,
  100. ConvertedTo, Adjustment);
  101. }
  102. ProgramStateRef
  103. RangedConstraintManager::assumeSymUnsupported(ProgramStateRef State,
  104. SymbolRef Sym, bool Assumption) {
  105. Sym = simplify(State, Sym);
  106. BasicValueFactory &BVF = getBasicVals();
  107. QualType T = Sym->getType();
  108. // Non-integer types are not supported.
  109. if (!T->isIntegralOrEnumerationType())
  110. return State;
  111. // Reverse the operation and add directly to state.
  112. const llvm::APSInt &Zero = BVF.getValue(0, T);
  113. if (Assumption)
  114. return assumeSymNE(State, Sym, Zero, Zero);
  115. else
  116. return assumeSymEQ(State, Sym, Zero, Zero);
  117. }
  118. ProgramStateRef RangedConstraintManager::assumeSymRel(ProgramStateRef State,
  119. SymbolRef Sym,
  120. BinaryOperator::Opcode Op,
  121. const llvm::APSInt &Int) {
  122. assert(BinaryOperator::isComparisonOp(Op) &&
  123. "Non-comparison ops should be rewritten as comparisons to zero.");
  124. // Simplification: translate an assume of a constraint of the form
  125. // "(exp comparison_op expr) != 0" to true into an assume of
  126. // "exp comparison_op expr" to true. (And similarly, an assume of the form
  127. // "(exp comparison_op expr) == 0" to true into an assume of
  128. // "exp comparison_op expr" to false.)
  129. if (Int == 0 && (Op == BO_EQ || Op == BO_NE)) {
  130. if (const BinarySymExpr *SE = dyn_cast<BinarySymExpr>(Sym))
  131. if (BinaryOperator::isComparisonOp(SE->getOpcode()))
  132. return assumeSym(State, Sym, (Op == BO_NE ? true : false));
  133. }
  134. // Get the type used for calculating wraparound.
  135. BasicValueFactory &BVF = getBasicVals();
  136. APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
  137. // We only handle simple comparisons of the form "$sym == constant"
  138. // or "($sym+constant1) == constant2".
  139. // The adjustment is "constant1" in the above expression. It's used to
  140. // "slide" the solution range around for modular arithmetic. For example,
  141. // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
  142. // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
  143. // the subclasses of SimpleConstraintManager to handle the adjustment.
  144. llvm::APSInt Adjustment = WraparoundType.getZeroValue();
  145. computeAdjustment(Sym, Adjustment);
  146. // Convert the right-hand side integer as necessary.
  147. APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
  148. llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
  149. // Prefer unsigned comparisons.
  150. if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
  151. ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
  152. Adjustment.setIsSigned(false);
  153. switch (Op) {
  154. default:
  155. llvm_unreachable("invalid operation not caught by assertion above");
  156. case BO_EQ:
  157. return assumeSymEQ(State, Sym, ConvertedInt, Adjustment);
  158. case BO_NE:
  159. return assumeSymNE(State, Sym, ConvertedInt, Adjustment);
  160. case BO_GT:
  161. return assumeSymGT(State, Sym, ConvertedInt, Adjustment);
  162. case BO_GE:
  163. return assumeSymGE(State, Sym, ConvertedInt, Adjustment);
  164. case BO_LT:
  165. return assumeSymLT(State, Sym, ConvertedInt, Adjustment);
  166. case BO_LE:
  167. return assumeSymLE(State, Sym, ConvertedInt, Adjustment);
  168. } // end switch
  169. }
  170. void RangedConstraintManager::computeAdjustment(SymbolRef &Sym,
  171. llvm::APSInt &Adjustment) {
  172. // Is it a "($sym+constant1)" expression?
  173. if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
  174. BinaryOperator::Opcode Op = SE->getOpcode();
  175. if (Op == BO_Add || Op == BO_Sub) {
  176. Sym = SE->getLHS();
  177. Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
  178. // Don't forget to negate the adjustment if it's being subtracted.
  179. // This should happen /after/ promotion, in case the value being
  180. // subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
  181. if (Op == BO_Sub)
  182. Adjustment = -Adjustment;
  183. }
  184. }
  185. }
  186. SVal simplifyToSVal(ProgramStateRef State, SymbolRef Sym) {
  187. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  188. return SVB.simplifySVal(State, SVB.makeSymbolVal(Sym));
  189. }
  190. SymbolRef simplify(ProgramStateRef State, SymbolRef Sym) {
  191. SVal SimplifiedVal = simplifyToSVal(State, Sym);
  192. if (SymbolRef SimplifiedSym = SimplifiedVal.getAsSymbol())
  193. return SimplifiedSym;
  194. return Sym;
  195. }
  196. } // end of namespace ento
  197. } // end of namespace clang