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