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