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