SimpleConstraintManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //== SimpleConstraintManager.cpp --------------------------------*- 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 SimpleConstraintManager, a class that holds code shared
  11. // between BasicConstraintManager and RangeConstraintManager.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "SimpleConstraintManager.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  18. namespace clang {
  19. namespace ento {
  20. SimpleConstraintManager::~SimpleConstraintManager() {}
  21. bool SimpleConstraintManager::canReasonAbout(SVal X) const {
  22. Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
  23. if (SymVal && SymVal->isExpression()) {
  24. const SymExpr *SE = SymVal->getSymbol();
  25. if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(SE)) {
  26. switch (SIE->getOpcode()) {
  27. // We don't reason yet about bitwise-constraints on symbolic values.
  28. case BO_And:
  29. case BO_Or:
  30. case BO_Xor:
  31. return false;
  32. // We don't reason yet about these arithmetic constraints on
  33. // symbolic values.
  34. case BO_Mul:
  35. case BO_Div:
  36. case BO_Rem:
  37. case BO_Shl:
  38. case BO_Shr:
  39. return false;
  40. // All other cases.
  41. default:
  42. return true;
  43. }
  44. }
  45. if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(SE)) {
  46. if (BinaryOperator::isComparisonOp(SSE->getOpcode())) {
  47. // We handle Loc <> Loc comparisons, but not (yet) NonLoc <> NonLoc.
  48. if (Loc::isLocType(SSE->getLHS()->getType())) {
  49. assert(Loc::isLocType(SSE->getRHS()->getType()));
  50. return true;
  51. }
  52. }
  53. }
  54. return false;
  55. }
  56. return true;
  57. }
  58. ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
  59. DefinedSVal Cond,
  60. bool Assumption) {
  61. // If we have a Loc value, cast it to a bool NonLoc first.
  62. if (Optional<Loc> LV = Cond.getAs<Loc>()) {
  63. SValBuilder &SVB = state->getStateManager().getSValBuilder();
  64. QualType T;
  65. const MemRegion *MR = LV->getAsRegion();
  66. if (const TypedRegion *TR = dyn_cast_or_null<TypedRegion>(MR))
  67. T = TR->getLocationType();
  68. else
  69. T = SVB.getContext().VoidPtrTy;
  70. Cond = SVB.evalCast(*LV, SVB.getContext().BoolTy, T).castAs<DefinedSVal>();
  71. }
  72. return assume(state, Cond.castAs<NonLoc>(), Assumption);
  73. }
  74. ProgramStateRef SimpleConstraintManager::assume(ProgramStateRef state,
  75. NonLoc cond,
  76. bool assumption) {
  77. state = assumeAux(state, cond, assumption);
  78. if (NotifyAssumeClients && SU)
  79. return SU->processAssume(state, cond, assumption);
  80. return state;
  81. }
  82. ProgramStateRef
  83. SimpleConstraintManager::assumeAuxForSymbol(ProgramStateRef State,
  84. SymbolRef Sym, bool Assumption) {
  85. BasicValueFactory &BVF = getBasicVals();
  86. QualType T = Sym->getType();
  87. // None of the constraint solvers currently support non-integer types.
  88. if (!T->isIntegralOrEnumerationType())
  89. return State;
  90. const llvm::APSInt &zero = BVF.getValue(0, T);
  91. if (Assumption)
  92. return assumeSymNE(State, Sym, zero, zero);
  93. else
  94. return assumeSymEQ(State, Sym, zero, zero);
  95. }
  96. ProgramStateRef SimpleConstraintManager::assumeAux(ProgramStateRef state,
  97. NonLoc Cond,
  98. bool Assumption) {
  99. // We cannot reason about SymSymExprs, and can only reason about some
  100. // SymIntExprs.
  101. if (!canReasonAbout(Cond)) {
  102. // Just add the constraint to the expression without trying to simplify.
  103. SymbolRef sym = Cond.getAsSymExpr();
  104. return assumeAuxForSymbol(state, sym, Assumption);
  105. }
  106. switch (Cond.getSubKind()) {
  107. default:
  108. llvm_unreachable("'Assume' not implemented for this NonLoc");
  109. case nonloc::SymbolValKind: {
  110. nonloc::SymbolVal SV = Cond.castAs<nonloc::SymbolVal>();
  111. SymbolRef sym = SV.getSymbol();
  112. assert(sym);
  113. // Handle SymbolData.
  114. if (!SV.isExpression()) {
  115. return assumeAuxForSymbol(state, sym, Assumption);
  116. // Handle symbolic expression.
  117. } else if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(sym)) {
  118. // We can only simplify expressions whose RHS is an integer.
  119. BinaryOperator::Opcode op = SE->getOpcode();
  120. if (BinaryOperator::isComparisonOp(op)) {
  121. if (!Assumption)
  122. op = BinaryOperator::negateComparisonOp(op);
  123. return assumeSymRel(state, SE->getLHS(), op, SE->getRHS());
  124. }
  125. } else if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(sym)) {
  126. // Translate "a != b" to "(b - a) != 0".
  127. // We invert the order of the operands as a heuristic for how loop
  128. // conditions are usually written ("begin != end") as compared to length
  129. // calculations ("end - begin"). The more correct thing to do would be to
  130. // canonicalize "a - b" and "b - a", which would allow us to treat
  131. // "a != b" and "b != a" the same.
  132. SymbolManager &SymMgr = getSymbolManager();
  133. BinaryOperator::Opcode Op = SSE->getOpcode();
  134. assert(BinaryOperator::isComparisonOp(Op));
  135. // For now, we only support comparing pointers.
  136. assert(Loc::isLocType(SSE->getLHS()->getType()));
  137. assert(Loc::isLocType(SSE->getRHS()->getType()));
  138. QualType DiffTy = SymMgr.getContext().getPointerDiffType();
  139. SymbolRef Subtraction = SymMgr.getSymSymExpr(SSE->getRHS(), BO_Sub,
  140. SSE->getLHS(), DiffTy);
  141. const llvm::APSInt &Zero = getBasicVals().getValue(0, DiffTy);
  142. Op = BinaryOperator::reverseComparisonOp(Op);
  143. if (!Assumption)
  144. Op = BinaryOperator::negateComparisonOp(Op);
  145. return assumeSymRel(state, Subtraction, Op, Zero);
  146. }
  147. // If we get here, there's nothing else we can do but treat the symbol as
  148. // opaque.
  149. return assumeAuxForSymbol(state, sym, Assumption);
  150. }
  151. case nonloc::ConcreteIntKind: {
  152. bool b = Cond.castAs<nonloc::ConcreteInt>().getValue() != 0;
  153. bool isFeasible = b ? Assumption : !Assumption;
  154. return isFeasible ? state : nullptr;
  155. }
  156. case nonloc::LocAsIntegerKind:
  157. return assume(state, Cond.castAs<nonloc::LocAsInteger>().getLoc(),
  158. Assumption);
  159. } // end switch
  160. }
  161. ProgramStateRef SimpleConstraintManager::assumeWithinInclusiveRange(
  162. ProgramStateRef State, NonLoc Value, const llvm::APSInt &From,
  163. const llvm::APSInt &To, bool InRange) {
  164. assert(From.isUnsigned() == To.isUnsigned() &&
  165. From.getBitWidth() == To.getBitWidth() &&
  166. "Values should have same types!");
  167. if (!canReasonAbout(Value)) {
  168. // Just add the constraint to the expression without trying to simplify.
  169. SymbolRef Sym = Value.getAsSymExpr();
  170. assert(Sym);
  171. return assumeSymWithinInclusiveRange(State, Sym, From, To, InRange);
  172. }
  173. switch (Value.getSubKind()) {
  174. default:
  175. llvm_unreachable("'assumeWithinInclusiveRange' is not implemented"
  176. "for this NonLoc");
  177. case nonloc::LocAsIntegerKind:
  178. case nonloc::SymbolValKind: {
  179. if (SymbolRef Sym = Value.getAsSymbol())
  180. return assumeSymWithinInclusiveRange(State, Sym, From, To, InRange);
  181. return State;
  182. } // end switch
  183. case nonloc::ConcreteIntKind: {
  184. const llvm::APSInt &IntVal = Value.castAs<nonloc::ConcreteInt>().getValue();
  185. bool IsInRange = IntVal >= From && IntVal <= To;
  186. bool isFeasible = (IsInRange == InRange);
  187. return isFeasible ? State : nullptr;
  188. }
  189. } // end switch
  190. }
  191. static void computeAdjustment(SymbolRef &Sym, llvm::APSInt &Adjustment) {
  192. // Is it a "($sym+constant1)" expression?
  193. if (const SymIntExpr *SE = dyn_cast<SymIntExpr>(Sym)) {
  194. BinaryOperator::Opcode Op = SE->getOpcode();
  195. if (Op == BO_Add || Op == BO_Sub) {
  196. Sym = SE->getLHS();
  197. Adjustment = APSIntType(Adjustment).convert(SE->getRHS());
  198. // Don't forget to negate the adjustment if it's being subtracted.
  199. // This should happen /after/ promotion, in case the value being
  200. // subtracted is, say, CHAR_MIN, and the promoted type is 'int'.
  201. if (Op == BO_Sub)
  202. Adjustment = -Adjustment;
  203. }
  204. }
  205. }
  206. ProgramStateRef SimpleConstraintManager::assumeSymRel(ProgramStateRef state,
  207. const SymExpr *LHS,
  208. BinaryOperator::Opcode op,
  209. const llvm::APSInt& Int) {
  210. assert(BinaryOperator::isComparisonOp(op) &&
  211. "Non-comparison ops should be rewritten as comparisons to zero.");
  212. // Get the type used for calculating wraparound.
  213. BasicValueFactory &BVF = getBasicVals();
  214. APSIntType WraparoundType = BVF.getAPSIntType(LHS->getType());
  215. // We only handle simple comparisons of the form "$sym == constant"
  216. // or "($sym+constant1) == constant2".
  217. // The adjustment is "constant1" in the above expression. It's used to
  218. // "slide" the solution range around for modular arithmetic. For example,
  219. // x < 4 has the solution [0, 3]. x+2 < 4 has the solution [0-2, 3-2], which
  220. // in modular arithmetic is [0, 1] U [UINT_MAX-1, UINT_MAX]. It's up to
  221. // the subclasses of SimpleConstraintManager to handle the adjustment.
  222. SymbolRef Sym = LHS;
  223. llvm::APSInt Adjustment = WraparoundType.getZeroValue();
  224. computeAdjustment(Sym, Adjustment);
  225. // Convert the right-hand side integer as necessary.
  226. APSIntType ComparisonType = std::max(WraparoundType, APSIntType(Int));
  227. llvm::APSInt ConvertedInt = ComparisonType.convert(Int);
  228. // Prefer unsigned comparisons.
  229. if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
  230. ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
  231. Adjustment.setIsSigned(false);
  232. switch (op) {
  233. default:
  234. llvm_unreachable("invalid operation not caught by assertion above");
  235. case BO_EQ:
  236. return assumeSymEQ(state, Sym, ConvertedInt, Adjustment);
  237. case BO_NE:
  238. return assumeSymNE(state, Sym, ConvertedInt, Adjustment);
  239. case BO_GT:
  240. return assumeSymGT(state, Sym, ConvertedInt, Adjustment);
  241. case BO_GE:
  242. return assumeSymGE(state, Sym, ConvertedInt, Adjustment);
  243. case BO_LT:
  244. return assumeSymLT(state, Sym, ConvertedInt, Adjustment);
  245. case BO_LE:
  246. return assumeSymLE(state, Sym, ConvertedInt, Adjustment);
  247. } // end switch
  248. }
  249. ProgramStateRef
  250. SimpleConstraintManager::assumeSymWithinInclusiveRange(ProgramStateRef State,
  251. SymbolRef Sym,
  252. const llvm::APSInt &From,
  253. const llvm::APSInt &To,
  254. bool InRange) {
  255. // Get the type used for calculating wraparound.
  256. BasicValueFactory &BVF = getBasicVals();
  257. APSIntType WraparoundType = BVF.getAPSIntType(Sym->getType());
  258. llvm::APSInt Adjustment = WraparoundType.getZeroValue();
  259. SymbolRef AdjustedSym = Sym;
  260. computeAdjustment(AdjustedSym, Adjustment);
  261. // Convert the right-hand side integer as necessary.
  262. APSIntType ComparisonType = std::max(WraparoundType, APSIntType(From));
  263. llvm::APSInt ConvertedFrom = ComparisonType.convert(From);
  264. llvm::APSInt ConvertedTo = ComparisonType.convert(To);
  265. // Prefer unsigned comparisons.
  266. if (ComparisonType.getBitWidth() == WraparoundType.getBitWidth() &&
  267. ComparisonType.isUnsigned() && !WraparoundType.isUnsigned())
  268. Adjustment.setIsSigned(false);
  269. if (InRange)
  270. return assumeSymbolWithinInclusiveRange(State, AdjustedSym, ConvertedFrom,
  271. ConvertedTo, Adjustment);
  272. return assumeSymbolOutOfInclusiveRange(State, AdjustedSym, ConvertedFrom,
  273. ConvertedTo, Adjustment);
  274. }
  275. } // end of namespace ento
  276. } // end of namespace clang