clang  12.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 
18 #include "clang/Basic/TargetInfo.h"
21 
22 typedef llvm::ImmutableSet<
23  std::pair<clang::ento::SymbolRef, const llvm::SMTExpr *>>
26 
27 namespace clang {
28 namespace ento {
29 
31  mutable llvm::SMTSolverRef Solver = llvm::CreateZ3Solver();
32 
33 public:
36  : SimpleConstraintManager(EE, SB) {}
37  virtual ~SMTConstraintManager() = default;
38 
39  //===------------------------------------------------------------------===//
40  // Implementation for interface from SimpleConstraintManager.
41  //===------------------------------------------------------------------===//
42 
44  bool Assumption) override {
46 
47  QualType RetTy;
48  bool hasComparison;
49 
50  llvm::SMTExprRef Exp =
51  SMTConv::getExpr(Solver, Ctx, Sym, &RetTy, &hasComparison);
52 
53  // Create zero comparison for implicit boolean cast, with reversed
54  // assumption
55  if (!hasComparison && !RetTy->isBooleanType())
56  return assumeExpr(
57  State, Sym,
58  SMTConv::getZeroExpr(Solver, Ctx, Exp, RetTy, !Assumption));
59 
60  return assumeExpr(State, Sym, Assumption ? Exp : Solver->mkNot(Exp));
61  }
62 
64  const llvm::APSInt &From,
65  const llvm::APSInt &To,
66  bool InRange) override {
68  return assumeExpr(
69  State, Sym, SMTConv::getRangeExpr(Solver, Ctx, Sym, From, To, InRange));
70  }
71 
73  bool Assumption) override {
74  // Skip anything that is unsupported
75  return State;
76  }
77 
78  //===------------------------------------------------------------------===//
79  // Implementation for interface from ConstraintManager.
80  //===------------------------------------------------------------------===//
81 
84 
85  QualType RetTy;
86  // The expression may be casted, so we cannot call getZ3DataExpr() directly
87  llvm::SMTExprRef VarExp = SMTConv::getExpr(Solver, Ctx, Sym, &RetTy);
88  llvm::SMTExprRef Exp =
89  SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/true);
90 
91  // Negate the constraint
92  llvm::SMTExprRef NotExp =
93  SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/false);
94 
95  ConditionTruthVal isSat = checkModel(State, Sym, Exp);
96  ConditionTruthVal isNotSat = checkModel(State, Sym, NotExp);
97 
98  // Zero is the only possible solution
99  if (isSat.isConstrainedTrue() && isNotSat.isConstrainedFalse())
100  return true;
101 
102  // Zero is not a solution
103  if (isSat.isConstrainedFalse() && isNotSat.isConstrainedTrue())
104  return false;
105 
106  // Zero may be a solution
107  return ConditionTruthVal();
108  }
109 
111  SymbolRef Sym) const override {
113  ASTContext &Ctx = BVF.getContext();
114 
115  if (const SymbolData *SD = dyn_cast<SymbolData>(Sym)) {
116  QualType Ty = Sym->getType();
117  assert(!Ty->isRealFloatingType());
120 
121  // TODO: this should call checkModel so we can use the cache, however,
122  // this method tries to get the interpretation (the actual value) from
123  // the solver, which is currently not cached.
124 
125  llvm::SMTExprRef Exp =
126  SMTConv::fromData(Solver, SD->getSymbolID(), Ty, Ctx.getTypeSize(Ty));
127 
128  Solver->reset();
129  addStateConstraints(State);
130 
131  // Constraints are unsatisfiable
132  Optional<bool> isSat = Solver->check();
133  if (!isSat.hasValue() || !isSat.getValue())
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  Optional<bool> isNotSat = Solver->check();
150  if (!isSat.hasValue() || isNotSat.getValue())
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 (auto I = CZ.begin(), E = CZ.end(); I != E; ++I) {
207  if (SymReaper.isDead(I->first))
208  CZ = CZFactory.remove(CZ, *I);
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 
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 
273  SValBuilder &SVB = getSValBuilder();
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 
296 protected:
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
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  Optional<bool> res = Solver->check();
345  if (!res.hasValue())
346  Cached[hash] = ConditionTruthVal();
347  else
348  Cached[hash] = ConditionTruthVal(res.getValue());
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
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to &#39;false&#39;.
A (possibly-)qualified type.
Definition: Type.h:655
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2114
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:647
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::ImmutableSet< std::pair< clang::ento::SymbolRef, const llvm::SMTExpr * > > ConstraintSMTType
Symbolic value.
Definition: SymExpr.h:29
static std::pair< llvm::APSInt, QualType > fixAPSInt(ASTContext &Ctx, const llvm::APSInt &Int)
Definition: SMTConv.h:550
SVal makeSymbolVal(SymbolRef Sym)
Make an SVal that represents the given symbol.
Definition: SValBuilder.h:372
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:174
LineState State
SMTConstraintManager(clang::ento::ExprEngine *EE, clang::ento::SValBuilder &SB)
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6902
const llvm::APSInt & Convert(const llvm::APSInt &To, const llvm::APSInt &From)
Convert - Create a new persistent APSInt with the same value as &#39;From&#39; but with the bitwidth and sign...
void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\, unsigned int Space=0, bool IsDot=false) const override
virtual QualType getType() const =0
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to &#39;true&#39;.
virtual ProgramStateRef assumeExpr(ProgramStateRef State, SymbolRef Sym, const llvm::SMTExprRef &Exp)
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:603
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:646
Exposes information about the current target.
Definition: TargetInfo.h:179
BasicValueFactory & getBasicVals() const
ProgramStateRef removeDeadBindings(ProgramStateRef State, SymbolReaper &SymReaper) override
Scan all symbols referenced by the constraints.
static llvm::SMTExprRef getZeroExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const llvm::SMTExprRef &Exp, QualType Ty, bool Assumption)
Definition: SMTConv.h:473
Represents a cast expression.
Template implementation for all binary symbolic expressions.
virtual ~SMTConstraintManager()=default
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:111
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy...
static llvm::SMTExprRef getExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, QualType *RetTy=nullptr, bool *hasComparison=nullptr)
Definition: SMTConv.h:461
llvm::APSInt APSInt
bool InRange(InterpState &S, CodePtr OpPC)
Definition: Interp.h:264
bool canReasonAbout(SVal X) const override
canReasonAbout - Not all ConstraintManagers can accurately reason about all SVal values.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:75
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2027
A class responsible for cleaning up unused symbols.
const llvm::APSInt * evalAPSInt(BinaryOperator::Opcode Op, const llvm::APSInt &V1, const llvm::APSInt &V2)
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 ...
Dataflow Directional Tag Classes.
Represents a symbolic expression involving a binary operator.
LLVM_DUMP_METHOD void dump() const
Dumps SMT formula.
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
bool isBooleanType() const
Definition: Type.h:7045
Represents symbolic expression that isn&#39;t a location.
Definition: SVals.h:349
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...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2060
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...
static llvm::SMTExprRef fromData(llvm::SMTSolverRef &Solver, const SymbolID ID, const QualType &Ty, uint64_t BitWidth)
Construct an SMTSolverRef from a SymbolData.
Definition: SMTConv.h:322
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:15148
llvm::DenseMap< unsigned, ConditionTruthVal > Cached
bool isVoidType() const
Definition: Type.h:6933
virtual void addStateConstraints(ProgramStateRef State) const
Given a program state, construct the logical conjunction and add it to the solver.
Defines the clang::TargetInfo interface.
bool isComplexIntegerType() const
Definition: Type.cpp:609
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition: JsonSupport.h:20
bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const override
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")...
A symbol representing data which can be stored in a memory location (region).
Definition: SymExpr.h:116
static llvm::SMTExprRef getRangeExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange)
Definition: SMTConv.h:504