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