clang  9.0.0svn
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 
19 
20 typedef llvm::ImmutableSet<
21  std::pair<clang::ento::SymbolRef, const llvm::SMTExpr *>>
24 
25 namespace clang {
26 namespace ento {
27 
29  mutable llvm::SMTSolverRef Solver = llvm::CreateZ3Solver();
30 
31 public:
33  : SimpleConstraintManager(SE, SB) {}
34  virtual ~SMTConstraintManager() = default;
35 
36  //===------------------------------------------------------------------===//
37  // Implementation for interface from SimpleConstraintManager.
38  //===------------------------------------------------------------------===//
39 
41  bool Assumption) override {
43 
44  QualType RetTy;
45  bool hasComparison;
46 
47  llvm::SMTExprRef Exp =
48  SMTConv::getExpr(Solver, Ctx, Sym, &RetTy, &hasComparison);
49 
50  // Create zero comparison for implicit boolean cast, with reversed
51  // assumption
52  if (!hasComparison && !RetTy->isBooleanType())
53  return assumeExpr(
54  State, Sym,
55  SMTConv::getZeroExpr(Solver, Ctx, Exp, RetTy, !Assumption));
56 
57  return assumeExpr(State, Sym, Assumption ? Exp : Solver->mkNot(Exp));
58  }
59 
61  const llvm::APSInt &From,
62  const llvm::APSInt &To,
63  bool InRange) override {
65  return assumeExpr(
66  State, Sym, SMTConv::getRangeExpr(Solver, Ctx, Sym, From, To, InRange));
67  }
68 
70  bool Assumption) override {
71  // Skip anything that is unsupported
72  return State;
73  }
74 
75  //===------------------------------------------------------------------===//
76  // Implementation for interface from ConstraintManager.
77  //===------------------------------------------------------------------===//
78 
81 
82  QualType RetTy;
83  // The expression may be casted, so we cannot call getZ3DataExpr() directly
84  llvm::SMTExprRef VarExp = SMTConv::getExpr(Solver, Ctx, Sym, &RetTy);
85  llvm::SMTExprRef Exp =
86  SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/true);
87 
88  // Negate the constraint
89  llvm::SMTExprRef NotExp =
90  SMTConv::getZeroExpr(Solver, Ctx, VarExp, RetTy, /*Assumption=*/false);
91 
92  ConditionTruthVal isSat = checkModel(State, Sym, Exp);
93  ConditionTruthVal isNotSat = checkModel(State, Sym, NotExp);
94 
95  // Zero is the only possible solution
96  if (isSat.isConstrainedTrue() && isNotSat.isConstrainedFalse())
97  return true;
98 
99  // Zero is not a solution
100  if (isSat.isConstrainedFalse() && isNotSat.isConstrainedTrue())
101  return false;
102 
103  // Zero may be a solution
104  return ConditionTruthVal();
105  }
106 
107  const llvm::APSInt *getSymVal(ProgramStateRef State,
108  SymbolRef Sym) const override {
110  ASTContext &Ctx = BVF.getContext();
111 
112  if (const SymbolData *SD = dyn_cast<SymbolData>(Sym)) {
113  QualType Ty = Sym->getType();
114  assert(!Ty->isRealFloatingType());
115  llvm::APSInt Value(Ctx.getTypeSize(Ty),
117 
118  // TODO: this should call checkModel so we can use the cache, however,
119  // this method tries to get the interpretation (the actual value) from
120  // the solver, which is currently not cached.
121 
122  llvm::SMTExprRef Exp =
123  SMTConv::fromData(Solver, SD->getSymbolID(), Ty, Ctx.getTypeSize(Ty));
124 
125  Solver->reset();
126  addStateConstraints(State);
127 
128  // Constraints are unsatisfiable
129  Optional<bool> isSat = Solver->check();
130  if (!isSat.hasValue() || !isSat.getValue())
131  return nullptr;
132 
133  // Model does not assign interpretation
134  if (!Solver->getInterpretation(Exp, Value))
135  return nullptr;
136 
137  // A value has been obtained, check if it is the only value
138  llvm::SMTExprRef NotExp = SMTConv::fromBinOp(
139  Solver, Exp, BO_NE,
140  Ty->isBooleanType() ? Solver->mkBoolean(Value.getBoolValue())
141  : Solver->mkBitvector(Value, Value.getBitWidth()),
142  /*isSigned=*/false);
143 
144  Solver->addConstraint(NotExp);
145 
146  Optional<bool> isNotSat = Solver->check();
147  if (!isSat.hasValue() || isNotSat.getValue())
148  return nullptr;
149 
150  // This is the only solution, store it
151  return &BVF.getValue(Value);
152  }
153 
154  if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) {
155  SymbolRef CastSym = SC->getOperand();
156  QualType CastTy = SC->getType();
157  // Skip the void type
158  if (CastTy->isVoidType())
159  return nullptr;
160 
161  const llvm::APSInt *Value;
162  if (!(Value = getSymVal(State, CastSym)))
163  return nullptr;
164  return &BVF.Convert(SC->getType(), *Value);
165  }
166 
167  if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
168  const llvm::APSInt *LHS, *RHS;
169  if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE)) {
170  LHS = getSymVal(State, SIE->getLHS());
171  RHS = &SIE->getRHS();
172  } else if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE)) {
173  LHS = &ISE->getLHS();
174  RHS = getSymVal(State, ISE->getRHS());
175  } else if (const SymSymExpr *SSM = dyn_cast<SymSymExpr>(BSE)) {
176  // Early termination to avoid expensive call
177  LHS = getSymVal(State, SSM->getLHS());
178  RHS = LHS ? getSymVal(State, SSM->getRHS()) : nullptr;
179  } else {
180  llvm_unreachable("Unsupported binary expression to get symbol value!");
181  }
182 
183  if (!LHS || !RHS)
184  return nullptr;
185 
186  llvm::APSInt ConvertedLHS, ConvertedRHS;
187  QualType LTy, RTy;
188  std::tie(ConvertedLHS, LTy) = SMTConv::fixAPSInt(Ctx, *LHS);
189  std::tie(ConvertedRHS, RTy) = SMTConv::fixAPSInt(Ctx, *RHS);
190  SMTConv::doIntTypeConversion<llvm::APSInt, &SMTConv::castAPSInt>(
191  Solver, Ctx, ConvertedLHS, LTy, ConvertedRHS, RTy);
192  return BVF.evalAPSInt(BSE->getOpcode(), ConvertedLHS, ConvertedRHS);
193  }
194 
195  llvm_unreachable("Unsupported expression to get symbol value!");
196  }
197 
199  SymbolReaper &SymReaper) override {
200  auto CZ = State->get<ConstraintSMT>();
201  auto &CZFactory = State->get_context<ConstraintSMT>();
202 
203  for (auto I = CZ.begin(), E = CZ.end(); I != E; ++I) {
204  if (SymReaper.isDead(I->first))
205  CZ = CZFactory.remove(CZ, *I);
206  }
207 
208  return State->set<ConstraintSMT>(CZ);
209  }
210 
211  void print(ProgramStateRef St, raw_ostream &OS, const char *nl,
212  const char *sep) override {
213 
214  auto CZ = St->get<ConstraintSMT>();
215 
216  OS << nl << sep << "Constraints:";
217  for (auto I = CZ.begin(), E = CZ.end(); I != E; ++I) {
218  OS << nl << ' ' << I->first << " : ";
219  I->second->print(OS);
220  }
221  OS << nl;
222  }
223 
225  ProgramStateRef S2) const override {
226  return S1->get<ConstraintSMT>() == S2->get<ConstraintSMT>();
227  }
228 
229  bool canReasonAbout(SVal X) const override {
231 
233  if (!SymVal)
234  return true;
235 
236  const SymExpr *Sym = SymVal->getSymbol();
237  QualType Ty = Sym->getType();
238 
239  // Complex types are not modeled
240  if (Ty->isComplexType() || Ty->isComplexIntegerType())
241  return false;
242 
243  // Non-IEEE 754 floating-point types are not modeled
244  if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
245  (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
246  &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())))
247  return false;
248 
249  if (Ty->isRealFloatingType())
250  return Solver->isFPSupported();
251 
252  if (isa<SymbolData>(Sym))
253  return true;
254 
255  SValBuilder &SVB = getSValBuilder();
256 
257  if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
258  return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));
259 
260  if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
261  if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE))
262  return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));
263 
264  if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE))
265  return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));
266 
267  if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(BSE))
268  return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
269  canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
270  }
271 
272  llvm_unreachable("Unsupported expression to reason about!");
273  }
274 
275  /// Dumps SMT formula
276  LLVM_DUMP_METHOD void dump() const { Solver->dump(); }
277 
278 protected:
279  // Check whether a new model is satisfiable, and update the program state.
281  const llvm::SMTExprRef &Exp) {
282  // Check the model, avoid simplifying AST to save time
283  if (checkModel(State, Sym, Exp).isConstrainedTrue())
284  return State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
285 
286  return nullptr;
287  }
288 
289  /// Given a program state, construct the logical conjunction and add it to
290  /// the solver
292  // TODO: Don't add all the constraints, only the relevant ones
293  auto CZ = State->get<ConstraintSMT>();
294  auto I = CZ.begin(), IE = CZ.end();
295 
296  // Construct the logical AND of all the constraints
297  if (I != IE) {
298  std::vector<llvm::SMTExprRef> ASTs;
299 
300  llvm::SMTExprRef Constraint = I++->second;
301  while (I != IE) {
302  Constraint = Solver->mkAnd(Constraint, I++->second);
303  }
304 
305  Solver->addConstraint(Constraint);
306  }
307  }
308 
309  // Generate and check a Z3 model, using the given constraint.
311  const llvm::SMTExprRef &Exp) const {
312  ProgramStateRef NewState =
313  State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
314 
315  llvm::FoldingSetNodeID ID;
316  NewState->get<ConstraintSMT>().Profile(ID);
317 
318  unsigned hash = ID.ComputeHash();
319  auto I = Cached.find(hash);
320  if (I != Cached.end())
321  return I->second;
322 
323  Solver->reset();
324  addStateConstraints(NewState);
325 
326  Optional<bool> res = Solver->check();
327  if (!res.hasValue())
328  Cached[hash] = ConditionTruthVal();
329  else
330  Cached[hash] = ConditionTruthVal(res.getValue());
331 
332  return Cached[hash];
333  }
334 
335  // Cache the result of an SMT query (true, false, unknown). The key is the
336  // hash of the constraints in a state
337  mutable llvm::DenseMap<unsigned, ConditionTruthVal> Cached;
338 }; // end class SMTConstraintManager
339 
340 } // namespace ento
341 } // namespace clang
342 
343 #endif
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to &#39;false&#39;.
A (possibly-)qualified type.
Definition: Type.h:639
SMTConstraintManager(clang::ento::SubEngine *SE, clang::ento::SValBuilder &SB)
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1959
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
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:154
LineState State
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:6527
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...
Represents a symbolic expression like &#39;x&#39; + 3.
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:481
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:588
Exposes information about the current target.
Definition: TargetInfo.h:161
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.
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
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:1882
Represents a symbolic expression like 3 - &#39;x&#39;.
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:6677
Represents symbolic expression that isn&#39;t a location.
Definition: SVals.h:346
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
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:2072
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:14051
llvm::DenseMap< unsigned, ConditionTruthVal > Cached
bool isVoidType() const
Definition: Type.h:6560
virtual void addStateConstraints(ProgramStateRef State) const
Given a program state, construct the logical conjunction and add it to the solver.
bool isComplexIntegerType() const
Definition: Type.cpp:487
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")...
void print(ProgramStateRef St, raw_ostream &OS, const char *nl, const char *sep) override
Represents a symbolic expression like &#39;x&#39; + &#39;y&#39;.
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