clang 19.0.0git
SMTConstraintManager.h
Go to the documentation of this file.
1//== SMTConstraintManager.h -------------------------------------*- 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 a SMT generic API, which will be the base class for
10// every SMT solver specific class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H
15#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H
16
21#include <optional>
22
23typedef llvm::ImmutableSet<
24 std::pair<clang::ento::SymbolRef, const llvm::SMTExpr *>>
27
28namespace clang {
29namespace ento {
30
32 mutable llvm::SMTSolverRef Solver = llvm::CreateZ3Solver();
33
34public:
37 : SimpleConstraintManager(EE, SB) {}
38 virtual ~SMTConstraintManager() = default;
39
40 //===------------------------------------------------------------------===//
41 // Implementation for interface from SimpleConstraintManager.
42 //===------------------------------------------------------------------===//
43
45 bool Assumption) override {
47
48 QualType RetTy;
49 bool hasComparison;
50
51 llvm::SMTExprRef Exp =
52 SMTConv::getExpr(Solver, Ctx, Sym, &RetTy, &hasComparison);
53
54 // Create zero comparison for implicit boolean cast, with reversed
55 // assumption
56 if (!hasComparison && !RetTy->isBooleanType())
57 return assumeExpr(
58 State, Sym,
59 SMTConv::getZeroExpr(Solver, Ctx, Exp, RetTy, !Assumption));
60
61 return assumeExpr(State, Sym, Assumption ? Exp : Solver->mkNot(Exp));
62 }
63
65 const llvm::APSInt &From,
66 const llvm::APSInt &To,
67 bool InRange) override {
69 return assumeExpr(
70 State, Sym, SMTConv::getRangeExpr(Solver, Ctx, Sym, From, To, InRange));
71 }
72
74 bool Assumption) override {
75 // Skip anything that is unsupported
76 return State;
77 }
78
79 //===------------------------------------------------------------------===//
80 // Implementation for interface from ConstraintManager.
81 //===------------------------------------------------------------------===//
82
85
86 QualType RetTy;
87 // The expression may be casted, so we cannot call getZ3DataExpr() directly
88 llvm::SMTExprRef VarExp = SMTConv::getExpr(Solver, Ctx, Sym, &RetTy);
89 llvm::SMTExprRef Exp =
90 SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/true);
91
92 // Negate the constraint
93 llvm::SMTExprRef NotExp =
94 SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/false);
95
96 ConditionTruthVal isSat = checkModel(State, Sym, Exp);
97 ConditionTruthVal isNotSat = checkModel(State, Sym, NotExp);
98
99 // Zero is the only possible solution
100 if (isSat.isConstrainedTrue() && isNotSat.isConstrainedFalse())
101 return true;
102
103 // Zero is not a solution
104 if (isSat.isConstrainedFalse() && isNotSat.isConstrainedTrue())
105 return false;
106
107 // Zero may be a solution
108 return ConditionTruthVal();
109 }
110
111 const llvm::APSInt *getSymVal(ProgramStateRef State,
112 SymbolRef Sym) const override {
114 ASTContext &Ctx = BVF.getContext();
115
116 if (const SymbolData *SD = dyn_cast<SymbolData>(Sym)) {
117 QualType Ty = Sym->getType();
118 assert(!Ty->isRealFloatingType());
119 llvm::APSInt Value(Ctx.getTypeSize(Ty),
121
122 // TODO: this should call checkModel so we can use the cache, however,
123 // this method tries to get the interpretation (the actual value) from
124 // the solver, which is currently not cached.
125
126 llvm::SMTExprRef Exp = SMTConv::fromData(Solver, Ctx, SD);
127
128 Solver->reset();
129 addStateConstraints(State);
130
131 // Constraints are unsatisfiable
132 std::optional<bool> isSat = Solver->check();
133 if (!isSat || !*isSat)
134 return nullptr;
135
136 // Model does not assign interpretation
137 if (!Solver->getInterpretation(Exp, Value))
138 return nullptr;
139
140 // A value has been obtained, check if it is the only value
141 llvm::SMTExprRef NotExp = SMTConv::fromBinOp(
142 Solver, Exp, BO_NE,
143 Ty->isBooleanType() ? Solver->mkBoolean(Value.getBoolValue())
144 : Solver->mkBitvector(Value, Value.getBitWidth()),
145 /*isSigned=*/false);
146
147 Solver->addConstraint(NotExp);
148
149 std::optional<bool> isNotSat = Solver->check();
150 if (!isNotSat || *isNotSat)
151 return nullptr;
152
153 // This is the only solution, store it
154 return &BVF.getValue(Value);
155 }
156
157 if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) {
158 SymbolRef CastSym = SC->getOperand();
159 QualType CastTy = SC->getType();
160 // Skip the void type
161 if (CastTy->isVoidType())
162 return nullptr;
163
164 const llvm::APSInt *Value;
165 if (!(Value = getSymVal(State, CastSym)))
166 return nullptr;
167 return &BVF.Convert(SC->getType(), *Value);
168 }
169
170 if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
171 const llvm::APSInt *LHS, *RHS;
172 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE)) {
173 LHS = getSymVal(State, SIE->getLHS());
174 RHS = &SIE->getRHS();
175 } else if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE)) {
176 LHS = &ISE->getLHS();
177 RHS = getSymVal(State, ISE->getRHS());
178 } else if (const SymSymExpr *SSM = dyn_cast<SymSymExpr>(BSE)) {
179 // Early termination to avoid expensive call
180 LHS = getSymVal(State, SSM->getLHS());
181 RHS = LHS ? getSymVal(State, SSM->getRHS()) : nullptr;
182 } else {
183 llvm_unreachable("Unsupported binary expression to get symbol value!");
184 }
185
186 if (!LHS || !RHS)
187 return nullptr;
188
189 llvm::APSInt ConvertedLHS, ConvertedRHS;
190 QualType LTy, RTy;
191 std::tie(ConvertedLHS, LTy) = SMTConv::fixAPSInt(Ctx, *LHS);
192 std::tie(ConvertedRHS, RTy) = SMTConv::fixAPSInt(Ctx, *RHS);
193 SMTConv::doIntTypeConversion<llvm::APSInt, &SMTConv::castAPSInt>(
194 Solver, Ctx, ConvertedLHS, LTy, ConvertedRHS, RTy);
195 return BVF.evalAPSInt(BSE->getOpcode(), ConvertedLHS, ConvertedRHS);
196 }
197
198 llvm_unreachable("Unsupported expression to get symbol value!");
199 }
200
202 SymbolReaper &SymReaper) override {
203 auto CZ = State->get<ConstraintSMT>();
204 auto &CZFactory = State->get_context<ConstraintSMT>();
205
206 for (const auto &Entry : CZ) {
207 if (SymReaper.isDead(Entry.first))
208 CZ = CZFactory.remove(CZ, Entry);
209 }
210
211 return State->set<ConstraintSMT>(CZ);
212 }
213
214 void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
215 unsigned int Space = 0, bool IsDot = false) const override {
216 ConstraintSMTType Constraints = State->get<ConstraintSMT>();
217
218 Indent(Out, Space, IsDot) << "\"constraints\": ";
219 if (Constraints.isEmpty()) {
220 Out << "null," << NL;
221 return;
222 }
223
224 ++Space;
225 Out << '[' << NL;
226 for (ConstraintSMTType::iterator I = Constraints.begin();
227 I != Constraints.end(); ++I) {
228 Indent(Out, Space, IsDot)
229 << "{ \"symbol\": \"" << I->first << "\", \"range\": \"";
230 I->second->print(Out);
231 Out << "\" }";
232
233 if (std::next(I) != Constraints.end())
234 Out << ',';
235 Out << NL;
236 }
237
238 --Space;
239 Indent(Out, Space, IsDot) << "],";
240 }
241
243 ProgramStateRef S2) const override {
244 return S1->get<ConstraintSMT>() == S2->get<ConstraintSMT>();
245 }
246
247 bool canReasonAbout(SVal X) const override {
249
250 std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
251 if (!SymVal)
252 return true;
253
254 const SymExpr *Sym = SymVal->getSymbol();
255 QualType Ty = Sym->getType();
256
257 // Complex types are not modeled
258 if (Ty->isComplexType() || Ty->isComplexIntegerType())
259 return false;
260
261 // Non-IEEE 754 floating-point types are not modeled
262 if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
263 (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
264 &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())))
265 return false;
266
267 if (Ty->isRealFloatingType())
268 return Solver->isFPSupported();
269
270 if (isa<SymbolData>(Sym))
271 return true;
272
274
275 if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
276 return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));
277
278 if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
279 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE))
280 return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));
281
282 if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE))
283 return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));
284
285 if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(BSE))
286 return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
287 canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
288 }
289
290 llvm_unreachable("Unsupported expression to reason about!");
291 }
292
293 /// Dumps SMT formula
294 LLVM_DUMP_METHOD void dump() const { Solver->dump(); }
295
296protected:
297 // Check whether a new model is satisfiable, and update the program state.
299 const llvm::SMTExprRef &Exp) {
300 // Check the model, avoid simplifying AST to save time
301 if (checkModel(State, Sym, Exp).isConstrainedTrue())
302 return State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
303
304 return nullptr;
305 }
306
307 /// Given a program state, construct the logical conjunction and add it to
308 /// the solver
309 virtual void addStateConstraints(ProgramStateRef State) const {
310 // TODO: Don't add all the constraints, only the relevant ones
311 auto CZ = State->get<ConstraintSMT>();
312 auto I = CZ.begin(), IE = CZ.end();
313
314 // Construct the logical AND of all the constraints
315 if (I != IE) {
316 std::vector<llvm::SMTExprRef> ASTs;
317
318 llvm::SMTExprRef Constraint = I++->second;
319 while (I != IE) {
320 Constraint = Solver->mkAnd(Constraint, I++->second);
321 }
322
323 Solver->addConstraint(Constraint);
324 }
325 }
326
327 // Generate and check a Z3 model, using the given constraint.
329 const llvm::SMTExprRef &Exp) const {
330 ProgramStateRef NewState =
331 State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
332
333 llvm::FoldingSetNodeID ID;
334 NewState->get<ConstraintSMT>().Profile(ID);
335
336 unsigned hash = ID.ComputeHash();
337 auto I = Cached.find(hash);
338 if (I != Cached.end())
339 return I->second;
340
341 Solver->reset();
342 addStateConstraints(NewState);
343
344 std::optional<bool> res = Solver->check();
345 if (!res)
346 Cached[hash] = ConditionTruthVal();
347 else
348 Cached[hash] = ConditionTruthVal(*res);
349
350 return Cached[hash];
351 }
352
353 // Cache the result of an SMT query (true, false, unknown). The key is the
354 // hash of the constraints in a state
355 mutable llvm::DenseMap<unsigned, ConditionTruthVal> Cached;
356}; // end class SMTConstraintManager
357
358} // namespace ento
359} // namespace clang
360
361#endif
static char ID
Definition: Arena.cpp:183
#define X(type, name)
Definition: Value.h:143
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
llvm::ImmutableSet< std::pair< clang::ento::SymbolRef, const llvm::SMTExpr * > > ConstraintSMTType
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2350
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
A (possibly-)qualified type.
Definition: Type.h:940
Exposes information about the current target.
Definition: TargetInfo.h:218
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
bool isVoidType() const
Definition: Type.h:7910
bool isBooleanType() const
Definition: Type.h:8038
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2156
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:667
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7879
bool isComplexIntegerType() const
Definition: Type.cpp:673
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
const llvm::APSInt & Convert(const llvm::APSInt &To, const llvm::APSInt &From)
Convert - Create a new persistent APSInt with the same value as 'From' but with the bitwidth and sign...
const llvm::APSInt * evalAPSInt(BinaryOperator::Opcode Op, const llvm::APSInt &V1, const llvm::APSInt &V2)
Template implementation for all binary symbolic expressions.
Represents a symbolic expression involving a binary operator.
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to 'false'.
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
SMTConstraintManager(clang::ento::ExprEngine *EE, clang::ento::SValBuilder &SB)
virtual void addStateConstraints(ProgramStateRef State) const
Given a program state, construct the logical conjunction and add it to the solver.
bool canReasonAbout(SVal X) const override
canReasonAbout - Not all ConstraintManagers can accurately reason about all SVal values.
ProgramStateRef assumeSymInclusiveRange(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange) override
Given a symbolic expression within the range [From, To], assume that it is true/false and generate th...
LLVM_DUMP_METHOD void dump() const
Dumps SMT formula.
ConditionTruthVal checkModel(ProgramStateRef State, SymbolRef Sym, const llvm::SMTExprRef &Exp) const
const llvm::APSInt * getSymVal(ProgramStateRef State, SymbolRef Sym) const override
If a symbol is perfectly constrained to a constant, attempt to return the concrete value.
ProgramStateRef removeDeadBindings(ProgramStateRef State, SymbolReaper &SymReaper) override
Scan all symbols referenced by the constraints.
ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override
Returns whether or not a symbol is known to be null ("true"), known to be non-null ("false"),...
ProgramStateRef assumeSym(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that can be reasoned about, assume that it is true/false and generate the...
llvm::DenseMap< unsigned, ConditionTruthVal > Cached
virtual ~SMTConstraintManager()=default
virtual ProgramStateRef assumeExpr(ProgramStateRef State, SymbolRef Sym, const llvm::SMTExprRef &Exp)
void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const override
ProgramStateRef assumeSymUnsupported(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that cannot be reasoned about, assume that it is zero/nonzero and add it ...
bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const override
static llvm::SMTExprRef getZeroExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const llvm::SMTExprRef &Exp, QualType Ty, bool Assumption)
Definition: SMTConv.h:501
static llvm::SMTExprRef getRangeExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange)
Definition: SMTConv.h:532
static llvm::SMTExprRef getExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, QualType *RetTy=nullptr, bool *hasComparison=nullptr)
Definition: SMTConv.h:489
static llvm::SMTExprRef fromData(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const SymbolData *Sym)
Construct an SMTSolverRef from a SymbolData.
Definition: SMTConv.h:323
static llvm::SMTExprRef fromBinOp(llvm::SMTSolverRef &Solver, const llvm::SMTExprRef &LHS, const BinaryOperator::Opcode Op, const llvm::SMTExprRef &RHS, bool isSigned)
Construct an SMTSolverRef from a binary operator.
Definition: SMTConv.h:90
static std::pair< llvm::APSInt, QualType > fixAPSInt(ASTContext &Ctx, const llvm::APSInt &Int)
Definition: SMTConv.h:578
DefinedSVal makeSymbolVal(SymbolRef Sym)
Make an SVal that represents the given symbol.
Definition: SValBuilder.h:400
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
BasicValueFactory & getBasicVals() const
Symbolic value.
Definition: SymExpr.h:30
virtual QualType getType() const =0
Represents a cast expression.
A symbol representing data which can be stored in a memory location (region).
Definition: SymExpr.h:119
A class responsible for cleaning up unused symbols.
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
Represents symbolic expression that isn't a location.
Definition: SVals.h:276
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.