1 /********************* */
2 /*! \file smt_engine.cpp
4 ** Original author: Morgan Deters
5 ** Major contributors: Clark Barrett
6 ** Minor contributors (to current version): Christopher L. Conway, Tianyi Liang, Martin Brain <>, Kshitij Bansal, Liana Hadarean, Dejan Jovanovic, Tim King, Andrew Reynolds
7 ** This file is part of the CVC4 project.
8 ** Copyright (c) 2009-2014 New York University and The University of Iowa
9 ** See the file COPYING in the top-level source directory for licensing
10 ** information.\endverbatim
12 ** \brief The main entry point into the CVC4 library's SMT interface
14 ** The main entry point into the CVC4 library's SMT interface.
25 #include <ext/hash_map>
27 #include "context/cdlist.h"
28 #include "context/cdhashset.h"
29 #include "context/context.h"
30 #include "decision/decision_engine.h"
31 #include "decision/decision_mode.h"
32 #include "decision/options.h"
33 #include "expr/command.h"
34 #include "expr/expr.h"
35 #include "expr/kind.h"
36 #include "expr/metakind.h"
37 #include "expr/node_builder.h"
38 #include "expr/node.h"
39 #include "expr/node_self_iterator.h"
40 #include "prop/prop_engine.h"
41 #include "proof/theory_proof.h"
42 #include "smt/modal_exception.h"
43 #include "smt/smt_engine.h"
44 #include "smt/smt_engine_scope.h"
45 #include "smt/model_postprocessor.h"
46 #include "smt/logic_request.h"
47 #include "theory/theory_engine.h"
48 #include "theory/bv/theory_bv_rewriter.h"
49 #include "proof/proof_manager.h"
50 #include "main/options.h"
51 #include "util/unsat_core.h"
52 #include "util/proof.h"
53 #include "proof/proof.h"
54 #include "proof/proof_manager.h"
55 #include "util/boolean_simplification.h"
56 #include "util/node_visitor.h"
57 #include "util/configuration.h"
58 #include "util/exception.h"
59 #include "util/nary_builder.h"
60 #include "smt/command_list.h"
61 #include "smt/boolean_terms.h"
62 #include "smt/options.h"
63 #include "options/option_exception.h"
64 #include "util/output.h"
65 #include "util/hash.h"
66 #include "theory/substitutions.h"
67 #include "theory/uf/options.h"
68 #include "theory/arith/options.h"
69 #include "theory/strings/options.h"
70 #include "theory/bv/options.h"
71 #include "theory/theory_traits.h"
72 #include "theory/logic_info.h"
73 #include "theory/options.h"
74 #include "theory/booleans/circuit_propagator.h"
75 #include "theory/booleans/boolean_term_conversion_mode.h"
76 #include "theory/booleans/options.h"
77 #include "util/ite_removal.h"
78 #include "theory/theory_model.h"
79 #include "printer/printer.h"
80 #include "prop/options.h"
81 #include "theory/arrays/options.h"
82 #include "util/sort_inference.h"
83 #include "theory/quantifiers/quant_conflict_find.h"
84 #include "theory/quantifiers/macros.h"
85 #include "theory/quantifiers/first_order_reasoning.h"
86 #include "theory/quantifiers/quantifiers_rewriter.h"
87 #include "theory/quantifiers/options.h"
88 #include "theory/datatypes/options.h"
89 #include "theory/strings/theory_strings_preprocess.h"
90 #include "printer/options.h"
92 #include "theory/arith/pseudoboolean_proc.h"
93 #include "theory/bv/bvintropow2.h"
97 using namespace CVC4::smt
;
98 using namespace CVC4::prop
;
99 using namespace CVC4::context
;
100 using namespace CVC4::theory
;
106 /** Useful for counting the number of recursive calls. */
111 ScopeCounter(unsigned& d
) : d_depth(d
) {
120 * Representation of a defined function. We keep these around in
121 * SmtEngine to permit expanding definitions late (and lazily), to
122 * support getValue() over defined functions, to support user output
123 * in terms of defined functions, etc.
125 class DefinedFunction
{
127 vector
<Node
> d_formals
;
131 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
136 Node
getFunction() const { return d_func
; }
137 vector
<Node
> getFormals() const { return d_formals
; }
138 Node
getFormula() const { return d_formula
; }
139 };/* class DefinedFunction */
141 class AssertionPipeline
{
142 vector
<Node
> d_nodes
;
146 size_t size() const { return d_nodes
.size(); }
148 void resize(size_t n
) { d_nodes
.resize(n
); }
149 void clear() { d_nodes
.clear(); }
151 Node
& operator[](size_t i
) { return d_nodes
[i
]; }
152 const Node
& operator[](size_t i
) const { return d_nodes
[i
]; }
153 void push_back(Node n
) { d_nodes
.push_back(n
); }
155 vector
<Node
>& ref() { return d_nodes
; }
156 const vector
<Node
>& ref() const { return d_nodes
; }
158 void replace(size_t i
, Node n
) {
159 PROOF( ProofManager::currentPM()->addDependence(n
, d_nodes
[i
]); );
163 };/* class AssertionPipeline */
165 struct SmtEngineStatistics
{
166 /** time spent in definition-expansion */
167 TimerStat d_definitionExpansionTime
;
168 /** time spent in Boolean term rewriting */
169 TimerStat d_rewriteBooleanTermsTime
;
170 /** time spent in non-clausal simplification */
171 TimerStat d_nonclausalSimplificationTime
;
172 /** time spent in miplib pass */
173 TimerStat d_miplibPassTime
;
174 /** number of assertions removed by miplib pass */
175 IntStat d_numMiplibAssertionsRemoved
;
176 /** number of constant propagations found during nonclausal simp */
177 IntStat d_numConstantProps
;
178 /** time spent in static learning */
179 TimerStat d_staticLearningTime
;
180 /** time spent in simplifying ITEs */
181 TimerStat d_simpITETime
;
182 /** time spent in simplifying ITEs */
183 TimerStat d_unconstrainedSimpTime
;
184 /** time spent removing ITEs */
185 TimerStat d_iteRemovalTime
;
186 /** time spent in theory preprocessing */
187 TimerStat d_theoryPreprocessTime
;
188 /** time spent in theory preprocessing */
189 TimerStat d_rewriteApplyToConstTime
;
190 /** time spent converting to CNF */
191 TimerStat d_cnfConversionTime
;
192 /** Num of assertions before ite removal */
193 IntStat d_numAssertionsPre
;
194 /** Num of assertions after ite removal */
195 IntStat d_numAssertionsPost
;
196 /** time spent in checkModel() */
197 TimerStat d_checkModelTime
;
198 /** time spent in checkProof() */
199 TimerStat d_checkProofTime
;
200 /** time spent in PropEngine::checkSat() */
201 TimerStat d_solveTime
;
202 /** time spent in pushing/popping */
203 TimerStat d_pushPopTime
;
204 /** time spent in processAssertions() */
205 TimerStat d_processAssertionsTime
;
207 /** Has something simplified to false? */
208 IntStat d_simplifiedToFalse
;
210 SmtEngineStatistics() :
211 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
212 d_rewriteBooleanTermsTime("smt::SmtEngine::rewriteBooleanTermsTime"),
213 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
214 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
215 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
216 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
217 d_staticLearningTime("smt::SmtEngine::staticLearningTime"),
218 d_simpITETime("smt::SmtEngine::simpITETime"),
219 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
220 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
221 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
222 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
223 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
224 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
225 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
226 d_checkModelTime("smt::SmtEngine::checkModelTime"),
227 d_checkProofTime("smt::SmtEngine::checkProofTime"),
228 d_solveTime("smt::SmtEngine::solveTime"),
229 d_pushPopTime("smt::SmtEngine::pushPopTime"),
230 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
231 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0)
234 StatisticsRegistry::registerStat(&d_definitionExpansionTime
);
235 StatisticsRegistry::registerStat(&d_rewriteBooleanTermsTime
);
236 StatisticsRegistry::registerStat(&d_nonclausalSimplificationTime
);
237 StatisticsRegistry::registerStat(&d_miplibPassTime
);
238 StatisticsRegistry::registerStat(&d_numMiplibAssertionsRemoved
);
239 StatisticsRegistry::registerStat(&d_numConstantProps
);
240 StatisticsRegistry::registerStat(&d_staticLearningTime
);
241 StatisticsRegistry::registerStat(&d_simpITETime
);
242 StatisticsRegistry::registerStat(&d_unconstrainedSimpTime
);
243 StatisticsRegistry::registerStat(&d_iteRemovalTime
);
244 StatisticsRegistry::registerStat(&d_theoryPreprocessTime
);
245 StatisticsRegistry::registerStat(&d_rewriteApplyToConstTime
);
246 StatisticsRegistry::registerStat(&d_cnfConversionTime
);
247 StatisticsRegistry::registerStat(&d_numAssertionsPre
);
248 StatisticsRegistry::registerStat(&d_numAssertionsPost
);
249 StatisticsRegistry::registerStat(&d_checkModelTime
);
250 StatisticsRegistry::registerStat(&d_checkProofTime
);
251 StatisticsRegistry::registerStat(&d_solveTime
);
252 StatisticsRegistry::registerStat(&d_pushPopTime
);
253 StatisticsRegistry::registerStat(&d_processAssertionsTime
);
254 StatisticsRegistry::registerStat(&d_simplifiedToFalse
);
257 ~SmtEngineStatistics() {
258 StatisticsRegistry::unregisterStat(&d_definitionExpansionTime
);
259 StatisticsRegistry::unregisterStat(&d_rewriteBooleanTermsTime
);
260 StatisticsRegistry::unregisterStat(&d_nonclausalSimplificationTime
);
261 StatisticsRegistry::unregisterStat(&d_miplibPassTime
);
262 StatisticsRegistry::unregisterStat(&d_numMiplibAssertionsRemoved
);
263 StatisticsRegistry::unregisterStat(&d_numConstantProps
);
264 StatisticsRegistry::unregisterStat(&d_staticLearningTime
);
265 StatisticsRegistry::unregisterStat(&d_simpITETime
);
266 StatisticsRegistry::unregisterStat(&d_unconstrainedSimpTime
);
267 StatisticsRegistry::unregisterStat(&d_iteRemovalTime
);
268 StatisticsRegistry::unregisterStat(&d_theoryPreprocessTime
);
269 StatisticsRegistry::unregisterStat(&d_rewriteApplyToConstTime
);
270 StatisticsRegistry::unregisterStat(&d_cnfConversionTime
);
271 StatisticsRegistry::unregisterStat(&d_numAssertionsPre
);
272 StatisticsRegistry::unregisterStat(&d_numAssertionsPost
);
273 StatisticsRegistry::unregisterStat(&d_checkModelTime
);
274 StatisticsRegistry::unregisterStat(&d_checkProofTime
);
275 StatisticsRegistry::unregisterStat(&d_solveTime
);
276 StatisticsRegistry::unregisterStat(&d_pushPopTime
);
277 StatisticsRegistry::unregisterStat(&d_processAssertionsTime
);
278 StatisticsRegistry::unregisterStat(&d_simplifiedToFalse
);
280 };/* struct SmtEngineStatistics */
283 * This is an inelegant solution, but for the present, it will work.
284 * The point of this is to separate the public and private portions of
285 * the SmtEngine class, so that smt_engine.h doesn't
286 * include "expr/node.h", which is a private CVC4 header (and can lead
287 * to linking errors due to the improper inlining of non-visible symbols
290 * The "real" solution (that which is usually implemented) is to move
291 * ALL the implementation to SmtEnginePrivate and maintain a
292 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
293 * one) becomes an "interface shell" which simply acts as a forwarder
296 class SmtEnginePrivate
: public NodeManagerListener
{
299 /** Learned literals */
300 vector
<Node
> d_nonClausalLearnedLiterals
;
302 /** Size of assertions array when preprocessing starts */
303 unsigned d_realAssertionsEnd
;
305 /** The converter for Boolean terms -> BITVECTOR(1). */
306 BooleanTermConverter
* d_booleanTermConverter
;
308 /** A circuit propagator for non-clausal propositional deduction */
309 booleans::CircuitPropagator d_propagator
;
310 bool d_propagatorNeedsFinish
;
311 std::vector
<Node
> d_boolVars
;
313 /** Assertions in the preprocessing pipeline */
314 AssertionPipeline d_assertions
;
316 /** Whether any assertions have been processed */
317 CDO
<bool> d_assertionsProcessed
;
319 /** Index for where to store substitutions */
320 CDO
<unsigned> d_substitutionsIndex
;
326 * A context that never pushes/pops, for use by CD structures (like
327 * SubstitutionMaps) that should be "global".
329 context::Context d_fakeContext
;
332 * A map of AbsractValues to their actual constants. Only used if
333 * options::abstractValues() is on.
335 SubstitutionMap d_abstractValueMap
;
338 * A mapping of all abstract values (actual value |-> abstract) that
339 * we've handed out. This is necessary to ensure that we give the
340 * same AbstractValues for the same real constants. Only used if
341 * options::abstractValues() is on.
343 hash_map
<Node
, Node
, NodeHashFunction
> d_abstractValues
;
345 /** Number of calls of simplify assertions active.
347 unsigned d_simplifyAssertionsDepth
;
351 * Map from skolem variables to index in d_assertions containing
352 * corresponding introduced Boolean ite
354 IteSkolemMap d_iteSkolemMap
;
356 /** Instance of the ITE remover */
357 RemoveITE d_iteRemover
;
361 theory::arith::PseudoBooleanProcessor d_pbsProcessor
;
363 /** The top level substitutions */
364 SubstitutionMap d_topLevelSubstitutions
;
366 static const bool d_doConstantProp
= true;
369 * Runs the nonclausal solver and tries to solve all the assigned
372 * Returns false if the formula simplifies to "false"
374 bool nonClausalSimplify();
377 * Performs static learning on the assertions.
379 void staticLearning();
382 * Remove ITEs from the assertions.
387 * Helper function to fix up assertion list to restore invariants needed after ite removal
389 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, hash_map
<Node
, bool, NodeHashFunction
>& cache
);
392 * Helper function to fix up assertion list to restore invariants needed after ite removal
394 bool checkForBadSkolems(TNode n
, TNode skolem
, hash_map
<Node
, bool, NodeHashFunction
>& cache
);
396 // Lift bit-vectors of size 1 to booleans
399 // Abstract common structure over small domains to UF
400 // return true if changes were made.
401 void bvAbstraction();
403 // Simplify ITE structure
406 // Simplify based on unconstrained values
407 void unconstrainedSimp();
409 // Ensures the assertions asserted after before now
410 // effectively come before d_realAssertionsEnd
411 void compressBeforeRealAssertions(size_t before
);
414 * Any variable in an assertion that is declared as a subtype type
415 * (predicate subtype or integer subrange type) must be constrained
416 * to be in that type.
418 void constrainSubtypes(TNode n
, AssertionPipeline
& assertions
)
421 // trace nodes back to their assertions using CircuitPropagator's BackEdgesMap
422 void traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
);
423 // remove conjuncts in toRemove from conjunction n; return # of removed conjuncts
424 size_t removeFromConjunction(Node
& n
, const std::hash_set
<unsigned long>& toRemove
);
426 // scrub miplib encodings
427 void doMiplibTrick();
430 * Perform non-clausal simplification of a Node. This involves
431 * Theory implementations, but does NOT involve the SAT solver in
434 * Returns false if the formula simplifies to "false"
436 bool simplifyAssertions() throw(TypeCheckingException
, LogicException
);
440 SmtEnginePrivate(SmtEngine
& smt
) :
442 d_nonClausalLearnedLiterals(),
443 d_realAssertionsEnd(0),
444 d_booleanTermConverter(NULL
),
445 d_propagator(d_nonClausalLearnedLiterals
, true, true),
446 d_propagatorNeedsFinish(false),
448 d_assertionsProcessed(smt
.d_userContext
, false),
449 d_substitutionsIndex(smt
.d_userContext
, 0),
451 d_abstractValueMap(&d_fakeContext
),
453 d_simplifyAssertionsDepth(0),
455 d_iteRemover(smt
.d_userContext
),
456 d_pbsProcessor(smt
.d_userContext
),
457 d_topLevelSubstitutions(smt
.d_userContext
)
459 d_smt
.d_nodeManager
->subscribeEvents(this);
460 d_true
= NodeManager::currentNM()->mkConst(true);
463 ~SmtEnginePrivate() {
464 if(d_propagatorNeedsFinish
) {
465 d_propagator
.finish();
466 d_propagatorNeedsFinish
= false;
468 if(d_booleanTermConverter
!= NULL
) {
469 delete d_booleanTermConverter
;
470 d_booleanTermConverter
= NULL
;
472 d_smt
.d_nodeManager
->unsubscribeEvents(this);
475 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) {
476 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
479 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
480 d_smt
.addToModelCommandAndDump(c
, flags
);
484 void nmNotifyNewSortConstructor(TypeNode tn
) {
485 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
486 tn
.getAttribute(expr::SortArityAttr()),
488 d_smt
.addToModelCommandAndDump(c
);
491 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
) {
492 DatatypeDeclarationCommand
c(dtts
);
493 d_smt
.addToModelCommandAndDump(c
);
496 void nmNotifyNewVar(TNode n
, uint32_t flags
) {
497 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
499 n
.getType().toType());
500 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
501 d_smt
.addToModelCommandAndDump(c
, flags
);
503 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
504 d_boolVars
.push_back(n
);
508 void nmNotifyNewSkolem(TNode n
, const std::string
& comment
, uint32_t flags
) {
509 string id
= n
.getAttribute(expr::VarNameAttr());
510 DeclareFunctionCommand
c(id
,
512 n
.getType().toType());
513 if(Dump
.isOn("skolems") && comment
!= "") {
514 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
516 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
517 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
519 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
520 d_boolVars
.push_back(n
);
524 Node
applySubstitutions(TNode node
) const {
525 return Rewriter::rewrite(d_topLevelSubstitutions
.apply(node
));
529 * Process the assertions that have been asserted.
531 void processAssertions();
534 * Process a user pop. Clears out the non-context-dependent stuff in this
535 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
536 * someone does a push-assert-pop without a check-sat.
539 d_assertions
.clear();
540 d_nonClausalLearnedLiterals
.clear();
541 d_realAssertionsEnd
= 0;
542 d_iteSkolemMap
.clear();
546 * Adds a formula to the current context. Action here depends on
547 * the SimplificationMode (in the current Options scope); the
548 * formula might be pushed out to the propositional layer
549 * immediately, or it might be simplified and kept, or it might not
550 * even be simplified.
552 void addFormula(TNode n
)
553 throw(TypeCheckingException
, LogicException
);
556 * Expand definitions in n.
558 Node
expandDefinitions(TNode n
, hash_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
= false)
559 throw(TypeCheckingException
, LogicException
);
562 * Rewrite Boolean terms in a Node.
564 Node
rewriteBooleanTerms(TNode n
);
567 * Simplify node "in" by expanding definitions and applying any
568 * substitutions learned from preprocessing.
570 Node
simplify(TNode in
) {
571 // Substitute out any abstract values in ex.
572 // Expand definitions.
573 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
574 Node n
= expandDefinitions(in
, cache
).toExpr();
575 // Make sure we've done all preprocessing, etc.
576 Assert(d_assertions
.size() == 0);
577 return applySubstitutions(n
).toExpr();
581 * Substitute away all AbstractValues in a node.
583 Node
substituteAbstractValues(TNode n
) {
584 // We need to do this even if options::abstractValues() is off,
585 // since the setting might have changed after we already gave out
586 // some abstract values.
587 return d_abstractValueMap
.apply(n
);
591 * Make a new (or return an existing) abstract value for a node.
592 * Can only use this if options::abstractValues() is on.
594 Node
mkAbstractValue(TNode n
) {
595 Assert(options::abstractValues());
596 Node
& val
= d_abstractValues
[n
];
598 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
599 d_abstractValueMap
.addSubstitution(val
, n
);
604 std::hash_map
<Node
, Node
, NodeHashFunction
> rewriteApplyToConstCache
;
605 Node
rewriteApplyToConst(TNode n
) {
606 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n
<< std::endl
;
608 if(n
.getMetaKind() == kind::metakind::CONSTANT
|| n
.getMetaKind() == kind::metakind::VARIABLE
) {
612 if(rewriteApplyToConstCache
.find(n
) != rewriteApplyToConstCache
.end()) {
613 Trace("rewriteApplyToConst") << "in cache :: " << rewriteApplyToConstCache
[n
] << std::endl
;
614 return rewriteApplyToConstCache
[n
];
616 if(n
.getKind() == kind::APPLY_UF
) {
617 if(n
.getNumChildren() == 1 && n
[0].isConst() && n
[0].getType().isInteger()) {
619 ss
<< n
.getOperator() << "_";
620 if(n
[0].getConst
<Rational
>() < 0) {
621 ss
<< "m" << -n
[0].getConst
<Rational
>();
625 Node newvar
= NodeManager::currentNM()->mkSkolem(ss
.str(), n
.getType(), "rewriteApplyToConst skolem", NodeManager::SKOLEM_EXACT_NAME
);
626 rewriteApplyToConstCache
[n
] = newvar
;
627 Trace("rewriteApplyToConst") << "made :: " << newvar
<< std::endl
;
631 ss
<< "The rewrite-apply-to-const preprocessor is currently limited;\n"
632 << "it only works if all function symbols are unary and with Integer\n"
633 << "domain, and all applications are to integer values.\n"
634 << "Found application: " << n
;
639 NodeBuilder
<> builder(n
.getKind());
640 if(n
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
641 builder
<< n
.getOperator();
643 for(unsigned i
= 0; i
< n
.getNumChildren(); ++i
) {
644 builder
<< rewriteApplyToConst(n
[i
]);
647 rewriteApplyToConstCache
[n
] = rewr
;
648 Trace("rewriteApplyToConst") << "built :: " << rewr
<< std::endl
;
652 };/* class SmtEnginePrivate */
654 }/* namespace CVC4::smt */
656 SmtEngine::SmtEngine(ExprManager
* em
) throw() :
657 d_context(em
->getContext()),
659 d_userContext(new UserContext()),
661 d_nodeManager(d_exprManager
->getNodeManager()),
662 d_decisionEngine(NULL
),
663 d_theoryEngine(NULL
),
665 d_proofManager(NULL
),
666 d_definedFunctions(NULL
),
667 d_assertionList(NULL
),
669 d_modelGlobalCommands(),
670 d_modelCommands(NULL
),
674 d_fullyInited(false),
675 d_problemExtended(false),
677 d_needPostsolve(false),
678 d_earlyTheoryPP(true),
679 d_timeBudgetCumulative(0),
680 d_timeBudgetPerCall(0),
681 d_resourceBudgetCumulative(0),
682 d_resourceBudgetPerCall(0),
683 d_cumulativeTimeUsed(0),
684 d_cumulativeResourceUsed(0),
687 d_statisticsRegistry(NULL
),
691 d_private
= new smt::SmtEnginePrivate(*this);
692 d_statisticsRegistry
= new StatisticsRegistry();
693 d_stats
= new SmtEngineStatistics();
695 PROOF( d_proofManager
= new ProofManager(); );
697 // We have mutual dependency here, so we add the prop engine to the theory
698 // engine later (it is non-essential there)
699 d_theoryEngine
= new TheoryEngine(d_context
, d_userContext
, d_private
->d_iteRemover
, const_cast<const LogicInfo
&>(d_logic
));
702 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
703 TheoryConstructor::addTheory(d_theoryEngine
, id
);
706 // global push/pop around everything, to ensure proper destruction
707 // of context-dependent data structures
708 d_userContext
->push();
711 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
712 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
715 void SmtEngine::finishInit() {
716 // ensure that our heuristics are properly set up
719 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
720 d_decisionEngine
->init(); // enable appropriate strategies
722 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
, d_userContext
);
724 d_theoryEngine
->setPropEngine(d_propEngine
);
725 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
726 d_theoryEngine
->finishInit();
728 // [MGD 10/20/2011] keep around in incremental mode, due to a
729 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
730 // first, some user-context-dependent TNodes might still exist
732 if(options::interactive() ||
733 options::incrementalSolving()) {
734 // In the case of incremental solving, we appear to need these to
735 // ensure the relevant Nodes remain live.
736 d_assertionList
= new(true) AssertionList(d_userContext
);
739 // dump out a set-logic command
740 if(Dump
.isOn("benchmark")) {
741 // Dump("benchmark") << SetBenchmarkLogicCommand(logic.getLogicString());
742 LogicInfo everything
;
744 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, \"all-supported\" logic (below), as some internals might require the use of a logic more general than the input.")
745 << SetBenchmarkLogicCommand(everything
.getLogicString());
748 // dump out any pending declaration commands
749 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
750 Dump("declarations") << *d_dumpCommands
[i
];
751 delete d_dumpCommands
[i
];
753 d_dumpCommands
.clear();
755 if(options::perCallResourceLimit() != 0) {
756 setResourceLimit(options::perCallResourceLimit(), false);
758 if(options::cumulativeResourceLimit() != 0) {
759 setResourceLimit(options::cumulativeResourceLimit(), true);
761 if(options::perCallMillisecondLimit() != 0) {
762 setTimeLimit(options::perCallMillisecondLimit(), false);
764 if(options::cumulativeMillisecondLimit() != 0) {
765 setTimeLimit(options::cumulativeMillisecondLimit(), true);
768 PROOF( ProofManager::currentPM()->setLogic(d_logic
.getLogicString()); );
771 void SmtEngine::finalOptionsAreSet() {
776 if(! d_logic
.isLocked()) {
780 // finish initialization, create the prop engine, etc.
783 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
784 "The PropEngine has pushed but the SmtEngine "
785 "hasn't finished initializing!" );
787 d_fullyInited
= true;
788 Assert(d_logic
.isLocked());
790 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
791 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
794 void SmtEngine::shutdown() {
797 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
801 // check to see if a postsolve() is pending
802 if(d_needPostsolve
) {
803 d_theoryEngine
->postsolve();
804 d_needPostsolve
= false;
807 if(d_propEngine
!= NULL
) {
808 d_propEngine
->shutdown();
810 if(d_theoryEngine
!= NULL
) {
811 d_theoryEngine
->shutdown();
813 if(d_decisionEngine
!= NULL
) {
814 d_decisionEngine
->shutdown();
818 SmtEngine::~SmtEngine() throw() {
824 // global push/pop around everything, to ensure proper destruction
825 // of context-dependent data structures
827 d_userContext
->popto(0);
829 if(d_assignments
!= NULL
) {
830 d_assignments
->deleteSelf();
833 if(d_assertionList
!= NULL
) {
834 d_assertionList
->deleteSelf();
837 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
838 delete d_dumpCommands
[i
];
840 d_dumpCommands
.clear();
842 if(d_modelCommands
!= NULL
) {
843 d_modelCommands
->deleteSelf();
846 d_definedFunctions
->deleteSelf();
848 delete d_theoryEngine
;
850 delete d_decisionEngine
;
853 delete d_statisticsRegistry
;
857 delete d_userContext
;
859 } catch(Exception
& e
) {
860 Warning() << "CVC4 threw an exception during cleanup." << endl
865 void SmtEngine::setLogic(const LogicInfo
& logic
) throw(ModalException
) {
868 throw ModalException("Cannot set logic in SmtEngine after the engine has finished initializing");
874 void SmtEngine::setLogic(const std::string
& s
) throw(ModalException
, LogicException
) {
877 setLogic(LogicInfo(s
));
878 } catch(IllegalArgumentException
& e
) {
879 throw LogicException(e
.what());
883 void SmtEngine::setLogic(const char* logic
) throw(ModalException
, LogicException
) {
884 setLogic(string(logic
));
887 LogicInfo
SmtEngine::getLogicInfo() const {
891 void SmtEngine::setLogicInternal() throw() {
892 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already finished initializing for this run");
896 void SmtEngine::setDefaults() {
897 if(options::forceLogic
.wasSetByUser()) {
898 d_logic
= options::forceLogic();
902 /* - disabled for 1.4 release [MGD 2014.06.25]
903 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
904 if(! options::stringExp.wasSetByUser()) {
905 options::stringExp.set( true );
906 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
911 if(options::stringExp()) {
912 if( !d_logic
.isQuantified() ) {
913 d_logic
= d_logic
.getUnlockedCopy();
914 d_logic
.enableQuantifiers();
916 Trace("smt") << "turning on quantifier logic, for strings-exp" << std::endl
;
918 if(! options::finiteModelFind
.wasSetByUser()) {
919 options::finiteModelFind
.set( true );
920 Trace("smt") << "turning on finite-model-find, for strings-exp" << std::endl
;
922 if(! options::fmfBoundInt
.wasSetByUser()) {
923 if(! options::fmfBoundIntLazy
.wasSetByUser()) {
924 options::fmfBoundIntLazy
.set( true );
926 options::fmfBoundInt
.set( true );
927 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
930 if(! options::rewriteDivk.wasSetByUser()) {
931 options::rewriteDivk.set( true );
932 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
935 if(! options::stringFMF.wasSetByUser()) {
936 options::stringFMF.set( true );
937 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
942 if(options::checkModels()) {
943 if(! options::interactive()) {
944 Notice() << "SmtEngine: turning on interactive-mode to support check-models" << endl
;
945 setOption("interactive-mode", SExpr("true"));
949 if(options::unsatCores()) {
950 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
951 if(options::simplificationMode
.wasSetByUser()) {
952 throw OptionException("simplification not supported with unsat cores");
954 Notice() << "SmtEngine: turning off simplification to support unsat-cores" << endl
;
955 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
958 if(options::unconstrainedSimp()) {
959 if(options::unconstrainedSimp
.wasSetByUser()) {
960 throw OptionException("unconstrained simplification not supported with unsat cores");
962 Notice() << "SmtEngine: turning off unconstrained simplification to support unsat-cores" << endl
;
963 options::unconstrainedSimp
.set(false);
966 if(options::pbRewrites()) {
967 if(options::pbRewrites
.wasSetByUser()) {
968 throw OptionException("pseudoboolean rewrites not supported with unsat cores");
970 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support unsat-cores" << endl
;
971 setOption("pb-rewrites", false);
974 if(options::sortInference()) {
975 if(options::sortInference
.wasSetByUser()) {
976 throw OptionException("sort inference not supported with unsat cores");
978 Notice() << "SmtEngine: turning off sort inference to support unsat-cores" << endl
;
979 options::sortInference
.set(false);
982 if(options::preSkolemQuant()) {
983 if(options::preSkolemQuant
.wasSetByUser()) {
984 throw OptionException("pre-skolemization not supported with unsat cores");
986 Notice() << "SmtEngine: turning off pre-skolemization to support unsat-cores" << endl
;
987 options::preSkolemQuant
.set(false);
990 if(options::bitvectorToBool()) {
991 if(options::bitvectorToBool
.wasSetByUser()) {
992 throw OptionException("bv-to-bool not supported with unsat cores");
994 Notice() << "SmtEngine: turning off bitvector-to-bool support unsat-cores" << endl
;
995 options::bitvectorToBool
.set(false);
998 if(options::bvIntroducePow2()) {
999 if(options::bvIntroducePow2
.wasSetByUser()) {
1000 throw OptionException("bv-intro-pow2 not supported with unsat cores");
1002 Notice() << "SmtEngine: turning off bv-introduce-pow2 to support unsat-cores" << endl
;
1003 setOption("bv-intro-pow2", false);
1007 if(options::produceAssignments() && !options::produceModels()) {
1008 Notice() << "SmtEngine: turning on produce-models to support produce-assignments" << endl
;
1009 setOption("produce-models", SExpr("true"));
1012 // Set the options for the theoryOf
1013 if(!options::theoryOfMode
.wasSetByUser()) {
1014 if(d_logic
.isSharingEnabled() && !d_logic
.isTheoryEnabled(THEORY_BV
) && !d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1015 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1016 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1020 // by default, symmetry breaker is on only for QF_UF
1021 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1022 bool qf_uf
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified();
1023 Trace("smt") << "setting uf symmetry breaker to " << qf_uf
<< endl
;
1024 options::ufSymmetryBreaker
.set(qf_uf
);
1026 // by default, nonclausal simplification is off for QF_SAT
1027 if(! options::simplificationMode
.wasSetByUser()) {
1028 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1029 Trace("smt") << "setting simplification mode to <" << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1030 //simplification=none works better for SMT LIB benchmarks with quantifiers, not others
1031 //options::simplificationMode.set(qf_sat || quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1032 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
: SIMPLIFICATION_MODE_BATCH
);
1035 // If in arrays, set the UF handler to arrays
1036 if(d_logic
.isTheoryEnabled(THEORY_ARRAY
) && ( !d_logic
.isQuantified() ||
1037 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1038 Theory::setUninterpretedSortOwner(THEORY_ARRAY
);
1040 Theory::setUninterpretedSortOwner(THEORY_UF
);
1042 // Turn on ite simplification for QF_LIA and QF_AUFBV
1043 if(! options::doITESimp
.wasSetByUser()) {
1044 bool qf_aufbv
= !d_logic
.isQuantified() &&
1045 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1046 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1047 d_logic
.isTheoryEnabled(THEORY_BV
);
1048 bool qf_lia
= !d_logic
.isQuantified() &&
1049 d_logic
.isPure(THEORY_ARITH
) &&
1050 d_logic
.isLinear() &&
1051 !d_logic
.isDifferenceLogic() &&
1052 !d_logic
.areRealsUsed();
1054 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1055 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1056 options::doITESimp
.set(iteSimp
);
1058 if(! options::compressItes
.wasSetByUser() ){
1059 bool qf_lia
= !d_logic
.isQuantified() &&
1060 d_logic
.isPure(THEORY_ARITH
) &&
1061 d_logic
.isLinear() &&
1062 !d_logic
.isDifferenceLogic() &&
1063 !d_logic
.areRealsUsed();
1065 bool compressIte
= qf_lia
;
1066 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1067 options::compressItes
.set(compressIte
);
1069 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1070 bool qf_aufbv
= !d_logic
.isQuantified() &&
1071 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1072 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1073 d_logic
.isTheoryEnabled(THEORY_BV
);
1075 bool withCare
= qf_aufbv
;
1076 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1077 options::simplifyWithCareEnabled
.set(withCare
);
1079 // Turn off array eager index splitting for QF_AUFLIA
1080 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1081 if (not d_logic
.isQuantified() &&
1082 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1083 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1084 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1085 Trace("smt") << "setting array eager index splitting to false" << endl
;
1086 options::arraysEagerIndexSplitting
.set(false);
1089 // Turn on model-based arrays for QF_AX (unless models are enabled)
1090 // if(! options::arraysModelBased.wasSetByUser()) {
1091 // if (not d_logic.isQuantified() &&
1092 // d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1093 // d_logic.isPure(THEORY_ARRAY) &&
1094 // !options::produceModels() &&
1095 // !options::checkModels()) {
1096 // Trace("smt") << "turning on model-based array solver" << endl;
1097 // options::arraysModelBased.set(true);
1100 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1101 if(! options::repeatSimp
.wasSetByUser()) {
1102 bool repeatSimp
= !d_logic
.isQuantified() &&
1103 (d_logic
.isTheoryEnabled(THEORY_ARRAY
) && d_logic
.isTheoryEnabled(THEORY_UF
) && d_logic
.isTheoryEnabled(THEORY_BV
));
1104 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1105 options::repeatSimp
.set(repeatSimp
);
1107 // Turn on unconstrained simplification for QF_AUFBV
1108 if(! options::unconstrainedSimp
.wasSetByUser() || options::incrementalSolving()) {
1109 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1110 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1111 bool uncSimp
= !options::incrementalSolving() && !d_logic
.isQuantified() && !options::produceModels() && !options::produceAssignments() && !options::checkModels() &&
1112 (d_logic
.isTheoryEnabled(THEORY_ARRAY
) && d_logic
.isTheoryEnabled(THEORY_BV
));
1113 Trace("smt") << "setting unconstrained simplification to " << uncSimp
<< endl
;
1114 options::unconstrainedSimp
.set(uncSimp
);
1116 // Unconstrained simp currently does *not* support model generation
1117 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1118 if (options::produceModels()) {
1119 if (options::produceModels
.wasSetByUser()) {
1120 throw OptionException("Cannot use unconstrained-simp with model generation.");
1122 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1123 setOption("produce-models", SExpr("false"));
1125 if (options::produceAssignments()) {
1126 if (options::produceAssignments
.wasSetByUser()) {
1127 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1129 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1130 setOption("produce-assignments", SExpr("false"));
1132 if (options::checkModels()) {
1133 if (options::checkModels
.wasSetByUser()) {
1134 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1136 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1137 setOption("check-models", SExpr("false"));
1142 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
1143 options::incrementalSolving()) {
1144 if (options::incrementalSolving
.wasSetByUser()) {
1145 throw OptionException(std::string("Eager bit-blasting does not currently support incremental mode. \n\
1146 Try --bitblast=lazy"));
1148 Notice() << "SmtEngine: turning off incremental to support eager bit-blasting" << endl
;
1149 setOption("incremental", SExpr("false"));
1152 if (! options::bvEagerExplanations
.wasSetByUser() &&
1153 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1154 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1155 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1156 options::bvEagerExplanations
.set(true);
1159 // Turn on arith rewrite equalities only for pure arithmetic
1160 if(! options::arithRewriteEq
.wasSetByUser()) {
1161 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified();
1162 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1163 options::arithRewriteEq
.set(arithRewriteEq
);
1165 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1166 int16_t heuristicPivots
= 5;
1167 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1168 if(d_logic
.isDifferenceLogic()) {
1169 heuristicPivots
= -1;
1170 } else if(!d_logic
.areIntegersUsed()) {
1171 heuristicPivots
= 0;
1174 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1175 options::arithHeuristicPivots
.set(heuristicPivots
);
1177 if(! options::arithPivotThreshold
.wasSetByUser()){
1178 uint16_t pivotThreshold
= 2;
1179 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1180 if(d_logic
.isDifferenceLogic()){
1181 pivotThreshold
= 16;
1184 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1185 options::arithPivotThreshold
.set(pivotThreshold
);
1187 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1188 int16_t varOrderPivots
= -1;
1189 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1190 varOrderPivots
= 200;
1192 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1193 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1195 // Turn off early theory preprocessing if arithRewriteEq is on
1196 if (options::arithRewriteEq()) {
1197 d_earlyTheoryPP
= false;
1200 // Set decision mode based on logic (if not set by user)
1201 if(!options::decisionMode
.wasSetByUser()) {
1202 decision::DecisionMode decMode
=
1204 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1206 (not d_logic
.isQuantified() &&
1207 d_logic
.isPure(THEORY_BV
)
1209 // QF_AUFBV or QF_ABV or QF_UFBV
1210 (not d_logic
.isQuantified() &&
1211 (d_logic
.isTheoryEnabled(THEORY_ARRAY
) ||
1212 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1213 d_logic
.isTheoryEnabled(THEORY_BV
)
1215 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1216 (not d_logic
.isQuantified() &&
1217 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1218 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1219 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1222 (not d_logic
.isQuantified() &&
1223 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1226 d_logic
.isQuantified() ||
1228 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1229 ? decision::DECISION_STRATEGY_JUSTIFICATION
1230 : decision::DECISION_STRATEGY_INTERNAL
1235 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1237 (not d_logic
.isQuantified() &&
1238 d_logic
.isTheoryEnabled(THEORY_ARRAY
) &&
1239 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1240 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1243 (not d_logic
.isQuantified() &&
1244 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1249 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1250 options::decisionMode
.set(decMode
);
1251 options::decisionStopOnly
.set(stoponly
);
1254 //for finite model finding
1255 if( ! options::instWhenMode
.wasSetByUser()){
1256 //instantiate only on last call
1257 if( options::fmfInstEngine() ){
1258 Trace("smt") << "setting inst when mode to LAST_CALL" << endl
;
1259 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1262 if( d_logic
.hasCardinalityConstraints() ){
1263 //must have finite model finding on
1264 options::finiteModelFind
.set( true );
1266 if( options::recurseCbqi() ){
1267 options::cbqi
.set( true );
1269 if(options::fmfBoundIntLazy
.wasSetByUser() && options::fmfBoundIntLazy()) {
1270 options::fmfBoundInt
.set( true );
1272 if( options::fmfBoundInt() ){
1273 //must have finite model finding on
1274 options::finiteModelFind
.set( true );
1275 if( ! options::mbqiMode
.wasSetByUser() ||
1276 ( options::mbqiMode()!=quantifiers::MBQI_NONE
&&
1277 options::mbqiMode()!=quantifiers::MBQI_FMC
&&
1278 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL
) ){
1279 //if bounded integers are set, use no MBQI by default
1280 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1283 if( options::mbqiMode()==quantifiers::MBQI_INTERVAL
){
1284 //must do pre-skolemization
1285 options::preSkolemQuant
.set( true );
1287 if( options::ufssSymBreak() ){
1288 options::sortInference
.set( true );
1290 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
1291 options::quantConflictFind
.set( true );
1293 //for induction techniques
1294 if( options::quantInduction() ){
1295 if( !options::dtStcInduction
.wasSetByUser() ){
1296 options::dtStcInduction
.set( true );
1298 if( !options::intWfInduction
.wasSetByUser() ){
1299 options::intWfInduction
.set( true );
1302 if( options::dtStcInduction() ){
1303 if( !options::dtForceAssignment
.wasSetByUser() ){
1304 options::dtForceAssignment
.set( true );
1307 if( options::intWfInduction() ){
1308 if( !options::purifyTriggers
.wasSetByUser() ){
1309 options::purifyTriggers
.set( true );
1313 //until bugs 371,431 are fixed
1314 if( ! options::minisatUseElim
.wasSetByUser()){
1315 if( d_logic
.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
1316 options::minisatUseElim
.set( false );
1319 else if (options::minisatUseElim()) {
1320 if (options::produceModels()) {
1321 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
1322 setOption("produce-models", SExpr("false"));
1324 if (options::produceAssignments()) {
1325 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
1326 setOption("produce-assignments", SExpr("false"));
1328 if (options::checkModels()) {
1329 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
1330 setOption("check-models", SExpr("false"));
1334 // For now, these array theory optimizations do not support model-building
1335 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
1336 options::arraysOptimizeLinear
.set(false);
1337 options::arraysLazyRIntro1
.set(false);
1340 // Non-linear arithmetic does not support models
1341 if (d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
1342 !d_logic
.isLinear()) {
1343 if (options::produceModels()) {
1344 Warning() << "SmtEngine: turning off produce-models because unsupported for nonlinear arith" << endl
;
1345 setOption("produce-models", SExpr("false"));
1347 if (options::produceAssignments()) {
1348 Warning() << "SmtEngine: turning off produce-assignments because unsupported for nonlinear arith" << endl
;
1349 setOption("produce-assignments", SExpr("false"));
1351 if (options::checkModels()) {
1352 Warning() << "SmtEngine: turning off check-models because unsupported for nonlinear arith" << endl
;
1353 setOption("check-models", SExpr("false"));
1357 if (options::incrementalSolving() && options::proof()) {
1358 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof" << endl
;
1359 setOption("incremental", SExpr("false"));
1363 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
1364 throw(OptionException
, ModalException
) {
1366 SmtScope
smts(this);
1368 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
1369 if(Dump
.isOn("benchmark")) {
1370 if(key
== "status") {
1371 string s
= value
.getValue();
1372 BenchmarkStatus status
=
1373 (s
== "sat") ? SMT_SATISFIABLE
:
1374 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
1375 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
1377 Dump("benchmark") << SetInfoCommand(key
, value
);
1381 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
1382 if(key
.length() > 5) {
1383 string prefix
= key
.substr(0, 5);
1384 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
1385 string cvc4key
= key
.substr(5);
1386 if(cvc4key
== "logic") {
1387 if(! value
.isAtom()) {
1388 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
1390 SmtScope
smts(this);
1391 d_logic
= value
.getValue();
1395 throw UnrecognizedOptionException();
1400 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
1401 if(key
== "source" ||
1402 key
== "category" ||
1403 key
== "difficulty" ||
1407 } else if(key
== "name") {
1408 d_filename
= value
.getValue();
1410 } else if(key
== "smt-lib-version") {
1411 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
1412 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
1413 (value
.getValue() == "2") ) {
1414 // supported SMT-LIB version
1417 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
1418 throw UnrecognizedOptionException();
1419 } else if(key
== "status") {
1421 if(value
.isAtom()) {
1422 s
= value
.getValue();
1424 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
1425 throw OptionException("argument to (set-info :status ..) must be "
1426 "`sat' or `unsat' or `unknown'");
1428 d_status
= Result(s
, d_filename
);
1431 throw UnrecognizedOptionException();
1434 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const
1435 throw(OptionException
, ModalException
) {
1437 SmtScope
smts(this);
1439 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
1440 if(key
== "all-statistics") {
1441 vector
<SExpr
> stats
;
1442 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
1443 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
1446 v
.push_back((*i
).first
);
1447 v
.push_back((*i
).second
);
1450 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
1451 i
!= d_statisticsRegistry
->end();
1454 v
.push_back((*i
).first
);
1455 v
.push_back((*i
).second
);
1459 } else if(key
== "error-behavior") {
1460 // immediate-exit | continued-execution
1461 if( options::continuedExecution() || options::interactive() ) {
1462 return SExpr::Keyword("continued-execution");
1464 return SExpr::Keyword("immediate-exit");
1466 } else if(key
== "name") {
1467 return Configuration::getName();
1468 } else if(key
== "version") {
1469 return Configuration::getVersionString();
1470 } else if(key
== "authors") {
1471 return Configuration::about();
1472 } else if(key
== "status") {
1473 // sat | unsat | unknown
1474 switch(d_status
.asSatisfiabilityResult().isSat()) {
1476 return SExpr::Keyword("sat");
1478 return SExpr::Keyword("unsat");
1480 return SExpr::Keyword("unknown");
1482 } else if(key
== "reason-unknown") {
1483 if(!d_status
.isNull() && d_status
.isUnknown()) {
1485 ss
<< d_status
.whyUnknown();
1486 string s
= ss
.str();
1487 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
1488 return SExpr::Keyword(s
);
1490 throw ModalException("Can't get-info :reason-unknown when the "
1491 "last result wasn't unknown!");
1493 } else if(key
== "all-options") {
1494 // get the options, like all-statistics
1495 return Options::current().getOptions();
1497 throw UnrecognizedOptionException();
1501 void SmtEngine::defineFunction(Expr func
,
1502 const std::vector
<Expr
>& formals
,
1504 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
1505 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
1506 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
1508 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
1509 << "definition of function " << func
<< ", formal\n"
1510 << " " << *i
<< "\n"
1511 << "has kind " << (*i
).getKind();
1512 throw TypeCheckingException(func
, ss
.str());
1517 ss
<< Expr::setlanguage(Expr::setlanguage::getLanguage(Dump
.getStream()))
1519 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
1520 addToModelCommandAndDump(c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
1522 SmtScope
smts(this);
1524 // Substitute out any abstract values in formula
1525 Expr form
= d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
1528 Type formulaType
= form
.getType(options::typeChecking());
1530 Type funcType
= func
.getType();
1531 // We distinguish here between definitions of constants and functions,
1532 // because the type checking for them is subtly different. Perhaps we
1533 // should instead have SmtEngine::defineFunction() and
1534 // SmtEngine::defineConstant() for better clarity, although then that
1535 // doesn't match the SMT-LIBv2 standard...
1536 if(formals
.size() > 0) {
1537 Type rangeType
= FunctionType(funcType
).getRangeType();
1538 if(! formulaType
.isComparableTo(rangeType
)) {
1540 ss
<< "Type of defined function does not match its declaration\n"
1541 << "The function : " << func
<< "\n"
1542 << "Declared type : " << rangeType
<< "\n"
1543 << "The body : " << formula
<< "\n"
1544 << "Body type : " << formulaType
;
1545 throw TypeCheckingException(func
, ss
.str());
1548 if(! formulaType
.isComparableTo(funcType
)) {
1550 ss
<< "Declared type of defined constant does not match its definition\n"
1551 << "The constant : " << func
<< "\n"
1552 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
1553 << "The definition : " << formula
<< "\n"
1554 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
1555 throw TypeCheckingException(func
, ss
.str());
1558 TNode funcNode
= func
.getTNode();
1559 vector
<Node
> formalsNodes
;
1560 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
1561 iend
= formals
.end();
1564 formalsNodes
.push_back((*i
).getNode());
1566 TNode formNode
= form
.getTNode();
1567 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
1568 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
1569 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
1570 // d_haveAdditions = true;
1571 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
1572 d_definedFunctions
->insert(funcNode
, def
);
1575 Node
SmtEnginePrivate::expandDefinitions(TNode n
, hash_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
1576 throw(TypeCheckingException
, LogicException
) {
1578 stack
< triple
<Node
, Node
, bool> > worklist
;
1580 worklist
.push(make_triple(Node(n
), Node(n
), false));
1581 // The worklist is made of triples, each is input / original node then the output / rewritten node
1582 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
1586 n
= worklist
.top().first
; // n is the input / original
1587 Node node
= worklist
.top().second
; // node is the output / result
1588 bool childrenPushed
= worklist
.top().third
;
1591 // Working downwards
1592 if(!childrenPushed
) {
1593 Kind k
= n
.getKind();
1595 // Apart from apply, we can short circuit leaves
1596 if(k
!= kind::APPLY
&& n
.getNumChildren() == 0) {
1597 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
1598 if(i
!= d_smt
.d_definedFunctions
->end()) {
1599 // replacement must be closed
1600 if((*i
).second
.getFormals().size() > 0) {
1601 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
1604 // don't bother putting in the cache
1605 result
.push((*i
).second
.getFormula());
1608 // don't bother putting in the cache
1613 // maybe it's in the cache
1614 hash_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
1615 if(cacheHit
!= cache
.end()) {
1616 TNode ret
= (*cacheHit
).second
;
1617 result
.push(ret
.isNull() ? n
: ret
);
1621 // otherwise expand it
1622 if (k
== kind::APPLY
) {
1623 // application of a user-defined symbol
1624 TNode func
= n
.getOperator();
1625 SmtEngine::DefinedFunctionMap::const_iterator i
=
1626 d_smt
.d_definedFunctions
->find(func
);
1627 DefinedFunction def
= (*i
).second
;
1628 vector
<Node
> formals
= def
.getFormals();
1630 if(Debug
.isOn("expand")) {
1631 Debug("expand") << "found: " << n
<< endl
;
1632 Debug("expand") << " func: " << func
<< endl
;
1633 string name
= func
.getAttribute(expr::VarNameAttr());
1634 Debug("expand") << " : \"" << name
<< "\"" << endl
;
1636 if(i
== d_smt
.d_definedFunctions
->end()) {
1637 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
1639 if(Debug
.isOn("expand")) {
1640 Debug("expand") << " defn: " << def
.getFunction() << endl
1642 if(formals
.size() > 0) {
1643 copy( formals
.begin(), formals
.end() - 1,
1644 ostream_iterator
<Node
>(Debug("expand"), ", ") );
1645 Debug("expand") << formals
.back();
1647 Debug("expand") << "]" << endl
1648 << " " << def
.getFunction().getType() << endl
1649 << " " << def
.getFormula() << endl
;
1652 TNode fm
= def
.getFormula();
1653 Node instance
= fm
.substitute(formals
.begin(), formals
.end(),
1654 n
.begin(), n
.end());
1655 Debug("expand") << "made : " << instance
<< endl
;
1657 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
1658 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
1659 result
.push(expanded
);
1662 } else if(! expandOnly
) {
1663 // do not do any theory stuff if expandOnly is true
1665 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
1668 LogicRequest
req(d_smt
);
1669 node
= t
->expandDefinition(req
, n
);
1672 // there should be children here, otherwise we short-circuited a result-push/continue, above
1673 if (node
.getNumChildren() == 0) {
1674 Debug("expand") << "Unexpectedly no children..." << node
<< endl
;
1676 // This invariant holds at the moment but it is concievable that a new theory
1677 // might introduce a kind which can have children before definition expansion but doesn't
1678 // afterwards. If this happens, remove this assertion.
1679 Assert(node
.getNumChildren() > 0);
1681 // the partial functions can fall through, in which case we still
1682 // consider their children
1683 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
1685 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
1686 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
1691 // Reconstruct the node from it's (now rewritten) children on the stack
1693 Debug("expand") << "cons : " << node
<< endl
;
1694 //cout << "cons : " << node << endl;
1695 NodeBuilder
<> nb(node
.getKind());
1696 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
1697 Debug("expand") << "op : " << node
.getOperator() << endl
;
1698 //cout << "op : " << node.getOperator() << endl;
1699 nb
<< node
.getOperator();
1701 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
1702 Assert(!result
.empty());
1703 Node expanded
= result
.top();
1705 //cout << "exchld : " << expanded << endl;
1706 Debug("expand") << "exchld : " << expanded
<< endl
;
1710 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
1713 } while(!worklist
.empty());
1715 AlwaysAssert(result
.size() == 1);
1717 return result
.top();
1720 void SmtEnginePrivate::removeITEs() {
1721 d_smt
.finalOptionsAreSet();
1723 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
1725 // Remove all of the ITE occurrences and normalize
1726 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
1727 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
1728 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
1732 void SmtEnginePrivate::staticLearning() {
1733 d_smt
.finalOptionsAreSet();
1735 TimerStat::CodeTimer
staticLearningTimer(d_smt
.d_stats
->d_staticLearningTime
);
1737 Trace("simplify") << "SmtEnginePrivate::staticLearning()" << endl
;
1739 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
1741 NodeBuilder
<> learned(kind::AND
);
1742 learned
<< d_assertions
[i
];
1743 d_smt
.d_theoryEngine
->ppStaticLearn(d_assertions
[i
], learned
);
1744 if(learned
.getNumChildren() == 1) {
1747 d_assertions
.replace(i
, learned
);
1752 // do dumping (before/after any preprocessing pass)
1753 static void dumpAssertions(const char* key
, const AssertionPipeline
& assertionList
) {
1754 if( Dump
.isOn("assertions") &&
1755 Dump
.isOn(string("assertions:") + key
) ) {
1756 // Push the simplified assertions to the dump output stream
1757 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
1758 TNode n
= assertionList
[i
];
1759 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
1764 // returns false if it learns a conflict
1765 bool SmtEnginePrivate::nonClausalSimplify() {
1766 d_smt
.finalOptionsAreSet();
1768 if(options::unsatCores()) {
1772 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
1774 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
1776 if(d_propagatorNeedsFinish
) {
1777 d_propagator
.finish();
1778 d_propagatorNeedsFinish
= false;
1780 d_propagator
.initialize();
1782 // Assert all the assertions to the propagator
1783 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1784 << "asserting to propagator" << endl
;
1785 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
1786 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
1787 // Don't reprocess substitutions
1788 if (d_substitutionsIndex
> 0 && i
== d_substitutionsIndex
) {
1791 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
1792 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
1793 d_propagator
.assertTrue(d_assertions
[i
]);
1796 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1797 << "propagating" << endl
;
1798 if (d_propagator
.propagate()) {
1799 // If in conflict, just return false
1800 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1801 << "conflict in non-clausal propagation" << endl
;
1802 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
1803 Assert(!options::unsatCores());
1804 d_assertions
.clear();
1805 d_assertions
.push_back(falseNode
);
1806 d_propagatorNeedsFinish
= true;
1810 // No conflict, go through the literals and solve them
1811 SubstitutionMap
constantPropagations(d_smt
.d_context
);
1812 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
1813 SubstitutionMap::iterator pos
;
1815 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
1816 // Simplify the literal we learned wrt previous substitutions
1817 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
1818 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
1819 Assert(d_topLevelSubstitutions
.apply(learnedLiteral
) == learnedLiteral
);
1820 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
1821 if (learnedLiteral
!= learnedLiteralNew
) {
1822 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
1825 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
1826 if (learnedLiteralNew
== learnedLiteral
) {
1829 ++d_smt
.d_stats
->d_numConstantProps
;
1830 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
1832 // It might just simplify to a constant
1833 if (learnedLiteral
.isConst()) {
1834 if (learnedLiteral
.getConst
<bool>()) {
1835 // If the learned literal simplifies to true, it's redundant
1838 // If the learned literal simplifies to false, we're in conflict
1839 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1841 << d_nonClausalLearnedLiterals
[i
] << endl
;
1842 Assert(!options::unsatCores());
1843 d_assertions
.clear();
1844 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(false));
1845 d_propagatorNeedsFinish
= true;
1850 // Solve it with the corresponding theory, possibly adding new
1851 // substitutions to newSubstitutions
1852 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1853 << "solving " << learnedLiteral
<< endl
;
1855 Theory::PPAssertStatus solveStatus
=
1856 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
1858 switch (solveStatus
) {
1859 case Theory::PP_ASSERT_STATUS_SOLVED
: {
1860 // The literal should rewrite to true
1861 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1862 << "solved " << learnedLiteral
<< endl
;
1863 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
1864 // vector<pair<Node, Node> > equations;
1865 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
1866 // if (equations.empty()) {
1869 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
1870 // else fall through
1873 case Theory::PP_ASSERT_STATUS_CONFLICT
:
1874 // If in conflict, we return false
1875 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1876 << "conflict while solving "
1877 << learnedLiteral
<< endl
;
1878 Assert(!options::unsatCores());
1879 d_assertions
.clear();
1880 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(false));
1881 d_propagatorNeedsFinish
= true;
1884 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
1885 // constant propagation
1888 if (learnedLiteral
[0].isConst()) {
1889 t
= learnedLiteral
[1];
1890 c
= learnedLiteral
[0];
1893 t
= learnedLiteral
[0];
1894 c
= learnedLiteral
[1];
1896 Assert(!t
.isConst());
1897 Assert(constantPropagations
.apply(t
) == t
);
1898 Assert(d_topLevelSubstitutions
.apply(t
) == t
);
1899 Assert(newSubstitutions
.apply(t
) == t
);
1900 constantPropagations
.addSubstitution(t
, c
);
1901 // vector<pair<Node,Node> > equations;
1902 // constantPropagations.simplifyLHS(t, c, equations, true);
1903 // if (!equations.empty()) {
1904 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
1905 // d_assertions.clear();
1906 // d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(false));
1909 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
1913 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
1918 #ifdef CVC4_ASSERTIONS
1919 // Check data structure invariants:
1920 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
1921 // 2. each lhs of constantPropagations rewrites to itself
1922 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' -> r' another constant propagation, then l'[l/r] -> r' should be a
1923 // constant propagation too
1924 // 4. each lhs of constantPropagations is different from each rhs
1925 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
1926 Assert((*pos
).first
.isVar());
1927 Assert(d_topLevelSubstitutions
.apply((*pos
).first
) == (*pos
).first
);
1928 Assert(d_topLevelSubstitutions
.apply((*pos
).second
) == (*pos
).second
);
1929 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
1931 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
1932 Assert((*pos
).second
.isConst());
1933 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
1934 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
1935 // if (newLeft != (*pos).first) {
1936 // newLeft = Rewriter::rewrite(newLeft);
1937 // Assert(newLeft == (*pos).second ||
1938 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
1940 // newLeft = constantPropagations.apply((*pos).first);
1941 // if (newLeft != (*pos).first) {
1942 // newLeft = Rewriter::rewrite(newLeft);
1943 // Assert(newLeft == (*pos).second ||
1944 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
1946 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
1948 #endif /* CVC4_ASSERTIONS */
1950 // Resize the learnt
1951 d_nonClausalLearnedLiterals
.resize(j
);
1953 hash_set
<TNode
, TNodeHashFunction
> s
;
1954 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
1955 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
1956 Node assertion
= d_assertions
[i
];
1957 Node assertionNew
= newSubstitutions
.apply(assertion
);
1958 Trace("debugging") << "assertion = " << assertion
<< endl
;
1959 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
1960 if (assertion
!= assertionNew
) {
1961 assertion
= Rewriter::rewrite(assertionNew
);
1962 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
1964 Assert(Rewriter::rewrite(assertion
) == assertion
);
1966 assertionNew
= constantPropagations
.apply(assertion
);
1967 if (assertionNew
== assertion
) {
1970 ++d_smt
.d_stats
->d_numConstantProps
;
1971 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
1972 assertion
= Rewriter::rewrite(assertionNew
);
1973 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
1975 Trace("debugging") << "\n";
1976 s
.insert(assertion
);
1977 d_assertions
.replace(i
, assertion
);
1978 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1979 << "non-clausal preprocessed: "
1980 << assertion
<< endl
;
1983 // If in incremental mode, add substitutions to the list of assertions
1984 if (d_substitutionsIndex
> 0) {
1985 NodeBuilder
<> substitutionsBuilder(kind::AND
);
1986 substitutionsBuilder
<< d_assertions
[d_substitutionsIndex
];
1987 pos
= newSubstitutions
.begin();
1988 for (; pos
!= newSubstitutions
.end(); ++pos
) {
1989 // Add back this substitution as an assertion
1990 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
1991 Node n
= NodeManager::currentNM()->mkNode(lhs
.getType().isBoolean() ? kind::IFF
: kind::EQUAL
, lhs
, rhs
);
1992 substitutionsBuilder
<< n
;
1993 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
1995 if (substitutionsBuilder
.getNumChildren() > 1) {
1996 d_assertions
.replace(d_substitutionsIndex
,
1997 Rewriter::rewrite(Node(substitutionsBuilder
)));
2000 // If not in incremental mode, must add substitutions to model
2001 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
2003 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
2004 Node n
= (*pos
).first
;
2005 Node v
= newSubstitutions
.apply((*pos
).second
);
2006 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
2007 m
->addSubstitution( n
, v
);
2012 NodeBuilder
<> learnedBuilder(kind::AND
);
2013 Assert(d_realAssertionsEnd
<= d_assertions
.size());
2014 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
2016 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
2017 Node learned
= d_nonClausalLearnedLiterals
[i
];
2018 Assert(d_topLevelSubstitutions
.apply(learned
) == learned
);
2019 Node learnedNew
= newSubstitutions
.apply(learned
);
2020 if (learned
!= learnedNew
) {
2021 learned
= Rewriter::rewrite(learnedNew
);
2023 Assert(Rewriter::rewrite(learned
) == learned
);
2025 learnedNew
= constantPropagations
.apply(learned
);
2026 if (learnedNew
== learned
) {
2029 ++d_smt
.d_stats
->d_numConstantProps
;
2030 learned
= Rewriter::rewrite(learnedNew
);
2032 if (s
.find(learned
) != s
.end()) {
2036 learnedBuilder
<< learned
;
2037 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2038 << "non-clausal learned : "
2041 d_nonClausalLearnedLiterals
.clear();
2043 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
2044 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
2045 Assert(d_topLevelSubstitutions
.apply(cProp
) == cProp
);
2046 Node cPropNew
= newSubstitutions
.apply(cProp
);
2047 if (cProp
!= cPropNew
) {
2048 cProp
= Rewriter::rewrite(cPropNew
);
2049 Assert(Rewriter::rewrite(cProp
) == cProp
);
2051 if (s
.find(cProp
) != s
.end()) {
2055 learnedBuilder
<< cProp
;
2056 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2057 << "non-clausal constant propagation : "
2061 // Add new substitutions to topLevelSubstitutions
2062 // Note that we don't have to keep rhs's in full solved form
2063 // because SubstitutionMap::apply does a fixed-point iteration when substituting
2064 d_topLevelSubstitutions
.addSubstitutions(newSubstitutions
);
2066 if(learnedBuilder
.getNumChildren() > 1) {
2067 d_assertions
.replace(d_realAssertionsEnd
- 1,
2068 Rewriter::rewrite(Node(learnedBuilder
)));
2071 d_propagatorNeedsFinish
= true;
2075 void SmtEnginePrivate::bvAbstraction() {
2076 Trace("bv-abstraction") << "SmtEnginePrivate::bvAbstraction()" << endl
;
2077 std::vector
<Node
> new_assertions
;
2078 bool changed
= d_smt
.d_theoryEngine
->ppBvAbstraction(d_assertions
.ref(), new_assertions
);
2079 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2080 d_assertions
.replace(i
, Rewriter::rewrite(new_assertions
[i
]));
2082 // if we are using the lazy solver and the abstraction
2083 // applies, then UF symbols were introduced
2084 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_LAZY
&&
2086 LogicRequest
req(d_smt
);
2087 req
.widenLogic(THEORY_UF
);
2092 void SmtEnginePrivate::bvToBool() {
2093 Trace("bv-to-bool") << "SmtEnginePrivate::bvToBool()" << endl
;
2094 std::vector
<Node
> new_assertions
;
2095 d_smt
.d_theoryEngine
->ppBvToBool(d_assertions
.ref(), new_assertions
);
2096 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2097 d_assertions
.replace(i
, Rewriter::rewrite(new_assertions
[i
]));
2101 bool SmtEnginePrivate::simpITE() {
2102 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
2104 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
2106 unsigned numAssertionOnEntry
= d_assertions
.size();
2107 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
2108 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
2109 d_assertions
.replace(i
, result
);
2110 if(result
.isConst() && !result
.getConst
<bool>()){
2114 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
2115 if(numAssertionOnEntry
< d_assertions
.size()){
2116 compressBeforeRealAssertions(numAssertionOnEntry
);
2121 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
2122 size_t curr
= d_assertions
.size();
2123 if(before
>= curr
||
2124 d_realAssertionsEnd
<= 0 ||
2125 d_realAssertionsEnd
>= curr
){
2130 // original: [0 ... d_realAssertionsEnd)
2132 // ites skolems [d_realAssertionsEnd, before)
2134 // added [before, curr)
2136 Assert(0 < d_realAssertionsEnd
);
2137 Assert(d_realAssertionsEnd
<= before
);
2138 Assert(before
< curr
);
2140 std::vector
<Node
> intoConjunction
;
2141 for(size_t i
= before
; i
<curr
; ++i
){
2142 intoConjunction
.push_back(d_assertions
[i
]);
2144 d_assertions
.resize(before
);
2145 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
2146 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
2147 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
2148 d_assertions
.replace(lastBeforeItes
, newLast
);
2149 Assert(d_assertions
.size() == before
);
2152 void SmtEnginePrivate::unconstrainedSimp() {
2153 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
2154 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
2155 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
2159 void SmtEnginePrivate::constrainSubtypes(TNode top
, AssertionPipeline
& assertions
)
2162 Trace("constrainSubtypes") << "constrainSubtypes(): looking at " << top
<< endl
;
2165 stack
<TNode
> worklist
;
2170 TNode n
= worklist
.top();
2173 TypeNode t
= n
.getType();
2174 if(t
.isPredicateSubtype()) {
2175 WarningOnce() << "Warning: CVC4 doesn't yet do checking that predicate subtypes are nonempty domains" << endl
;
2176 Node pred
= t
.getSubtypePredicate();
2178 // pred can be a LAMBDA, a function constant, or a datatype tester
2179 Trace("constrainSubtypes") << "constrainSubtypes(): pred.getType() == " << pred
.getType() << endl
;
2180 if(d_smt
.d_definedFunctions
->find(pred
) != d_smt
.d_definedFunctions
->end()) {
2182 } else if(pred
.getType().isTester()) {
2183 k
= kind::APPLY_TESTER
;
2187 Node app
= NodeManager::currentNM()->mkNode(k
, pred
, n
);
2188 Trace("constrainSubtypes") << "constrainSubtypes(): assert(" << k
<< ") " << app
<< endl
;
2189 assertions
.push_back(app
);
2190 } else if(t
.isSubrange()) {
2191 SubrangeBounds bounds
= t
.getSubrangeBounds();
2192 Trace("constrainSubtypes") << "constrainSubtypes(): got bounds " << bounds
<< endl
;
2193 if(bounds
.lower
.hasBound()) {
2194 Node c
= NodeManager::currentNM()->mkConst(Rational(bounds
.lower
.getBound()));
2195 Node lb
= NodeManager::currentNM()->mkNode(kind::LEQ
, c
, n
);
2196 Trace("constrainSubtypes") << "constrainSubtypes(): assert " << lb
<< endl
;
2197 assertions
.push_back(lb
);
2199 if(bounds
.upper
.hasBound()) {
2200 Node c
= NodeManager::currentNM()->mkConst(Rational(bounds
.upper
.getBound()));
2201 Node ub
= NodeManager::currentNM()->mkNode(kind::LEQ
, n
, c
);
2202 Trace("constrainSubtypes") << "constrainSubtypes(): assert " << ub
<< endl
;
2203 assertions
.push_back(ub
);
2207 for(TNode::iterator i
= n
.begin(); i
!= n
.end(); ++i
) {
2208 if(done
.find(*i
) == done
.end()) {
2213 } while(! worklist
.empty());
2216 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
2217 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
2218 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
2219 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
2220 // term must appear in map, otherwise how did we get here?!
2221 Assert(j
!= backEdges
.end());
2222 // if term maps to empty, that means it's a top-level assertion
2223 if(!(*j
).second
.empty()) {
2224 traceBackToAssertions((*j
).second
, assertions
);
2226 assertions
.push_back(*i
);
2231 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::hash_set
<unsigned long>& toRemove
) {
2232 Assert(n
.getKind() == kind::AND
);
2233 size_t removals
= 0;
2234 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
2235 size_t subremovals
= 0;
2237 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
2238 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
2239 NodeBuilder
<> b(kind::AND
);
2240 b
.append(n
.begin(), j
);
2241 if(subremovals
> 0) {
2242 removals
+= subremovals
;
2247 for(++j
; j
!= n
.end(); ++j
) {
2248 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
2250 } else if((*j
).getKind() == kind::AND
) {
2252 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
2253 removals
+= subremovals
;
2262 if(b
.getNumChildren() == 0) {
2265 } else if(b
.getNumChildren() == 1) {
2271 n
= Rewriter::rewrite(n
);
2276 Assert(removals
== 0);
2280 void SmtEnginePrivate::doMiplibTrick() {
2281 Assert(d_realAssertionsEnd
== d_assertions
.size());
2282 Assert(!options::incrementalSolving());
2284 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
2285 hash_set
<unsigned long> removeAssertions
;
2287 NodeManager
* nm
= NodeManager::currentNM();
2288 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
2290 hash_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
2291 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
2292 if(d_propagator
.isAssigned(*i
)) {
2293 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
2297 vector
<TNode
> assertions
;
2298 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
2299 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
2300 // if maps to an empty vector, that means the bool var was asserted itself.
2301 if(j
!= backEdges
.end()) {
2302 if(!(*j
).second
.empty()) {
2303 traceBackToAssertions((*j
).second
, assertions
);
2305 assertions
.push_back(*i
);
2308 Debug("miplib") << "for " << *i
<< endl
;
2309 bool eligible
= true;
2310 map
<pair
<Node
, Node
>, uint64_t> marks
;
2311 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
2312 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
2313 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
2314 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
2315 Debug("miplib") << " found: " << *j
<< endl
;
2316 if((*j
).getKind() != kind::IMPLIES
) {
2318 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
2321 Node conj
= BooleanSimplification::simplify((*j
)[0]);
2322 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
2324 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
2327 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
2329 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
2332 if((*j
)[1].getKind() != kind::EQUAL
||
2333 !( ( (*j
)[1][0].isVar() &&
2334 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
2335 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
2336 (*j
)[1][1].isVar() ) )) {
2338 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
2341 if(conj
.getKind() == kind::AND
) {
2343 bool found_x
= false;
2344 map
<TNode
, bool> neg
;
2345 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
2347 posv
.push_back(*ii
);
2349 found_x
= found_x
|| *i
== *ii
;
2350 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
2351 posv
.push_back((*ii
)[0]);
2352 neg
[(*ii
)[0]] = true;
2353 found_x
= found_x
|| *i
== (*ii
)[0];
2356 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
2359 if(d_propagator
.isAssigned(posv
.back())) {
2361 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
2370 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
2373 sort(posv
.begin(), posv
.end());
2374 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
2375 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
2376 const pair
<Node
, Node
> pos_var(pos
, var
);
2377 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
2379 unsigned countneg
= 0, thepos
= 0;
2380 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
2385 mark
|= (0x1 << ii
);
2388 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
2390 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
2393 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
2394 marks
[pos_var
] |= (1lu << mark
);
2395 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
2396 if(countneg
== pos
.getNumChildren()) {
2399 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
2402 } else if(countneg
== pos
.getNumChildren() - 1) {
2403 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
2404 if(coef
[pos_var
].size() <= thepos
) {
2405 coef
[pos_var
].resize(thepos
+ 1);
2407 coef
[pos_var
][thepos
] = constant
;
2409 if(checks
[pos_var
].size() <= mark
) {
2410 checks
[pos_var
].resize(mark
+ 1);
2412 checks
[pos_var
][mark
] = constant
;
2414 asserts
[pos_var
].push_back(*j
);
2417 if(x
!= *i
&& x
!= (*i
).notNode()) {
2419 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
2422 const bool xneg
= (x
.getKind() == kind::NOT
);
2423 x
= xneg
? x
[0] : x
;
2424 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
2425 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
2426 const pair
<Node
, Node
> x_var(x
, var
);
2427 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
2428 unsigned mark
= (xneg
? 0 : 1);
2429 if((marks
[x_var
] & (1u << mark
)) != 0) {
2431 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
2434 marks
[x_var
] |= (1u << mark
);
2438 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
2442 Assert(coef
[x_var
].size() <= 6);
2443 coef
[x_var
].resize(6);
2444 coef
[x_var
][0] = constant
;
2446 asserts
[x_var
].push_back(*j
);
2450 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
2451 const TNode pos
= (*j
).first
.first
;
2452 const TNode var
= (*j
).first
.second
;
2453 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
2454 const uint64_t mark
= (*j
).second
;
2455 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
2456 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
2457 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
2458 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
2459 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
2460 if(mark
!= expected
) {
2461 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
2463 if(mark
!= 3) { // exclude single-var case; nothing to check there
2464 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
2465 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
2466 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
2467 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
2468 if((k
& (k
- 1)) != 0) {
2470 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
2471 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
2472 if((kk
& 0x1) == 1) {
2473 Assert(pos
.getKind() == kind::AND
);
2474 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
2475 sum
+= coef
[pos_var
][v
- 1];
2478 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
2479 if(sum
!= checks
[pos_var
][k
]) {
2481 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
2485 Assert(checks
[pos_var
][k
] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos
.toString().c_str(), var
.toString().c_str(), k
, checks
[pos_var
][k
].toString().c_str()); // we never set for single-positive-var
2490 eligible
= true; // next is still eligible
2494 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
2495 vector
<Node
> newVars
;
2496 expr::NodeSelfIterator ii
, iiend
;
2497 if(pos
.getKind() == kind::AND
) {
2501 ii
= expr::NodeSelfIterator::self(pos
);
2502 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
2504 for(; ii
!= iiend
; ++ii
) {
2505 Node
& varRef
= intVars
[*ii
];
2506 if(varRef
.isNull()) {
2508 ss
<< "mipvar_" << *ii
;
2509 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
2510 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
2511 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
2512 d_assertions
.push_back(Rewriter::rewrite(geq
.andNode(leq
)));
2513 SubstitutionMap
nullMap(&d_fakeContext
);
2514 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
2515 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
2516 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
2517 "unexpected solution from arith's ppAssert()");
2518 Assert(nullMap
.empty(),
2519 "unexpected substitution from arith's ppAssert()");
2520 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
2521 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
2522 "unexpected solution from arith's ppAssert()");
2523 Assert(nullMap
.empty(),
2524 "unexpected substitution from arith's ppAssert()");
2525 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
2526 newVars
.push_back(newVar
);
2529 newVars
.push_back(varRef
);
2531 if(!d_smt
.d_logic
.areIntegersUsed()) {
2532 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
2533 d_smt
.d_logic
.enableIntegers();
2534 d_smt
.d_logic
.lock();
2538 if(pos
.getKind() == kind::AND
) {
2539 NodeBuilder
<> sumb(kind::PLUS
);
2540 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
2541 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
2545 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
2547 Debug("miplib") << "vars[] " << var
<< endl
2548 << " eq " << Rewriter::rewrite(sum
) << endl
;
2549 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
2550 if(d_topLevelSubstitutions
.hasSubstitution(newAssertion
[0])) {
2551 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
2552 //Warning() << "REPLACE " << newAssertion[1] << endl;
2553 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
2554 Assert(d_topLevelSubstitutions
.getSubstitution(newAssertion
[0]) == newAssertion
[1]);
2555 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
2556 d_topLevelSubstitutions
.addSubstitution(newAssertion
[0], newAssertion
[1]);
2557 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
2559 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
2561 newAssertion
= Rewriter::rewrite(newAssertion
);
2562 Debug("miplib") << " " << newAssertion
<< endl
;
2563 d_assertions
.push_back(newAssertion
);
2564 Debug("miplib") << " assertions to remove: " << endl
;
2565 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
2566 Debug("miplib") << " " << *k
<< endl
;
2567 removeAssertions
.insert((*k
).getId());
2573 if(!removeAssertions
.empty()) {
2574 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
2575 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
2576 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
2577 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
2578 d_assertions
[i
] = d_true
;
2579 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
2580 } else if(d_assertions
[i
].getKind() == kind::AND
) {
2581 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
2583 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
2584 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
2585 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
2588 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
2589 d_assertions
[i
] = Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
]));
2590 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
2593 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
2595 d_realAssertionsEnd
= d_assertions
.size();
2599 // returns false if simplification led to "false"
2600 bool SmtEnginePrivate::simplifyAssertions()
2601 throw(TypeCheckingException
, LogicException
) {
2602 Assert(d_smt
.d_pendingPops
== 0);
2604 ScopeCounter
depth(d_simplifyAssertionsDepth
);
2606 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
2608 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
2609 // Perform non-clausal simplification
2610 Chat() << "...performing nonclausal simplification..." << endl
;
2611 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2612 << "performing non-clausal simplification" << endl
;
2613 bool noConflict
= nonClausalSimplify();
2618 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
2619 // do the miplib trick.
2620 if( // check that option is on
2621 options::arithMLTrick() &&
2622 // miplib rewrites aren't safe in incremental mode
2623 ! options::incrementalSolving() &&
2624 // only useful in arith
2625 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
2626 // we add new assertions and need this (in practice, this
2627 // restriction only disables miplib processing during
2628 // re-simplification, which we don't expect to be useful anyway)
2629 d_realAssertionsEnd
== d_assertions
.size() ) {
2630 Chat() << "...fixing miplib encodings..." << endl
;
2631 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2632 << "looking for miplib pseudobooleans..." << endl
;
2634 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
2638 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2639 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
2643 dumpAssertions("post-nonclausal", d_assertions
);
2644 Trace("smt") << "POST nonClausalSimplify" << endl
;
2645 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2647 // before ppRewrite check if only core theory for BV theory
2648 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
2650 dumpAssertions("pre-theorypp", d_assertions
);
2652 // Theory preprocessing
2653 if (d_smt
.d_earlyTheoryPP
) {
2654 Chat() << "...doing early theory preprocessing..." << endl
;
2655 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
2656 // Call the theory preprocessors
2657 d_smt
.d_theoryEngine
->preprocessStart();
2658 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2659 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
2660 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
2661 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
2665 dumpAssertions("post-theorypp", d_assertions
);
2666 Trace("smt") << "POST theoryPP" << endl
;
2667 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2669 // ITE simplification
2670 if(options::doITESimp() &&
2671 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
2672 Chat() << "...doing ITE simplification..." << endl
;
2673 bool noConflict
= simpITE();
2675 Chat() << "...ITE simplification found unsat..." << endl
;
2680 dumpAssertions("post-itesimp", d_assertions
);
2681 Trace("smt") << "POST iteSimp" << endl
;
2682 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2684 // Unconstrained simplification
2685 if(options::unconstrainedSimp()) {
2686 Chat() << "...doing unconstrained simplification..." << endl
;
2687 unconstrainedSimp();
2690 dumpAssertions("post-unconstrained", d_assertions
);
2691 Trace("smt") << "POST unconstrainedSimp" << endl
;
2692 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2694 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
2695 Chat() << "...doing another round of nonclausal simplification..." << endl
;
2696 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2697 << " doing repeated simplification" << endl
;
2698 bool noConflict
= nonClausalSimplify();
2704 dumpAssertions("post-repeatsimp", d_assertions
);
2705 Trace("smt") << "POST repeatSimp" << endl
;
2706 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2708 } catch(TypeCheckingExceptionPrivate
& tcep
) {
2709 // Calls to this function should have already weeded out any
2710 // typechecking exceptions via (e.g.) ensureBoolean(). But a
2711 // theory could still create a new expression that isn't
2712 // well-typed, and we don't want the C++ runtime to abort our
2713 // process without any error notice.
2715 ss
<< "A bad expression was produced. Original exception follows:\n"
2717 InternalError(ss
.str().c_str());
2722 Result
SmtEngine::check() {
2723 Assert(d_fullyInited
);
2724 Assert(d_pendingPops
== 0);
2726 Trace("smt") << "SmtEngine::check()" << endl
;
2728 // Make sure the prop layer has all of the assertions
2729 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
2730 d_private
->processAssertions();
2732 // Turn off stop only for QF_LRA
2733 // TODO: Bring up in a meeting where to put this
2734 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
2736 (not d_logic
.isQuantified() &&
2737 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
2739 if(d_private
->d_iteSkolemMap
.empty()){
2740 options::decisionStopOnly
.set(false);
2741 d_decisionEngine
->clearStrategies();
2742 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
2747 unsigned long millis
= 0;
2748 if(d_timeBudgetCumulative
!= 0) {
2749 millis
= getTimeRemaining();
2751 return Result(Result::VALIDITY_UNKNOWN
, Result::TIMEOUT
, d_filename
);
2754 if(d_timeBudgetPerCall
!= 0 && (millis
== 0 || d_timeBudgetPerCall
< millis
)) {
2755 millis
= d_timeBudgetPerCall
;
2758 unsigned long resource
= 0;
2759 if(d_resourceBudgetCumulative
!= 0) {
2760 resource
= getResourceRemaining();
2762 return Result(Result::VALIDITY_UNKNOWN
, Result::RESOURCEOUT
, d_filename
);
2765 if(d_resourceBudgetPerCall
!= 0 && (resource
== 0 || d_resourceBudgetPerCall
< resource
)) {
2766 resource
= d_resourceBudgetPerCall
;
2769 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
2771 Chat() << "solving..." << endl
;
2772 Trace("smt") << "SmtEngine::check(): running check" << endl
;
2773 Result result
= d_propEngine
->checkSat(millis
, resource
);
2775 // PropEngine::checkSat() returns the actual amount used in these
2777 d_cumulativeTimeUsed
+= millis
;
2778 d_cumulativeResourceUsed
+= resource
;
2780 Trace("limit") << "SmtEngine::check(): cumulative millis " << d_cumulativeTimeUsed
2781 << ", conflicts " << d_cumulativeResourceUsed
<< endl
;
2783 return Result(result
, d_filename
);
2786 Result
SmtEngine::quickCheck() {
2787 Assert(d_fullyInited
);
2788 Trace("smt") << "SMT quickCheck()" << endl
;
2789 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
2793 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, hash_map
<Node
, bool, NodeHashFunction
>& cache
)
2795 hash_map
<Node
, bool, NodeHashFunction
>::iterator it
;
2797 if (it
!= cache
.end()) {
2801 size_t sz
= n
.getNumChildren();
2803 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
2804 if (it
!= d_iteSkolemMap
.end()) {
2805 skolemSet
.insert(n
);
2812 for (; k
< sz
; ++k
) {
2813 collectSkolems(n
[k
], skolemSet
, cache
);
2819 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, hash_map
<Node
, bool, NodeHashFunction
>& cache
)
2821 hash_map
<Node
, bool, NodeHashFunction
>::iterator it
;
2823 if (it
!= cache
.end()) {
2824 return (*it
).second
;
2827 size_t sz
= n
.getNumChildren();
2829 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
2831 if (it
!= d_iteSkolemMap
.end()) {
2832 if (!((*it
).first
< n
)) {
2841 for (; k
< sz
; ++k
) {
2842 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
2852 Node
SmtEnginePrivate::rewriteBooleanTerms(TNode n
) {
2853 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteBooleanTermsTime
);
2854 if(d_booleanTermConverter
== NULL
) {
2855 // This needs to be initialized _after_ the whole SMT framework is in place, subscribed
2856 // to ExprManager notifications, etc. Otherwise we might miss the "BooleanTerm" datatype
2857 // definition, and not dump it properly.
2858 d_booleanTermConverter
= new BooleanTermConverter(d_smt
);
2860 Node retval
= d_booleanTermConverter
->rewriteBooleanTerms(n
);
2862 switch(booleans::BooleanTermConversionMode mode
= options::booleanTermConversionMode()) {
2863 case booleans::BOOLEAN_TERM_CONVERT_TO_BITVECTORS
:
2864 case booleans::BOOLEAN_TERM_CONVERT_NATIVE
:
2865 if(!d_smt
.d_logic
.isTheoryEnabled(THEORY_BV
)) {
2866 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
2867 d_smt
.d_logic
.enableTheory(THEORY_BV
);
2868 d_smt
.d_logic
.lock();
2871 case booleans::BOOLEAN_TERM_CONVERT_TO_DATATYPES
:
2872 if(!d_smt
.d_logic
.isTheoryEnabled(THEORY_DATATYPES
)) {
2873 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
2874 d_smt
.d_logic
.enableTheory(THEORY_DATATYPES
);
2875 d_smt
.d_logic
.lock();
2885 void SmtEnginePrivate::processAssertions() {
2886 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
2888 Assert(d_smt
.d_fullyInited
);
2889 Assert(d_smt
.d_pendingPops
== 0);
2891 // Dump the assertions
2892 dumpAssertions("pre-everything", d_assertions
);
2894 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
2896 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2898 if (d_assertions
.size() == 0) {
2903 if (d_assertionsProcessed
&& options::incrementalSolving()) {
2904 // Placeholder for storing substitutions
2905 d_substitutionsIndex
= d_assertions
.size();
2906 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
2909 // Add dummy assertion in last position - to be used as a
2910 // placeholder for any new assertions to get added
2911 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
2912 // any assertions added beyond realAssertionsEnd must NOT affect the
2913 // equisatisfiability
2914 d_realAssertionsEnd
= d_assertions
.size();
2916 // Assertions are NOT guaranteed to be rewritten by this point
2918 dumpAssertions("pre-definition-expansion", d_assertions
);
2920 Chat() << "expanding definitions..." << endl
;
2921 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
2922 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
2923 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
2924 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2925 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
2928 dumpAssertions("post-definition-expansion", d_assertions
);
2930 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2932 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
2933 !d_smt
.d_logic
.isPure(THEORY_BV
)) {
2934 throw ModalException("Eager bit-blasting does not currently support theory combination. "
2935 "Note that in a QF_BV problem UF symbols can be introduced for division. "
2936 "Try --bv-div-zero-const to interpret division by zero as a constant.");
2939 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
2940 d_smt
.d_theoryEngine
->mkAckermanizationAsssertions(d_assertions
.ref());
2943 if ( options::bvAbstraction() &&
2944 !options::incrementalSolving()) {
2945 dumpAssertions("pre-bv-abstraction", d_assertions
);
2947 dumpAssertions("post-bv-abstraction", d_assertions
);
2950 dumpAssertions("pre-boolean-terms", d_assertions
);
2952 Chat() << "rewriting Boolean terms..." << endl
;
2953 for(unsigned i
= 0, i_end
= d_assertions
.size(); i
!= i_end
; ++i
) {
2954 d_assertions
.replace(i
, rewriteBooleanTerms(d_assertions
[i
]));
2957 dumpAssertions("post-boolean-terms", d_assertions
);
2959 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2961 dumpAssertions("pre-constrain-subtypes", d_assertions
);
2963 // Any variables of subtype types need to be constrained properly.
2964 // Careful, here: constrainSubtypes() adds to the back of
2965 // d_assertions, but we don't need to reprocess those.
2966 // We also can't use an iterator, because the vector may be moved in
2967 // memory during this loop.
2968 Chat() << "constraining subtypes..." << endl
;
2969 for(unsigned i
= 0, i_end
= d_assertions
.size(); i
!= i_end
; ++i
) {
2970 constrainSubtypes(d_assertions
[i
], d_assertions
);
2973 dumpAssertions("post-constrain-subtypes", d_assertions
);
2975 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2977 bool noConflict
= true;
2979 // Unconstrained simplification
2980 if(options::unconstrainedSimp()) {
2981 dumpAssertions("pre-unconstrained-simp", d_assertions
);
2982 Chat() << "...doing unconstrained simplification..." << endl
;
2983 unconstrainedSimp();
2984 dumpAssertions("post-unconstrained-simp", d_assertions
);
2987 if(options::bvIntroducePow2()){
2988 theory::bv::BVIntroducePow2::pow2Rewrite(d_assertions
.ref());
2991 dumpAssertions("pre-substitution", d_assertions
);
2993 if(options::unsatCores()) {
2994 // special rewriting pass for unsat cores, since many of the passes below are skipped
2995 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2996 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
2999 // Apply the substitutions we already have, and normalize
3000 if(!options::unsatCores()) {
3001 Chat() << "applying substitutions..." << endl
;
3002 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3003 << "applying substitutions" << endl
;
3004 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3005 Trace("simplify") << "applying to " << d_assertions
[i
] << endl
;
3006 d_assertions
.replace(i
, Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
])));
3007 Trace("simplify") << " got " << d_assertions
[i
] << endl
;
3012 dumpAssertions("post-substitution", d_assertions
);
3014 // Assertions ARE guaranteed to be rewritten by this point
3016 // Lift bit-vectors of size 1 to bool
3017 if(options::bitvectorToBool()) {
3018 dumpAssertions("pre-bv-to-bool", d_assertions
);
3019 Chat() << "...doing bvToBool..." << endl
;
3021 dumpAssertions("post-bv-to-bool", d_assertions
);
3024 if( d_smt
.d_logic
.isTheoryEnabled(THEORY_STRINGS
) ) {
3025 dumpAssertions("pre-strings-pp", d_assertions
);
3026 CVC4::theory::strings::StringsPreprocess sp
;
3027 std::vector
<Node
> newNodes
;
3028 newNodes
.push_back(d_assertions
[d_realAssertionsEnd
- 1]);
3029 sp
.simplify( d_assertions
.ref(), newNodes
);
3030 if(newNodes
.size() > 1) {
3031 d_assertions
[d_realAssertionsEnd
- 1] = NodeManager::currentNM()->mkNode(kind::AND
, newNodes
);
3033 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3034 d_assertions
[i
] = Rewriter::rewrite( d_assertions
[i
] );
3036 dumpAssertions("post-strings-pp", d_assertions
);
3038 if( d_smt
.d_logic
.isQuantified() ){
3039 //remove rewrite rules
3040 for( unsigned i
=0; i
< d_assertions
.size(); i
++ ) {
3041 if( d_assertions
[i
].getKind() == kind::REWRITE_RULE
){
3042 Node prev
= d_assertions
[i
];
3043 Trace("quantifiers-rewrite-debug") << "Rewrite rewrite rule " << prev
<< "..." << std::endl
;
3044 d_assertions
[i
] = Rewriter::rewrite( quantifiers::QuantifiersRewriter::rewriteRewriteRule( d_assertions
[i
] ) );
3045 Trace("quantifiers-rewrite") << "*** rr-rewrite " << prev
<< endl
;
3046 Trace("quantifiers-rewrite") << " ...got " << d_assertions
[i
] << endl
;
3050 dumpAssertions("pre-skolem-quant", d_assertions
);
3051 if( options::preSkolemQuant() ){
3052 //apply pre-skolemization to existential quantifiers
3053 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3054 Node prev
= d_assertions
[i
];
3055 Trace("quantifiers-rewrite-debug") << "Pre-skolemize " << prev
<< "..." << std::endl
;
3056 vector
< TypeNode
> fvTypes
;
3057 vector
< TNode
> fvs
;
3058 d_assertions
.replace(i
, quantifiers::QuantifiersRewriter::preSkolemizeQuantifiers( prev
, true, fvTypes
, fvs
));
3059 if( prev
!=d_assertions
[i
] ){
3060 d_assertions
.replace(i
, Rewriter::rewrite( d_assertions
[i
] ));
3061 Trace("quantifiers-rewrite") << "*** Pre-skolemize " << prev
<< endl
;
3062 Trace("quantifiers-rewrite") << " ...got " << d_assertions
[i
] << endl
;
3066 dumpAssertions("post-skolem-quant", d_assertions
);
3067 if( options::macrosQuant() ){
3068 //quantifiers macro expansion
3071 quantifiers::QuantifierMacros qm
;
3072 success
= qm
.simplify( d_assertions
.ref(), true );
3076 Trace("fo-rsn-enable") << std::endl
;
3077 if( options::foPropQuant() ){
3078 quantifiers::FirstOrderPropagation fop
;
3079 fop
.simplify( d_assertions
.ref() );
3083 if( options::sortInference() ){
3084 //sort inference technique
3085 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
3086 si
->simplify( d_assertions
.ref() );
3087 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
3088 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
3089 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
3093 //if( options::quantConflictFind() ){
3094 // d_smt.d_theoryEngine->getQuantConflictFind()->registerAssertions( d_assertions );
3097 if( options::pbRewrites() ){
3098 d_pbsProcessor
.learn(d_assertions
.ref());
3099 if(d_pbsProcessor
.likelyToHelp()){
3100 d_pbsProcessor
.applyReplacements(d_assertions
.ref());
3104 dumpAssertions("pre-simplify", d_assertions
);
3105 Chat() << "simplifying assertions..." << endl
;
3106 noConflict
= simplifyAssertions();
3108 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
3110 dumpAssertions("post-simplify", d_assertions
);
3112 dumpAssertions("pre-static-learning", d_assertions
);
3113 if(options::doStaticLearning()) {
3114 // Perform static learning
3115 Chat() << "doing static learning..." << endl
;
3116 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3117 << "performing static learning" << endl
;
3120 dumpAssertions("post-static-learning", d_assertions
);
3122 Trace("smt") << "POST bvToBool" << endl
;
3123 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3126 dumpAssertions("pre-ite-removal", d_assertions
);
3128 Chat() << "removing term ITEs..." << endl
;
3129 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
3130 // Remove ITEs, updating d_iteSkolemMap
3131 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
3133 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
3135 dumpAssertions("post-ite-removal", d_assertions
);
3137 dumpAssertions("pre-repeat-simplify", d_assertions
);
3138 if(options::repeatSimp()) {
3139 Chat() << "re-simplifying assertions..." << endl
;
3140 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3141 noConflict
&= simplifyAssertions();
3143 // Need to fix up assertion list to maintain invariants:
3144 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
3145 // during ite removal.
3146 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
3148 // cache for expression traversal
3149 hash_map
<Node
, bool, NodeHashFunction
> cache
;
3151 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
3152 // to be moved to the main assertion set
3153 set
<TNode
> skolemSet
;
3154 SubstitutionMap::iterator pos
= d_topLevelSubstitutions
.begin();
3155 for (; pos
!= d_topLevelSubstitutions
.end(); ++pos
) {
3156 collectSkolems((*pos
).first
, skolemSet
, cache
);
3157 collectSkolems((*pos
).second
, skolemSet
, cache
);
3160 // We need to ensure:
3161 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
3162 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
3163 // If either of these is violated, we must add iteExpr as a proper assertion
3164 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
3165 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
3166 NodeBuilder
<> builder(kind::AND
);
3167 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
3168 vector
<TNode
> toErase
;
3169 for (; it
!= iend
; ++it
) {
3170 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
3171 TNode iteExpr
= d_assertions
[(*it
).second
];
3172 if (iteExpr
.getKind() == kind::ITE
&&
3173 iteExpr
[1].getKind() == kind::EQUAL
&&
3174 iteExpr
[1][0] == (*it
).first
&&
3175 iteExpr
[2].getKind() == kind::EQUAL
&&
3176 iteExpr
[2][0] == (*it
).first
) {
3178 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
3179 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
3180 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
3186 // Move this iteExpr into the main assertions
3187 builder
<< d_assertions
[(*it
).second
];
3188 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
3189 toErase
.push_back((*it
).first
);
3191 if(builder
.getNumChildren() > 1) {
3192 while (!toErase
.empty()) {
3193 d_iteSkolemMap
.erase(toErase
.back());
3196 d_assertions
[d_realAssertionsEnd
- 1] =
3197 Rewriter::rewrite(Node(builder
));
3199 // For some reason this is needed for some benchmarks, such as
3200 // http://cvc4.cs.nyu.edu/benchmarks/smtlib2/QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
3201 // Figure it out later
3203 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
3206 dumpAssertions("post-repeat-simplify", d_assertions
);
3208 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
3209 if(options::rewriteApplyToConst()) {
3210 Chat() << "Rewriting applies to constants..." << endl
;
3211 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
3212 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3213 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
3216 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
3218 // begin: INVARIANT to maintain: no reordering of assertions or
3219 // introducing new ones
3220 #ifdef CVC4_ASSERTIONS
3221 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
3224 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3226 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
3227 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3229 dumpAssertions("pre-theory-preprocessing", d_assertions
);
3231 Chat() << "theory preprocessing..." << endl
;
3232 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3233 // Call the theory preprocessors
3234 d_smt
.d_theoryEngine
->preprocessStart();
3235 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3236 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3239 dumpAssertions("post-theory-preprocessing", d_assertions
);
3241 // If we are using eager bit-blasting wrap assertions in fake atom so that
3242 // everything gets bit-blasted to internal SAT solver
3243 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
3244 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3245 TNode atom
= d_assertions
[i
];
3246 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
3247 d_assertions
.replace(i
, eager_atom
);
3248 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3249 m
->addSubstitution(eager_atom
, atom
);
3253 // Push the formula to decision engine
3255 Chat() << "pushing to decision engine..." << endl
;
3256 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
3257 d_smt
.d_decisionEngine
->addAssertions
3258 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
3261 // end: INVARIANT to maintain: no reordering of assertions or
3262 // introducing new ones
3264 dumpAssertions("post-everything", d_assertions
);
3266 //set instantiation level of everything to zero
3267 if( options::instLevelInputOnly() && options::instMaxLevel()!=-1 ){
3268 for( unsigned i
=0; i
< d_assertions
.size(); i
++ ) {
3269 theory::QuantifiersEngine::setInstantiationLevelAttr( d_assertions
[i
], 0 );
3273 // Push the formula to SAT
3275 Chat() << "converting to CNF..." << endl
;
3276 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
3277 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3278 Chat() << "+ " << d_assertions
[i
] << std::endl
;
3279 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
3283 d_assertionsProcessed
= true;
3285 d_assertions
.clear();
3286 d_iteSkolemMap
.clear();
3289 void SmtEnginePrivate::addFormula(TNode n
)
3290 throw(TypeCheckingException
, LogicException
) {
3297 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< ")" << endl
;
3299 // Add the normalized formula to the queue
3300 d_assertions
.push_back(n
);
3301 //d_assertions.push_back(Rewriter::rewrite(n));
3304 void SmtEngine::ensureBoolean(const Expr
& e
) throw(TypeCheckingException
) {
3305 Type type
= e
.getType(options::typeChecking());
3306 Type boolType
= d_exprManager
->booleanType();
3307 if(type
!= boolType
) {
3309 ss
<< "Expected " << boolType
<< "\n"
3310 << "The assertion : " << e
<< "\n"
3311 << "Its type : " << type
;
3312 throw TypeCheckingException(e
, ss
.str());
3316 Result
SmtEngine::checkSat(const Expr
& ex
, bool inUnsatCore
) throw(TypeCheckingException
, ModalException
, LogicException
) {
3317 Assert(ex
.isNull() || ex
.getExprManager() == d_exprManager
);
3318 SmtScope
smts(this);
3319 finalOptionsAreSet();
3322 Trace("smt") << "SmtEngine::checkSat(" << ex
<< ")" << endl
;
3324 if(d_queryMade
&& !options::incrementalSolving()) {
3325 throw ModalException("Cannot make multiple queries unless "
3326 "incremental solving is enabled "
3327 "(try --incremental)");
3332 // Substitute out any abstract values in ex.
3333 e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3334 // Ensure expr is type-checked at this point.
3336 // Give it to proof manager
3337 PROOF( ProofManager::currentPM()->addAssertion(e
, inUnsatCore
); );
3340 // check to see if a postsolve() is pending
3341 if(d_needPostsolve
) {
3342 d_theoryEngine
->postsolve();
3343 d_needPostsolve
= false;
3349 // Note that a query has been made
3354 d_problemExtended
= true;
3355 if(d_assertionList
!= NULL
) {
3356 d_assertionList
->push_back(e
);
3358 d_private
->addFormula(e
.getNode());
3362 Result r
= check().asSatisfiabilityResult();
3363 d_needPostsolve
= true;
3365 // Dump the query if requested
3366 if(Dump
.isOn("benchmark")) {
3367 // the expr already got dumped out if assertion-dumping is on
3368 Dump("benchmark") << CheckSatCommand();
3374 // Remember the status
3377 d_problemExtended
= false;
3379 Trace("smt") << "SmtEngine::checkSat(" << e
<< ") => " << r
<< endl
;
3381 // Check that SAT results generate a model correctly.
3382 if(options::checkModels()) {
3383 if(r
.asSatisfiabilityResult().isSat() == Result::SAT
||
3384 (r
.isUnknown() && r
.whyUnknown() == Result::INCOMPLETE
) ){
3385 checkModel(/* hard failure iff */ ! r
.isUnknown());
3388 // Check that UNSAT results generate a proof correctly.
3389 if(options::checkProofs()) {
3390 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
3391 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
3397 }/* SmtEngine::checkSat() */
3399 Result
SmtEngine::query(const Expr
& ex
, bool inUnsatCore
) throw(TypeCheckingException
, ModalException
, LogicException
) {
3400 Assert(!ex
.isNull());
3401 Assert(ex
.getExprManager() == d_exprManager
);
3402 SmtScope
smts(this);
3403 finalOptionsAreSet();
3405 Trace("smt") << "SMT query(" << ex
<< ")" << endl
;
3407 if(d_queryMade
&& !options::incrementalSolving()) {
3408 throw ModalException("Cannot make multiple queries unless "
3409 "incremental solving is enabled "
3410 "(try --incremental)");
3413 // Substitute out any abstract values in ex
3414 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3415 // Ensure that the expression is type-checked at this point, and Boolean
3417 // Give it to proof manager
3418 PROOF( ProofManager::currentPM()->addAssertion(e
.notExpr(), inUnsatCore
); );
3420 // check to see if a postsolve() is pending
3421 if(d_needPostsolve
) {
3422 d_theoryEngine
->postsolve();
3423 d_needPostsolve
= false;
3429 // Note that a query has been made
3433 d_problemExtended
= true;
3434 if(d_assertionList
!= NULL
) {
3435 d_assertionList
->push_back(e
.notExpr());
3437 d_private
->addFormula(e
.getNode().notNode());
3440 Result r
= check().asValidityResult();
3441 d_needPostsolve
= true;
3443 // Dump the query if requested
3444 if(Dump
.isOn("benchmark")) {
3445 // the expr already got dumped out if assertion-dumping is on
3446 Dump("benchmark") << CheckSatCommand();
3452 // Remember the status
3455 d_problemExtended
= false;
3457 Trace("smt") << "SMT query(" << e
<< ") ==> " << r
<< endl
;
3459 // Check that SAT results generate a model correctly.
3460 if(options::checkModels()) {
3461 if(r
.asSatisfiabilityResult().isSat() == Result::SAT
||
3462 (r
.isUnknown() && r
.whyUnknown() == Result::INCOMPLETE
) ){
3463 checkModel(/* hard failure iff */ ! r
.isUnknown());
3466 // Check that UNSAT results generate a proof correctly.
3467 if(options::checkProofs()) {
3468 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
3469 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
3475 }/* SmtEngine::query() */
3477 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
) throw(TypeCheckingException
, LogicException
) {
3478 Assert(ex
.getExprManager() == d_exprManager
);
3479 SmtScope
smts(this);
3480 finalOptionsAreSet();
3483 PROOF( ProofManager::currentPM()->addAssertion(ex
, inUnsatCore
); );
3485 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
3487 // Substitute out any abstract values in ex
3488 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3491 if(d_assertionList
!= NULL
) {
3492 d_assertionList
->push_back(e
);
3494 d_private
->addFormula(e
.getNode());
3495 return quickCheck().asValidityResult();
3496 }/* SmtEngine::assertFormula() */
3498 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
3499 ModelPostprocessor mpost
;
3500 NodeVisitor
<ModelPostprocessor
> visitor
;
3501 Node value
= visitor
.run(mpost
, node
);
3502 Debug("boolean-terms") << "postproc: got " << value
<< " expect type " << expectedType
<< endl
;
3503 Node realValue
= mpost
.rewriteAs(value
, expectedType
);
3504 Debug("boolean-terms") << "postproc: realval " << realValue
<< " expect type " << expectedType
<< endl
;
3508 Expr
SmtEngine::simplify(const Expr
& ex
) throw(TypeCheckingException
, LogicException
) {
3509 Assert(ex
.getExprManager() == d_exprManager
);
3510 SmtScope
smts(this);
3511 finalOptionsAreSet();
3513 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
3515 if(Dump
.isOn("benchmark")) {
3516 Dump("benchmark") << SimplifyCommand(ex
);
3519 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3520 if( options::typeChecking() ) {
3521 e
.getType(true); // ensure expr is type-checked at this point
3524 // Make sure all preprocessing is done
3525 d_private
->processAssertions();
3526 Node n
= d_private
->simplify(Node::fromExpr(e
));
3527 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
3531 Expr
SmtEngine::expandDefinitions(const Expr
& ex
) throw(TypeCheckingException
, LogicException
) {
3532 Assert(ex
.getExprManager() == d_exprManager
);
3533 SmtScope
smts(this);
3534 finalOptionsAreSet();
3536 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
3538 // Substitute out any abstract values in ex.
3539 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3540 if(options::typeChecking()) {
3541 // Ensure expr is type-checked at this point.
3544 if(Dump
.isOn("benchmark")) {
3545 Dump("benchmark") << ExpandDefinitionsCommand(e
);
3547 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
3548 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
3549 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
3554 Expr
SmtEngine::getValue(const Expr
& ex
) const throw(ModalException
, TypeCheckingException
, LogicException
) {
3555 Assert(ex
.getExprManager() == d_exprManager
);
3556 SmtScope
smts(this);
3558 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
3559 if(Dump
.isOn("benchmark")) {
3560 Dump("benchmark") << GetValueCommand(ex
);
3563 if(!options::produceModels()) {
3565 "Cannot get value when produce-models options is off.";
3566 throw ModalException(msg
);
3568 if(d_status
.isNull() ||
3569 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3570 d_problemExtended
) {
3572 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
3573 throw ModalException(msg
);
3576 // Substitute out any abstract values in ex.
3577 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3579 // Ensure expr is type-checked at this point.
3580 e
.getType(options::typeChecking());
3582 // do not need to apply preprocessing substitutions (should be recorded
3583 // in model already)
3585 Node n
= Node::fromExpr(e
);
3586 Trace("smt") << "--- getting value of " << n
<< endl
;
3587 TypeNode expectedType
= n
.getType();
3589 // Expand, then normalize
3590 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
3591 n
= d_private
->expandDefinitions(n
, cache
);
3592 // There are two ways model values for terms are computed (for historical
3593 // reasons). One way is that used in check-model; the other is that
3594 // used by the Model classes. It's not clear to me exactly how these
3595 // two are different, but they need to be unified. This ugly hack here
3596 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
3597 if(!n
.getType().isFunction()) {
3598 n
= d_private
->rewriteBooleanTerms(n
);
3599 n
= Rewriter::rewrite(n
);
3602 Trace("smt") << "--- getting value of " << n
<< endl
;
3603 TheoryModel
* m
= d_theoryEngine
->getModel();
3606 resultNode
= m
->getValue(n
);
3608 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
3609 resultNode
= postprocess(resultNode
, expectedType
);
3610 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
3611 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
3612 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
3614 // type-check the result we got
3615 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
3616 "Run with -t smt for details.");
3618 // ensure it's a constant
3619 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
3621 if(options::abstractValues() && resultNode
.getType().isArray()) {
3622 resultNode
= d_private
->mkAbstractValue(resultNode
);
3625 return resultNode
.toExpr();
3628 bool SmtEngine::addToAssignment(const Expr
& ex
) throw() {
3629 SmtScope
smts(this);
3630 finalOptionsAreSet();
3632 // Substitute out any abstract values in ex
3633 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3634 Type type
= e
.getType(options::typeChecking());
3636 CheckArgument( type
.isBoolean(), e
,
3637 "expected Boolean-typed variable or function application "
3638 "in addToAssignment()" );
3639 Node n
= e
.getNode();
3640 // must be an APPLY of a zero-ary defined function, or a variable
3641 CheckArgument( ( ( n
.getKind() == kind::APPLY
&&
3642 ( d_definedFunctions
->find(n
.getOperator()) !=
3643 d_definedFunctions
->end() ) &&
3644 n
.getNumChildren() == 0 ) ||
3646 "expected variable or defined-function application "
3647 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
3648 if(!options::produceAssignments()) {
3651 if(d_assignments
== NULL
) {
3652 d_assignments
= new(true) AssignmentSet(d_context
);
3654 d_assignments
->insert(n
);
3659 CVC4::SExpr
SmtEngine::getAssignment() throw(ModalException
) {
3660 Trace("smt") << "SMT getAssignment()" << endl
;
3661 SmtScope
smts(this);
3662 finalOptionsAreSet();
3663 if(Dump
.isOn("benchmark")) {
3664 Dump("benchmark") << GetAssignmentCommand();
3666 if(!options::produceAssignments()) {
3668 "Cannot get the current assignment when "
3669 "produce-assignments option is off.";
3670 throw ModalException(msg
);
3672 if(d_status
.isNull() ||
3673 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3674 d_problemExtended
) {
3676 "Cannot get the current assignment unless immediately "
3677 "preceded by SAT/INVALID or UNKNOWN response.";
3678 throw ModalException(msg
);
3681 if(d_assignments
== NULL
) {
3682 return SExpr(vector
<SExpr
>());
3685 vector
<SExpr
> sexprs
;
3686 TypeNode boolType
= d_nodeManager
->booleanType();
3687 TheoryModel
* m
= d_theoryEngine
->getModel();
3688 for(AssignmentSet::const_iterator i
= d_assignments
->begin(),
3689 iend
= d_assignments
->end();
3692 Assert((*i
).getType() == boolType
);
3694 Trace("smt") << "--- getting value of " << *i
<< endl
;
3696 // Expand, then normalize
3697 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
3698 Node n
= d_private
->expandDefinitions(*i
, cache
);
3699 n
= d_private
->rewriteBooleanTerms(n
);
3700 n
= Rewriter::rewrite(n
);
3702 Trace("smt") << "--- getting value of " << n
<< endl
;
3705 resultNode
= m
->getValue(n
);
3708 // type-check the result we got
3709 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
3711 // ensure it's a constant
3712 Assert(resultNode
.isConst());
3715 if((*i
).getKind() == kind::APPLY
) {
3716 Assert((*i
).getNumChildren() == 0);
3717 v
.push_back(SExpr::Keyword((*i
).getOperator().toString()));
3719 Assert((*i
).isVar());
3720 v
.push_back(SExpr::Keyword((*i
).toString()));
3722 v
.push_back(SExpr::Keyword(resultNode
.toString()));
3723 sexprs
.push_back(v
);
3725 return SExpr(sexprs
);
3728 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
3729 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
3730 SmtScope
smts(this);
3731 // If we aren't yet fully inited, the user might still turn on
3732 // produce-models. So let's keep any commands around just in
3733 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
3734 // sort "U" in QF_UF before setLogic() is run and we still want to
3735 // support finding card(U) with --finite-model-find, and (2) to
3736 // decouple SmtEngine and ExprManager if the user does a few
3737 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
3738 // and expects to find their cardinalities in the model.
3739 if(/* userVisible && */
3740 (!d_fullyInited
|| options::produceModels()) &&
3741 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
3743 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
3744 d_modelGlobalCommands
.push_back(c
.clone());
3746 d_modelCommands
->push_back(c
.clone());
3749 if(Dump
.isOn(dumpTag
)) {
3753 d_dumpCommands
.push_back(c
.clone());
3758 Model
* SmtEngine::getModel() throw(ModalException
) {
3759 Trace("smt") << "SMT getModel()" << endl
;
3760 SmtScope
smts(this);
3762 finalOptionsAreSet();
3764 if(Dump
.isOn("benchmark")) {
3765 Dump("benchmark") << GetModelCommand();
3768 if(d_status
.isNull() ||
3769 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3770 d_problemExtended
) {
3772 "Cannot get the current model unless immediately "
3773 "preceded by SAT/INVALID or UNKNOWN response.";
3774 throw ModalException(msg
);
3776 if(!options::produceModels()) {
3778 "Cannot get model when produce-models options is off.";
3779 throw ModalException(msg
);
3781 TheoryModel
* m
= d_theoryEngine
->getModel();
3782 m
->d_inputName
= d_filename
;
3786 void SmtEngine::checkModel(bool hardFailure
) {
3787 // --check-model implies --interactive, which enables the assertion list,
3788 // so we should be ok.
3789 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
3791 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
3793 // Throughout, we use Notice() to give diagnostic output.
3795 // If this function is running, the user gave --check-model (or equivalent),
3796 // and if Notice() is on, the user gave --verbose (or equivalent).
3798 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
3799 TheoryModel
* m
= d_theoryEngine
->getModel();
3801 // Check individual theory assertions
3802 d_theoryEngine
->checkTheoryAssertionsWithModel();
3807 // We have a "fake context" for the substitution map (we don't need it
3808 // to be context-dependent)
3809 context::Context fakeContext
;
3810 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
3812 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
3813 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
3814 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
3816 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
3817 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
3819 // We have a DECLARE-FUN:
3821 // We'll first do some checks, then add to our substitution map
3822 // the mapping: function symbol |-> value
3824 Expr func
= c
->getFunction();
3825 Node val
= m
->getValue(func
);
3827 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
3829 // (1) if the value is a lambda, ensure the lambda doesn't contain the
3830 // function symbol (since then the definition is recursive)
3831 if (val
.getKind() == kind::LAMBDA
) {
3832 // first apply the model substitutions we have so far
3833 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
3834 Node n
= substitutions
.apply(val
[1]);
3835 Debug("boolean-terms") << "++ got " << n
<< endl
;
3836 // now check if n contains func by doing a substitution
3837 // [func->func2] and checking equality of the Nodes.
3838 // (this just a way to check if func is in n.)
3839 SubstitutionMap
subs(&fakeContext
);
3840 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
3841 subs
.addSubstitution(func
, func2
);
3842 if(subs
.apply(n
) != n
) {
3843 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
3845 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3846 << "considering model value for " << func
<< endl
3847 << "body of lambda is: " << val
<< endl
;
3849 ss
<< "body substitutes to: " << n
<< endl
;
3851 ss
<< "so " << func
<< " is defined in terms of itself." << endl
3852 << "Run with `--check-models -v' for additional diagnostics.";
3853 InternalError(ss
.str());
3857 // (2) check that the value is actually a value
3858 else if (!val
.isConst()) {
3859 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
3861 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3862 << "model value for " << func
<< endl
3863 << " is " << val
<< endl
3864 << "and that is not a constant (.isConst() == false)." << endl
3865 << "Run with `--check-models -v' for additional diagnostics.";
3866 InternalError(ss
.str());
3869 // (3) check that it's the correct (sub)type
3870 // This was intended to be a more general check, but for now we can't do that because
3871 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
3872 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
3873 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
3875 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3876 << "model value for " << func
<< endl
3877 << " is " << val
<< endl
3878 << "value type is " << val
.getType() << endl
3879 << "should be of type " << func
.getType() << endl
3880 << "Run with `--check-models -v' for additional diagnostics.";
3881 InternalError(ss
.str());
3884 // (4) checks complete, add the substitution
3885 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
3886 substitutions
.addSubstitution(func
, val
);
3890 // Now go through all our user assertions checking if they're satisfied.
3891 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
3892 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
3893 Node n
= Node::fromExpr(*i
);
3895 // Apply any define-funs from the problem.
3897 hash_map
<Node
, Node
, NodeHashFunction
> cache
;
3898 n
= d_private
->expandDefinitions(n
, cache
);
3900 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
3902 // Apply our model value substitutions.
3903 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
3904 n
= substitutions
.apply(n
);
3905 Debug("boolean-terms") << "++ got " << n
<< endl
;
3906 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
3908 //AJR : FIXME need to ignore quantifiers too?
3909 if( n
.getKind() != kind::REWRITE_RULE
){
3910 // In case it's a quantifier (or contains one), look up its value before
3911 // simplifying, or the quantifier might be irreparably altered.
3914 // Note this "skip" is done here, rather than above. This is
3915 // because (1) the quantifier could in principle simplify to false,
3916 // which should be reported, and (2) checking for the quantifier
3917 // above, before simplification, doesn't catch buried quantifiers
3918 // anyway (those not at the top-level).
3919 Notice() << "SmtEngine::checkModel(): -- skipping quantifiers/rewrite-rules assertion"
3924 // Simplify the result.
3925 n
= d_private
->simplify(n
);
3926 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
3928 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
3929 n
= d_private
->d_iteRemover
.replace(n
);
3930 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
3932 // Apply our model value substitutions (again), as things may have been simplified.
3933 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
3934 n
= substitutions
.apply(n
);
3935 Debug("boolean-terms") << "++ got " << n
<< endl
;
3936 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
3938 // As a last-ditch effort, ask model to simplify it.
3939 // Presently, this is only an issue for quantifiers, which can have a value
3940 // but don't show up in our substitution map above.
3942 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
3943 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
3945 // The result should be == true.
3946 if(n
!= NodeManager::currentNM()->mkConst(true)) {
3947 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
3950 ss
<< "SmtEngine::checkModel(): "
3951 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3952 << "assertion: " << *i
<< endl
3953 << "simplifies to: " << n
<< endl
3954 << "expected `true'." << endl
3955 << "Run with `--check-models -v' for additional diagnostics.";
3957 InternalError(ss
.str());
3959 Warning() << ss
.str() << endl
;
3963 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
3966 UnsatCore
SmtEngine::getUnsatCore() throw(ModalException
) {
3967 Trace("smt") << "SMT getUnsatCore()" << endl
;
3968 SmtScope
smts(this);
3969 finalOptionsAreSet();
3970 if(Dump
.isOn("benchmark")) {
3971 Dump("benchmark") << GetUnsatCoreCommand();
3974 if(!options::unsatCores()) {
3975 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
3977 if(d_status
.isNull() ||
3978 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
3979 d_problemExtended
) {
3980 throw ModalException("Cannot get an unsat core unless immediately preceded by UNSAT/VALID response.");
3983 d_proofManager
->getProof(this);// just to trigger core creation
3984 return UnsatCore(this, d_proofManager
->begin_unsat_core(), d_proofManager
->end_unsat_core());
3985 #else /* CVC4_PROOF */
3986 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
3987 #endif /* CVC4_PROOF */
3990 Proof
* SmtEngine::getProof() throw(ModalException
) {
3991 Trace("smt") << "SMT getProof()" << endl
;
3992 SmtScope
smts(this);
3993 finalOptionsAreSet();
3994 if(Dump
.isOn("benchmark")) {
3995 Dump("benchmark") << GetProofCommand();
3998 if(!options::proof()) {
3999 throw ModalException("Cannot get a proof when produce-proofs option is off.");
4001 if(d_status
.isNull() ||
4002 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
4003 d_problemExtended
) {
4004 throw ModalException("Cannot get a proof unless immediately preceded by UNSAT/VALID response.");
4007 return ProofManager::getProof(this);
4008 #else /* CVC4_PROOF */
4009 throw ModalException("This build of CVC4 doesn't have proof support.");
4010 #endif /* CVC4_PROOF */
4013 void SmtEngine::printInstantiations( std::ostream
& out
) {
4014 SmtScope
smts(this);
4015 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
4016 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
4018 if( d_theoryEngine
){
4019 d_theoryEngine
->printInstantiations( out
);
4021 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
4022 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
4026 vector
<Expr
> SmtEngine::getAssertions() throw(ModalException
) {
4027 SmtScope
smts(this);
4028 finalOptionsAreSet();
4029 if(Dump
.isOn("benchmark")) {
4030 Dump("benchmark") << GetAssertionsCommand();
4032 Trace("smt") << "SMT getAssertions()" << endl
;
4033 if(!options::interactive()) {
4035 "Cannot query the current assertion list when not in interactive mode.";
4036 throw ModalException(msg
);
4038 Assert(d_assertionList
!= NULL
);
4039 // copy the result out
4040 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
4043 void SmtEngine::push() throw(ModalException
, LogicException
) {
4044 SmtScope
smts(this);
4045 finalOptionsAreSet();
4047 Trace("smt") << "SMT push()" << endl
;
4048 d_private
->processAssertions();
4049 if(Dump
.isOn("benchmark")) {
4050 Dump("benchmark") << PushCommand();
4052 if(!options::incrementalSolving()) {
4053 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
4056 // check to see if a postsolve() is pending
4057 if(d_needPostsolve
) {
4058 d_theoryEngine
->postsolve();
4059 d_needPostsolve
= false;
4062 // The problem isn't really "extended" yet, but this disallows
4063 // get-model after a push, simplifying our lives somewhat and
4064 // staying symmtric with pop.
4065 d_problemExtended
= true;
4067 d_userLevels
.push_back(d_userContext
->getLevel());
4069 Trace("userpushpop") << "SmtEngine: pushed to level "
4070 << d_userContext
->getLevel() << endl
;
4073 void SmtEngine::pop() throw(ModalException
) {
4074 SmtScope
smts(this);
4075 finalOptionsAreSet();
4076 Trace("smt") << "SMT pop()" << endl
;
4077 if(Dump
.isOn("benchmark")) {
4078 Dump("benchmark") << PopCommand();
4080 if(!options::incrementalSolving()) {
4081 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
4083 if(d_userLevels
.size() == 0) {
4084 throw ModalException("Cannot pop beyond the first user frame");
4087 // check to see if a postsolve() is pending
4088 if(d_needPostsolve
) {
4089 d_theoryEngine
->postsolve();
4090 d_needPostsolve
= false;
4093 // The problem isn't really "extended" yet, but this disallows
4094 // get-model after a pop, simplifying our lives somewhat. It might
4095 // not be strictly necessary to do so, since the pops occur lazily,
4096 // but also it would be weird to have a legally-executed (get-model)
4097 // that only returns a subset of the assignment (because the rest
4098 // is no longer in scope!).
4099 d_problemExtended
= true;
4101 AlwaysAssert(d_userContext
->getLevel() > 0);
4102 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
4103 while (d_userLevels
.back() < d_userContext
->getLevel()) {
4106 d_userLevels
.pop_back();
4108 // Clear out assertion queues etc., in case anything is still in there
4109 d_private
->notifyPop();
4111 Trace("userpushpop") << "SmtEngine: popped to level "
4112 << d_userContext
->getLevel() << endl
;
4113 // FIXME: should we reset d_status here?
4114 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
4115 // Still, we want the right exit status after any final sequence
4119 void SmtEngine::internalPush() {
4120 Assert(d_fullyInited
);
4121 Trace("smt") << "SmtEngine::internalPush()" << endl
;
4123 if(options::incrementalSolving()) {
4124 d_private
->processAssertions();
4125 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
4126 d_userContext
->push();
4127 // the d_context push is done inside of the SAT solver
4128 d_propEngine
->push();
4132 void SmtEngine::internalPop(bool immediate
) {
4133 Assert(d_fullyInited
);
4134 Trace("smt") << "SmtEngine::internalPop()" << endl
;
4135 if(options::incrementalSolving()) {
4143 void SmtEngine::doPendingPops() {
4144 Assert(d_pendingPops
== 0 || options::incrementalSolving());
4145 while(d_pendingPops
> 0) {
4146 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
4147 d_propEngine
->pop();
4148 // the d_context pop is done inside of the SAT solver
4149 d_userContext
->pop();
4154 void SmtEngine::interrupt() throw(ModalException
) {
4155 if(!d_fullyInited
) {
4158 d_propEngine
->interrupt();
4159 d_theoryEngine
->interrupt();
4162 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
4164 Trace("limit") << "SmtEngine: setting cumulative resource limit to " << units
<< endl
;
4165 d_resourceBudgetCumulative
= (units
== 0) ? 0 : (d_cumulativeResourceUsed
+ units
);
4167 Trace("limit") << "SmtEngine: setting per-call resource limit to " << units
<< endl
;
4168 d_resourceBudgetPerCall
= units
;
4172 void SmtEngine::setTimeLimit(unsigned long millis
, bool cumulative
) {
4174 Trace("limit") << "SmtEngine: setting cumulative time limit to " << millis
<< " ms" << endl
;
4175 d_timeBudgetCumulative
= (millis
== 0) ? 0 : (d_cumulativeTimeUsed
+ millis
);
4177 Trace("limit") << "SmtEngine: setting per-call time limit to " << millis
<< " ms" << endl
;
4178 d_timeBudgetPerCall
= millis
;
4182 unsigned long SmtEngine::getResourceUsage() const {
4183 return d_cumulativeResourceUsed
;
4186 unsigned long SmtEngine::getTimeUsage() const {
4187 return d_cumulativeTimeUsed
;
4190 unsigned long SmtEngine::getResourceRemaining() const throw(ModalException
) {
4191 if(d_resourceBudgetCumulative
== 0) {
4192 throw ModalException("No cumulative resource limit is currently set");
4195 return d_resourceBudgetCumulative
<= d_cumulativeResourceUsed
? 0 :
4196 d_resourceBudgetCumulative
- d_cumulativeResourceUsed
;
4199 unsigned long SmtEngine::getTimeRemaining() const throw(ModalException
) {
4200 if(d_timeBudgetCumulative
== 0) {
4201 throw ModalException("No cumulative time limit is currently set");
4204 return d_timeBudgetCumulative
<= d_cumulativeTimeUsed
? 0 :
4205 d_timeBudgetCumulative
- d_cumulativeTimeUsed
;
4208 Statistics
SmtEngine::getStatistics() const throw() {
4209 return Statistics(*d_statisticsRegistry
);
4212 SExpr
SmtEngine::getStatistic(std::string name
) const throw() {
4213 return d_statisticsRegistry
->getStatistic(name
);
4216 void SmtEngine::setUserAttribute(const std::string
& attr
, Expr expr
, std::vector
<Expr
> expr_values
, std::string str_value
) {
4217 SmtScope
smts(this);
4218 std::vector
<Node
> node_values
;
4219 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
4220 node_values
.push_back( expr_values
[i
].getNode() );
4222 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
4225 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
4226 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
4227 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
4228 Command
* c
= d_modelGlobalCommands
[i
];
4229 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
4231 if( dfc
->getFunction()==f
){
4232 dfc
->setPrintInModel( p
);
4236 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
4237 Command
* c
= (*d_modelCommands
)[i
];
4238 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
4240 if( dfc
->getFunction()==f
){
4241 dfc
->setPrintInModel( p
);
4247 }/* CVC4 namespace */