1 /********************* */
2 /*! \file smt_engine.cpp
4 ** Top contributors (to current version):
5 ** Morgan Deters, Andrew Reynolds, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing 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.
17 #include "smt/smt_engine.h"
26 #include <unordered_map>
27 #include <unordered_set>
31 #include "base/configuration.h"
32 #include "base/configuration_private.h"
33 #include "base/exception.h"
34 #include "base/listener.h"
35 #include "base/modal_exception.h"
36 #include "base/output.h"
37 #include "context/cdhashmap.h"
38 #include "context/cdhashset.h"
39 #include "context/cdlist.h"
40 #include "context/context.h"
41 #include "decision/decision_engine.h"
42 #include "expr/attribute.h"
43 #include "expr/expr.h"
44 #include "expr/kind.h"
45 #include "expr/metakind.h"
46 #include "expr/node.h"
47 #include "expr/node_builder.h"
48 #include "expr/node_self_iterator.h"
49 #include "options/arith_options.h"
50 #include "options/arrays_options.h"
51 #include "options/base_options.h"
52 #include "options/booleans_options.h"
53 #include "options/bv_options.h"
54 #include "options/datatypes_options.h"
55 #include "options/decision_mode.h"
56 #include "options/decision_options.h"
57 #include "options/language.h"
58 #include "options/main_options.h"
59 #include "options/open_ostream.h"
60 #include "options/option_exception.h"
61 #include "options/printer_options.h"
62 #include "options/proof_options.h"
63 #include "options/prop_options.h"
64 #include "options/quantifiers_options.h"
65 #include "options/sep_options.h"
66 #include "options/set_language.h"
67 #include "options/smt_options.h"
68 #include "options/strings_options.h"
69 #include "options/theory_options.h"
70 #include "options/uf_options.h"
71 #include "preprocessing/passes/bool_to_bv.h"
72 #include "preprocessing/passes/bv_abstraction.h"
73 #include "preprocessing/passes/bv_ackermann.h"
74 #include "preprocessing/passes/bv_gauss.h"
75 #include "preprocessing/passes/bv_intro_pow2.h"
76 #include "preprocessing/passes/bv_to_bool.h"
77 #include "preprocessing/passes/int_to_bv.h"
78 #include "preprocessing/passes/pseudo_boolean_processor.h"
79 #include "preprocessing/passes/real_to_int.h"
80 #include "preprocessing/passes/static_learning.h"
81 #include "preprocessing/passes/symmetry_breaker.h"
82 #include "preprocessing/passes/symmetry_detect.h"
83 #include "preprocessing/preprocessing_pass.h"
84 #include "preprocessing/preprocessing_pass_context.h"
85 #include "preprocessing/preprocessing_pass_registry.h"
86 #include "printer/printer.h"
87 #include "proof/proof.h"
88 #include "proof/proof_manager.h"
89 #include "proof/theory_proof.h"
90 #include "proof/unsat_core.h"
91 #include "prop/prop_engine.h"
92 #include "smt/command.h"
93 #include "smt/command_list.h"
94 #include "smt/logic_request.h"
95 #include "smt/managed_ostreams.h"
96 #include "smt/smt_engine_scope.h"
97 #include "smt/term_formula_removal.h"
98 #include "smt/update_ostream.h"
99 #include "smt_util/boolean_simplification.h"
100 #include "smt_util/nary_builder.h"
101 #include "smt_util/node_visitor.h"
102 #include "theory/booleans/circuit_propagator.h"
103 #include "theory/bv/theory_bv_rewriter.h"
104 #include "theory/logic_info.h"
105 #include "theory/quantifiers/fun_def_process.h"
106 #include "theory/quantifiers/global_negate.h"
107 #include "theory/quantifiers/macros.h"
108 #include "theory/quantifiers/quantifiers_rewriter.h"
109 #include "theory/quantifiers/single_inv_partition.h"
110 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
111 #include "theory/quantifiers/sygus_inference.h"
112 #include "theory/quantifiers/term_util.h"
113 #include "theory/sort_inference.h"
114 #include "theory/strings/theory_strings.h"
115 #include "theory/substitutions.h"
116 #include "theory/theory_engine.h"
117 #include "theory/theory_model.h"
118 #include "theory/theory_traits.h"
119 #include "util/hash.h"
120 #include "util/proof.h"
121 #include "util/random.h"
122 #include "util/resource_manager.h"
125 using namespace CVC4
;
126 using namespace CVC4::smt
;
127 using namespace CVC4::preprocessing
;
128 using namespace CVC4::preprocessing::passes
;
129 using namespace CVC4::prop
;
130 using namespace CVC4::context
;
131 using namespace CVC4::theory
;
136 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
138 void operator()(const Command
* command
) { delete command
; }
141 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
142 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
146 /** Useful for counting the number of recursive calls. */
151 ScopeCounter(unsigned& d
) : d_depth(d
) {
160 * Representation of a defined function. We keep these around in
161 * SmtEngine to permit expanding definitions late (and lazily), to
162 * support getValue() over defined functions, to support user output
163 * in terms of defined functions, etc.
165 class DefinedFunction
{
167 vector
<Node
> d_formals
;
171 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
176 Node
getFunction() const { return d_func
; }
177 vector
<Node
> getFormals() const { return d_formals
; }
178 Node
getFormula() const { return d_formula
; }
179 };/* class DefinedFunction */
181 struct SmtEngineStatistics
{
182 /** time spent in gaussian elimination */
183 TimerStat d_gaussElimTime
;
184 /** time spent in definition-expansion */
185 TimerStat d_definitionExpansionTime
;
186 /** time spent in non-clausal simplification */
187 TimerStat d_nonclausalSimplificationTime
;
188 /** time spent in miplib pass */
189 TimerStat d_miplibPassTime
;
190 /** number of assertions removed by miplib pass */
191 IntStat d_numMiplibAssertionsRemoved
;
192 /** number of constant propagations found during nonclausal simp */
193 IntStat d_numConstantProps
;
194 /** time spent in simplifying ITEs */
195 TimerStat d_simpITETime
;
196 /** time spent in simplifying ITEs */
197 TimerStat d_unconstrainedSimpTime
;
198 /** time spent removing ITEs */
199 TimerStat d_iteRemovalTime
;
200 /** time spent in theory preprocessing */
201 TimerStat d_theoryPreprocessTime
;
202 /** time spent in theory preprocessing */
203 TimerStat d_rewriteApplyToConstTime
;
204 /** time spent converting to CNF */
205 TimerStat d_cnfConversionTime
;
206 /** Num of assertions before ite removal */
207 IntStat d_numAssertionsPre
;
208 /** Num of assertions after ite removal */
209 IntStat d_numAssertionsPost
;
210 /** time spent in checkModel() */
211 TimerStat d_checkModelTime
;
212 /** time spent in checkProof() */
213 TimerStat d_checkProofTime
;
214 /** time spent in checkUnsatCore() */
215 TimerStat d_checkUnsatCoreTime
;
216 /** time spent in PropEngine::checkSat() */
217 TimerStat d_solveTime
;
218 /** time spent in pushing/popping */
219 TimerStat d_pushPopTime
;
220 /** time spent in processAssertions() */
221 TimerStat d_processAssertionsTime
;
223 /** Has something simplified to false? */
224 IntStat d_simplifiedToFalse
;
225 /** Number of resource units spent. */
226 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
228 SmtEngineStatistics() :
229 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
230 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
231 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
232 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
233 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
234 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
235 d_simpITETime("smt::SmtEngine::simpITETime"),
236 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
237 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
238 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
239 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
240 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
241 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
242 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
243 d_checkModelTime("smt::SmtEngine::checkModelTime"),
244 d_checkProofTime("smt::SmtEngine::checkProofTime"),
245 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
246 d_solveTime("smt::SmtEngine::solveTime"),
247 d_pushPopTime("smt::SmtEngine::pushPopTime"),
248 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
249 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
250 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
253 smtStatisticsRegistry()->registerStat(&d_gaussElimTime
);
254 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
255 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime
);
256 smtStatisticsRegistry()->registerStat(&d_miplibPassTime
);
257 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved
);
258 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
259 smtStatisticsRegistry()->registerStat(&d_simpITETime
);
260 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime
);
261 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime
);
262 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime
);
263 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime
);
264 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
265 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
266 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
267 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
268 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
269 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
270 smtStatisticsRegistry()->registerStat(&d_solveTime
);
271 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
272 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
273 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
274 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
277 ~SmtEngineStatistics() {
278 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime
);
279 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
280 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime
);
281 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime
);
282 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved
);
283 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
284 smtStatisticsRegistry()->unregisterStat(&d_simpITETime
);
285 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime
);
286 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime
);
287 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime
);
288 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime
);
289 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
290 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
291 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
292 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
293 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
294 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
295 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
296 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
297 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
298 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
299 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
301 };/* struct SmtEngineStatistics */
304 class SoftResourceOutListener
: public Listener
{
306 SoftResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
307 void notify() override
309 SmtScope
scope(d_smt
);
310 Assert(smt::smtEngineInScope());
315 }; /* class SoftResourceOutListener */
318 class HardResourceOutListener
: public Listener
{
320 HardResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
321 void notify() override
323 SmtScope
scope(d_smt
);
324 theory::Rewriter::clearCaches();
328 }; /* class HardResourceOutListener */
330 class SetLogicListener
: public Listener
{
332 SetLogicListener(SmtEngine
& smt
) : d_smt(&smt
) {}
333 void notify() override
335 LogicInfo
inOptions(options::forceLogicString());
336 d_smt
->setLogic(inOptions
);
340 }; /* class SetLogicListener */
342 class BeforeSearchListener
: public Listener
{
344 BeforeSearchListener(SmtEngine
& smt
) : d_smt(&smt
) {}
345 void notify() override
{ d_smt
->beforeSearch(); }
349 }; /* class BeforeSearchListener */
351 class UseTheoryListListener
: public Listener
{
353 UseTheoryListListener(TheoryEngine
* theoryEngine
)
354 : d_theoryEngine(theoryEngine
)
357 void notify() override
359 std::stringstream
commaList(options::useTheoryList());
362 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
363 << options::useTheoryList() << std::endl
;
365 while(std::getline(commaList
, token
, ',')){
366 if(token
== "help") {
367 puts(theory::useTheoryHelp
);
370 if(theory::useTheoryValidate(token
)) {
371 d_theoryEngine
->enableTheoryAlternative(token
);
373 throw OptionException(
374 std::string("unknown option for --use-theory : `") + token
+
375 "'. Try --use-theory=help.");
381 TheoryEngine
* d_theoryEngine
;
382 }; /* class UseTheoryListListener */
385 class SetDefaultExprDepthListener
: public Listener
{
387 void notify() override
389 int depth
= options::defaultExprDepth();
390 Debug
.getStream() << expr::ExprSetDepth(depth
);
391 Trace
.getStream() << expr::ExprSetDepth(depth
);
392 Notice
.getStream() << expr::ExprSetDepth(depth
);
393 Chat
.getStream() << expr::ExprSetDepth(depth
);
394 Message
.getStream() << expr::ExprSetDepth(depth
);
395 Warning
.getStream() << expr::ExprSetDepth(depth
);
396 // intentionally exclude Dump stream from this list
400 class SetDefaultExprDagListener
: public Listener
{
402 void notify() override
404 int dag
= options::defaultDagThresh();
405 Debug
.getStream() << expr::ExprDag(dag
);
406 Trace
.getStream() << expr::ExprDag(dag
);
407 Notice
.getStream() << expr::ExprDag(dag
);
408 Chat
.getStream() << expr::ExprDag(dag
);
409 Message
.getStream() << expr::ExprDag(dag
);
410 Warning
.getStream() << expr::ExprDag(dag
);
411 Dump
.getStream() << expr::ExprDag(dag
);
415 class SetPrintExprTypesListener
: public Listener
{
417 void notify() override
419 bool value
= options::printExprTypes();
420 Debug
.getStream() << expr::ExprPrintTypes(value
);
421 Trace
.getStream() << expr::ExprPrintTypes(value
);
422 Notice
.getStream() << expr::ExprPrintTypes(value
);
423 Chat
.getStream() << expr::ExprPrintTypes(value
);
424 Message
.getStream() << expr::ExprPrintTypes(value
);
425 Warning
.getStream() << expr::ExprPrintTypes(value
);
426 // intentionally exclude Dump stream from this list
430 class DumpModeListener
: public Listener
{
432 void notify() override
434 const std::string
& value
= options::dumpModeString();
435 Dump
.setDumpFromString(value
);
439 class PrintSuccessListener
: public Listener
{
441 void notify() override
443 bool value
= options::printSuccess();
444 Debug
.getStream() << Command::printsuccess(value
);
445 Trace
.getStream() << Command::printsuccess(value
);
446 Notice
.getStream() << Command::printsuccess(value
);
447 Chat
.getStream() << Command::printsuccess(value
);
448 Message
.getStream() << Command::printsuccess(value
);
449 Warning
.getStream() << Command::printsuccess(value
);
450 *options::out() << Command::printsuccess(value
);
457 * This is an inelegant solution, but for the present, it will work.
458 * The point of this is to separate the public and private portions of
459 * the SmtEngine class, so that smt_engine.h doesn't
460 * include "expr/node.h", which is a private CVC4 header (and can lead
461 * to linking errors due to the improper inlining of non-visible symbols
464 * The "real" solution (that which is usually implemented) is to move
465 * ALL the implementation to SmtEnginePrivate and maintain a
466 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
467 * one) becomes an "interface shell" which simply acts as a forwarder
470 class SmtEnginePrivate
: public NodeManagerListener
{
473 typedef unordered_map
<Node
, Node
, NodeHashFunction
> NodeToNodeHashMap
;
474 typedef unordered_map
<Node
, bool, NodeHashFunction
> NodeToBoolHashMap
;
477 * Manager for limiting time and abstract resource usage.
479 ResourceManager
* d_resourceManager
;
481 /** Manager for the memory of regular-output-channel. */
482 ManagedRegularOutputChannel d_managedRegularChannel
;
484 /** Manager for the memory of diagnostic-output-channel. */
485 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel
;
487 /** Manager for the memory of --dump-to. */
488 ManagedDumpOStream d_managedDumpChannel
;
490 /** Manager for --replay-log. */
491 ManagedReplayLogOstream d_managedReplayLog
;
494 * This list contains:
498 * beforeSearchListener
499 * UseTheoryListListener
501 * This needs to be deleted before both NodeManager's Options,
502 * SmtEngine, d_resourceManager, and TheoryEngine.
504 ListenerRegistrationList
* d_listenerRegistrations
;
506 /** Learned literals */
507 vector
<Node
> d_nonClausalLearnedLiterals
;
509 /** Size of assertions array when preprocessing starts */
510 unsigned d_realAssertionsEnd
;
512 /** A circuit propagator for non-clausal propositional deduction */
513 booleans::CircuitPropagator d_propagator
;
514 bool d_propagatorNeedsFinish
;
515 std::vector
<Node
> d_boolVars
;
517 /** Assertions in the preprocessing pipeline */
518 AssertionPipeline d_assertions
;
520 /** Whether any assertions have been processed */
521 CDO
<bool> d_assertionsProcessed
;
523 /** Index for where to store substitutions */
524 CDO
<unsigned> d_substitutionsIndex
;
530 * A context that never pushes/pops, for use by CD structures (like
531 * SubstitutionMaps) that should be "global".
533 context::Context d_fakeContext
;
536 * A map of AbsractValues to their actual constants. Only used if
537 * options::abstractValues() is on.
539 SubstitutionMap d_abstractValueMap
;
542 * A mapping of all abstract values (actual value |-> abstract) that
543 * we've handed out. This is necessary to ensure that we give the
544 * same AbstractValues for the same real constants. Only used if
545 * options::abstractValues() is on.
547 NodeToNodeHashMap d_abstractValues
;
549 /** Number of calls of simplify assertions active.
551 unsigned d_simplifyAssertionsDepth
;
553 /** TODO: whether certain preprocess steps are necessary */
554 //bool d_needsExpandDefs;
556 //------------------------------- expression names
557 /** mapping from expressions to name */
558 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
559 //------------------------------- end expression names
562 * Map from skolem variables to index in d_assertions containing
563 * corresponding introduced Boolean ite
565 IteSkolemMap d_iteSkolemMap
;
567 /** Instance of the ITE remover */
568 RemoveTermFormulas d_iteRemover
;
570 /* Finishes the initialization of the private portion of SMTEngine. */
574 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
575 PreprocessingPassRegistry d_preprocessingPassRegistry
;
577 /** The top level substitutions */
578 SubstitutionMap d_topLevelSubstitutions
;
580 static const bool d_doConstantProp
= true;
583 * Runs the nonclausal solver and tries to solve all the assigned
586 * Returns false if the formula simplifies to "false"
588 bool nonClausalSimplify();
591 * Performs static learning on the assertions.
593 void staticLearning();
596 * Remove ITEs from the assertions.
600 Node
realToInt(TNode n
, NodeToNodeHashMap
& cache
, std::vector
< Node
>& var_eq
);
601 Node
purifyNlTerms(TNode n
, NodeToNodeHashMap
& cache
, NodeToNodeHashMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
= false);
604 * Helper function to fix up assertion list to restore invariants needed after
607 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
610 * Helper function to fix up assertion list to restore invariants needed after
613 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
615 // Simplify ITE structure
618 // Simplify based on unconstrained values
619 void unconstrainedSimp();
622 * Ensures the assertions asserted after before now effectively come before
623 * d_realAssertionsEnd.
625 void compressBeforeRealAssertions(size_t before
);
628 * Trace nodes back to their assertions using CircuitPropagator's
631 void traceBackToAssertions(const std::vector
<Node
>& nodes
,
632 std::vector
<TNode
>& assertions
);
635 * Remove conjuncts in toRemove from conjunction n. Return # of removed
638 size_t removeFromConjunction(Node
& n
,
639 const std::unordered_set
<unsigned long>& toRemove
);
641 /** Scrub miplib encodings. */
642 void doMiplibTrick();
645 * Perform non-clausal simplification of a Node. This involves
646 * Theory implementations, but does NOT involve the SAT solver in
649 * Returns false if the formula simplifies to "false"
651 bool simplifyAssertions();
655 SmtEnginePrivate(SmtEngine
& smt
) :
657 d_managedRegularChannel(),
658 d_managedDiagnosticChannel(),
659 d_managedDumpChannel(),
660 d_managedReplayLog(),
661 d_listenerRegistrations(new ListenerRegistrationList()),
662 d_nonClausalLearnedLiterals(),
663 d_realAssertionsEnd(0),
664 d_propagator(d_nonClausalLearnedLiterals
, true, true),
665 d_propagatorNeedsFinish(false),
667 d_assertionsProcessed(smt
.d_userContext
, false),
668 d_substitutionsIndex(smt
.d_userContext
, 0),
670 d_abstractValueMap(&d_fakeContext
),
672 d_simplifyAssertionsDepth(0),
673 //d_needsExpandDefs(true), //TODO?
674 d_exprNames(smt
.d_userContext
),
676 d_iteRemover(smt
.d_userContext
),
677 d_topLevelSubstitutions(smt
.d_userContext
)
679 d_smt
.d_nodeManager
->subscribeEvents(this);
680 d_true
= NodeManager::currentNM()->mkConst(true);
681 d_resourceManager
= NodeManager::currentResourceManager();
683 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
684 new SoftResourceOutListener(d_smt
)));
686 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
687 new HardResourceOutListener(d_smt
)));
689 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
690 d_listenerRegistrations
->add(
691 nodeManagerOptions
.registerForceLogicListener(
692 new SetLogicListener(d_smt
), true));
694 // Multiple options reuse BeforeSearchListener so registration requires an
695 // extra bit of care.
696 // We can safely not call notify on this before search listener at
697 // registration time. This d_smt cannot be beforeSearch at construction
698 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
699 // not have to be called.
700 d_listenerRegistrations
->add(
701 nodeManagerOptions
.registerBeforeSearchListener(
702 new BeforeSearchListener(d_smt
)));
704 // These do need registration calls.
705 d_listenerRegistrations
->add(
706 nodeManagerOptions
.registerSetDefaultExprDepthListener(
707 new SetDefaultExprDepthListener(), true));
708 d_listenerRegistrations
->add(
709 nodeManagerOptions
.registerSetDefaultExprDagListener(
710 new SetDefaultExprDagListener(), true));
711 d_listenerRegistrations
->add(
712 nodeManagerOptions
.registerSetPrintExprTypesListener(
713 new SetPrintExprTypesListener(), true));
714 d_listenerRegistrations
->add(
715 nodeManagerOptions
.registerSetDumpModeListener(
716 new DumpModeListener(), true));
717 d_listenerRegistrations
->add(
718 nodeManagerOptions
.registerSetPrintSuccessListener(
719 new PrintSuccessListener(), true));
720 d_listenerRegistrations
->add(
721 nodeManagerOptions
.registerSetRegularOutputChannelListener(
722 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
723 d_listenerRegistrations
->add(
724 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
725 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
726 d_listenerRegistrations
->add(
727 nodeManagerOptions
.registerDumpToFileNameListener(
728 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
729 d_listenerRegistrations
->add(
730 nodeManagerOptions
.registerSetReplayLogFilename(
731 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
736 delete d_listenerRegistrations
;
738 if(d_propagatorNeedsFinish
) {
739 d_propagator
.finish();
740 d_propagatorNeedsFinish
= false;
742 d_smt
.d_nodeManager
->unsubscribeEvents(this);
745 void unregisterPreprocessingPasses()
747 d_preprocessingPassRegistry
.unregisterPasses();
750 ResourceManager
* getResourceManager() { return d_resourceManager
; }
751 void spendResource(unsigned amount
)
753 d_resourceManager
->spendResource(amount
);
756 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) override
758 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
761 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
762 d_smt
.addToModelCommandAndDump(c
, flags
);
766 void nmNotifyNewSortConstructor(TypeNode tn
) override
768 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
769 tn
.getAttribute(expr::SortArityAttr()),
771 d_smt
.addToModelCommandAndDump(c
);
774 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
) override
776 DatatypeDeclarationCommand
c(dtts
);
777 d_smt
.addToModelCommandAndDump(c
);
780 void nmNotifyNewVar(TNode n
, uint32_t flags
) override
782 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
784 n
.getType().toType());
785 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
786 d_smt
.addToModelCommandAndDump(c
, flags
);
788 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
789 d_boolVars
.push_back(n
);
793 void nmNotifyNewSkolem(TNode n
,
794 const std::string
& comment
,
795 uint32_t flags
) override
797 string id
= n
.getAttribute(expr::VarNameAttr());
798 DeclareFunctionCommand
c(id
, n
.toExpr(), n
.getType().toType());
799 if(Dump
.isOn("skolems") && comment
!= "") {
800 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
802 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
803 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
805 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
806 d_boolVars
.push_back(n
);
810 void nmNotifyDeleteNode(TNode n
) override
{}
812 Node
applySubstitutions(TNode node
) const {
813 return Rewriter::rewrite(d_topLevelSubstitutions
.apply(node
));
817 * Apply the substitutions in d_topLevelAssertions and the rewriter to each of
818 * the assertions in d_assertions, and store the result back in d_assertions.
820 void applySubstitutionsToAssertions();
823 * Process the assertions that have been asserted.
825 void processAssertions();
827 /** Process a user push.
834 * Process a user pop. Clears out the non-context-dependent stuff in this
835 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
836 * someone does a push-assert-pop without a check-sat. It also pops the
837 * last map of expression names from notifyPush.
840 d_assertions
.clear();
841 d_nonClausalLearnedLiterals
.clear();
842 d_realAssertionsEnd
= 0;
843 d_iteSkolemMap
.clear();
847 * Adds a formula to the current context. Action here depends on
848 * the SimplificationMode (in the current Options scope); the
849 * formula might be pushed out to the propositional layer
850 * immediately, or it might be simplified and kept, or it might not
851 * even be simplified.
852 * the 2nd and 3rd arguments added for bookkeeping for proofs
854 void addFormula(TNode n
, bool inUnsatCore
, bool inInput
= true);
856 /** Expand definitions in n. */
857 Node
expandDefinitions(TNode n
,
858 NodeToNodeHashMap
& cache
,
859 bool expandOnly
= false);
862 * Simplify node "in" by expanding definitions and applying any
863 * substitutions learned from preprocessing.
865 Node
simplify(TNode in
) {
866 // Substitute out any abstract values in ex.
867 // Expand definitions.
868 NodeToNodeHashMap cache
;
869 Node n
= expandDefinitions(in
, cache
).toExpr();
870 // Make sure we've done all preprocessing, etc.
871 Assert(d_assertions
.size() == 0);
872 return applySubstitutions(n
).toExpr();
876 * Substitute away all AbstractValues in a node.
878 Node
substituteAbstractValues(TNode n
) {
879 // We need to do this even if options::abstractValues() is off,
880 // since the setting might have changed after we already gave out
881 // some abstract values.
882 return d_abstractValueMap
.apply(n
);
886 * Make a new (or return an existing) abstract value for a node.
887 * Can only use this if options::abstractValues() is on.
889 Node
mkAbstractValue(TNode n
) {
890 Assert(options::abstractValues());
891 Node
& val
= d_abstractValues
[n
];
893 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
894 d_abstractValueMap
.addSubstitution(val
, n
);
896 // We are supposed to ascribe types to all abstract values that go out.
897 NodeManager
* current
= d_smt
.d_nodeManager
;
898 Node ascription
= current
->mkConst(AscriptionType(n
.getType().toType()));
899 Node retval
= current
->mkNode(kind::APPLY_TYPE_ASCRIPTION
, ascription
, val
);
903 NodeToNodeHashMap d_rewriteApplyToConstCache
;
904 Node
rewriteApplyToConst(TNode n
) {
905 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n
<< std::endl
;
907 if(n
.getMetaKind() == kind::metakind::CONSTANT
||
908 n
.getMetaKind() == kind::metakind::VARIABLE
||
909 n
.getMetaKind() == kind::metakind::NULLARY_OPERATOR
)
914 if(d_rewriteApplyToConstCache
.find(n
) != d_rewriteApplyToConstCache
.end()) {
915 Trace("rewriteApplyToConst") << "in cache :: "
916 << d_rewriteApplyToConstCache
[n
]
918 return d_rewriteApplyToConstCache
[n
];
921 if(n
.getKind() == kind::APPLY_UF
) {
922 if(n
.getNumChildren() == 1 && n
[0].isConst() &&
923 n
[0].getType().isInteger())
926 ss
<< n
.getOperator() << "_";
927 if(n
[0].getConst
<Rational
>() < 0) {
928 ss
<< "m" << -n
[0].getConst
<Rational
>();
932 Node newvar
= NodeManager::currentNM()->mkSkolem(
933 ss
.str(), n
.getType(), "rewriteApplyToConst skolem",
934 NodeManager::SKOLEM_EXACT_NAME
);
935 d_rewriteApplyToConstCache
[n
] = newvar
;
936 Trace("rewriteApplyToConst") << "made :: " << newvar
<< std::endl
;
940 ss
<< "The rewrite-apply-to-const preprocessor is currently limited;"
942 << "it only works if all function symbols are unary and with Integer"
944 << "domain, and all applications are to integer values." << std::endl
945 << "Found application: " << n
;
950 NodeBuilder
<> builder(n
.getKind());
951 if(n
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
952 builder
<< n
.getOperator();
954 for(unsigned i
= 0; i
< n
.getNumChildren(); ++i
) {
955 builder
<< rewriteApplyToConst(n
[i
]);
958 d_rewriteApplyToConstCache
[n
] = rewr
;
959 Trace("rewriteApplyToConst") << "built :: " << rewr
<< std::endl
;
963 void addUseTheoryListListener(TheoryEngine
* theoryEngine
){
964 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
965 d_listenerRegistrations
->add(
966 nodeManagerOptions
.registerUseTheoryListListener(
967 new UseTheoryListListener(theoryEngine
), true));
970 std::ostream
* getReplayLog() const {
971 return d_managedReplayLog
.getReplayLog();
974 //------------------------------- expression names
975 // implements setExpressionName, as described in smt_engine.h
976 void setExpressionName(Expr e
, std::string name
) {
977 d_exprNames
[Node::fromExpr(e
)] = name
;
980 // implements getExpressionName, as described in smt_engine.h
981 bool getExpressionName(Expr e
, std::string
& name
) const {
982 context::CDHashMap
< Node
, std::string
, NodeHashFunction
>::const_iterator it
= d_exprNames
.find(e
);
983 if(it
!=d_exprNames
.end()) {
990 //------------------------------- end expression names
992 };/* class SmtEnginePrivate */
994 }/* namespace CVC4::smt */
996 SmtEngine::SmtEngine(ExprManager
* em
)
997 : d_context(new Context()),
999 d_userContext(new UserContext()),
1001 d_nodeManager(d_exprManager
->getNodeManager()),
1002 d_decisionEngine(NULL
),
1003 d_theoryEngine(NULL
),
1005 d_proofManager(NULL
),
1006 d_definedFunctions(NULL
),
1007 d_fmfRecFunctionsDefined(NULL
),
1008 d_assertionList(NULL
),
1009 d_assignments(NULL
),
1010 d_modelGlobalCommands(),
1011 d_modelCommands(NULL
),
1015 d_originalOptions(),
1017 d_fullyInited(false),
1018 d_problemExtended(false),
1020 d_needPostsolve(false),
1021 d_earlyTheoryPP(true),
1022 d_globalNegation(false),
1024 d_replayStream(NULL
),
1026 d_statisticsRegistry(NULL
),
1028 d_channels(new LemmaChannels())
1030 SmtScope
smts(this);
1031 d_originalOptions
.copyValues(em
->getOptions());
1032 d_private
= new smt::SmtEnginePrivate(*this);
1033 d_statisticsRegistry
= new StatisticsRegistry();
1034 d_stats
= new SmtEngineStatistics();
1035 d_stats
->d_resourceUnitsUsed
.setData(
1036 d_private
->getResourceManager()->getResourceUsage());
1038 // The ProofManager is constructed before any other proof objects such as
1039 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
1040 // initialized in TheoryEngine and PropEngine respectively.
1041 Assert(d_proofManager
== NULL
);
1043 // d_proofManager must be created before Options has been finished
1044 // being parsed from the input file. Because of this, we cannot trust
1045 // that options::proof() is set correctly yet.
1047 d_proofManager
= new ProofManager(d_userContext
);
1050 // We have mutual dependency here, so we add the prop engine to the theory
1051 // engine later (it is non-essential there)
1052 d_theoryEngine
= new TheoryEngine(d_context
, d_userContext
,
1053 d_private
->d_iteRemover
,
1054 const_cast<const LogicInfo
&>(d_logic
),
1058 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1059 TheoryConstructor::addTheory(d_theoryEngine
, id
);
1060 //register with proof engine if applicable
1062 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine
->theoryOf(id
));
1066 d_private
->addUseTheoryListListener(d_theoryEngine
);
1068 // global push/pop around everything, to ensure proper destruction
1069 // of context-dependent data structures
1070 d_userContext
->push();
1073 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
1074 d_fmfRecFunctionsDefined
= new(true) NodeList(d_userContext
);
1075 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
1078 void SmtEngine::finishInit() {
1079 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl
;
1080 // ensure that our heuristics are properly set up
1083 Trace("smt-debug") << "Making decision engine..." << std::endl
;
1085 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
1086 d_decisionEngine
->init(); // enable appropriate strategies
1088 Trace("smt-debug") << "Making prop engine..." << std::endl
;
1089 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
,
1090 d_userContext
, d_private
->getReplayLog(),
1091 d_replayStream
, d_channels
);
1093 Trace("smt-debug") << "Setting up theory engine..." << std::endl
;
1094 d_theoryEngine
->setPropEngine(d_propEngine
);
1095 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
1096 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl
;
1097 d_theoryEngine
->finishInit();
1099 Trace("smt-debug") << "Set up assertion list..." << std::endl
;
1100 // [MGD 10/20/2011] keep around in incremental mode, due to a
1101 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
1102 // first, some user-context-dependent TNodes might still exist
1104 if(options::produceAssertions() ||
1105 options::incrementalSolving()) {
1106 // In the case of incremental solving, we appear to need these to
1107 // ensure the relevant Nodes remain live.
1108 d_assertionList
= new(true) AssertionList(d_userContext
);
1111 // dump out a set-logic command
1112 if(Dump
.isOn("benchmark")) {
1113 if (Dump
.isOn("raw-benchmark")) {
1114 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic
.getLogicString());
1116 LogicInfo everything
;
1118 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.")
1119 << SetBenchmarkLogicCommand(everything
.getLogicString());
1123 Trace("smt-debug") << "Dump declaration commands..." << std::endl
;
1124 // dump out any pending declaration commands
1125 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1126 Dump("declarations") << *d_dumpCommands
[i
];
1127 delete d_dumpCommands
[i
];
1129 d_dumpCommands
.clear();
1131 PROOF( ProofManager::currentPM()->setLogic(d_logic
); );
1133 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1134 ProofManager::currentPM()->getTheoryProofEngine()->
1135 finishRegisterTheory(d_theoryEngine
->theoryOf(id
));
1138 d_private
->finishInit();
1139 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl
;
1142 void SmtEngine::finalOptionsAreSet() {
1147 if(! d_logic
.isLocked()) {
1151 // finish initialization, create the prop engine, etc.
1154 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
1155 "The PropEngine has pushed but the SmtEngine "
1156 "hasn't finished initializing!" );
1158 d_fullyInited
= true;
1159 Assert(d_logic
.isLocked());
1161 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
1162 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
1165 void SmtEngine::shutdown() {
1168 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
1172 // check to see if a postsolve() is pending
1173 if(d_needPostsolve
) {
1174 d_theoryEngine
->postsolve();
1175 d_needPostsolve
= false;
1178 if(d_propEngine
!= NULL
) {
1179 d_propEngine
->shutdown();
1181 if(d_theoryEngine
!= NULL
) {
1182 d_theoryEngine
->shutdown();
1184 if(d_decisionEngine
!= NULL
) {
1185 d_decisionEngine
->shutdown();
1189 SmtEngine::~SmtEngine()
1191 SmtScope
smts(this);
1196 // global push/pop around everything, to ensure proper destruction
1197 // of context-dependent data structures
1198 d_context
->popto(0);
1199 d_userContext
->popto(0);
1201 if(d_assignments
!= NULL
) {
1202 d_assignments
->deleteSelf();
1205 if(d_assertionList
!= NULL
) {
1206 d_assertionList
->deleteSelf();
1209 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1210 delete d_dumpCommands
[i
];
1211 d_dumpCommands
[i
] = NULL
;
1213 d_dumpCommands
.clear();
1215 DeleteAndClearCommandVector(d_modelGlobalCommands
);
1217 if(d_modelCommands
!= NULL
) {
1218 d_modelCommands
->deleteSelf();
1221 d_definedFunctions
->deleteSelf();
1222 d_fmfRecFunctionsDefined
->deleteSelf();
1224 //destroy all passes before destroying things that they refer to
1225 d_private
->unregisterPreprocessingPasses();
1227 delete d_theoryEngine
;
1228 d_theoryEngine
= NULL
;
1229 delete d_propEngine
;
1230 d_propEngine
= NULL
;
1231 delete d_decisionEngine
;
1232 d_decisionEngine
= NULL
;
1235 // d_proofManager is always created when proofs are enabled at configure time.
1236 // Becuase of this, this code should not be wrapped in PROOF() which
1237 // additionally checks flags such as options::proof().
1239 delete d_proofManager
;
1240 d_proofManager
= NULL
;
1245 delete d_statisticsRegistry
;
1246 d_statisticsRegistry
= NULL
;
1251 delete d_userContext
;
1252 d_userContext
= NULL
;
1259 } catch(Exception
& e
) {
1260 Warning() << "CVC4 threw an exception during cleanup." << endl
1265 void SmtEngine::setLogic(const LogicInfo
& logic
)
1267 SmtScope
smts(this);
1269 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1270 "finished initializing.");
1276 void SmtEngine::setLogic(const std::string
& s
)
1278 SmtScope
smts(this);
1280 setLogic(LogicInfo(s
));
1281 } catch(IllegalArgumentException
& e
) {
1282 throw LogicException(e
.what());
1286 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1287 LogicInfo
SmtEngine::getLogicInfo() const {
1290 void SmtEngine::setLogicInternal()
1292 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1293 " finished initializing for this run");
1297 void SmtEngine::setDefaults() {
1298 Random::getRandom().setSeed(options::seed());
1299 // Language-based defaults
1300 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1302 options::bitvectorDivByZeroConst
.set(
1303 language::isInputLang_smt2_6(options::inputLanguage()));
1305 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1307 if (!options::ceGuidedInst
.wasSetByUser())
1309 options::ceGuidedInst
.set(true);
1311 // must use Ferrante/Rackoff for real arithmetic
1312 if (!options::cbqiMidpoint
.wasSetByUser())
1314 options::cbqiMidpoint
.set(true);
1319 // cannot use sygus repair constants
1320 options::sygusRepairConst
.set(false);
1323 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
1325 if (options::incrementalSolving())
1327 if (options::incrementalSolving
.wasSetByUser())
1329 throw OptionException(std::string(
1330 "Eager bit-blasting does not currently support incremental mode. "
1331 "Try --bitblast=lazy"));
1333 Notice() << "SmtEngine: turning off incremental to support eager "
1334 << "bit-blasting" << endl
;
1335 setOption("incremental", SExpr("false"));
1337 if (options::produceModels()
1338 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1339 || d_logic
.isTheoryEnabled(THEORY_UF
)))
1341 if (options::bitblastMode
.wasSetByUser()
1342 || options::produceModels
.wasSetByUser())
1344 throw OptionException(std::string(
1345 "Eager bit-blasting currently does not support model generation "
1346 "for the combination of bit-vectors with arrays or uinterpreted "
1347 "functions. Try --bitblast=lazy"));
1349 Notice() << "SmtEngine: setting bit-blast mode to lazy to support model"
1350 << "generation" << endl
;
1351 setOption("bitblastMode", SExpr("lazy"));
1355 if(options::forceLogicString
.wasSetByUser()) {
1356 d_logic
= LogicInfo(options::forceLogicString());
1357 }else if (options::solveIntAsBV() > 0) {
1358 d_logic
= LogicInfo("QF_BV");
1359 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1360 d_logic
= LogicInfo("QF_NIA");
1361 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1362 d_logic
.getLogicString() == "QF_ABV") &&
1363 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1364 d_logic
= LogicInfo("QF_BV");
1368 /* - disabled for 1.4 release [MGD 2014.06.25]
1369 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1370 if(! options::stringExp.wasSetByUser()) {
1371 options::stringExp.set( true );
1372 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1377 if(options::stringExp()) {
1378 if( !d_logic
.isQuantified() ) {
1379 d_logic
= d_logic
.getUnlockedCopy();
1380 d_logic
.enableQuantifiers();
1382 Trace("smt") << "turning on quantifier logic, for strings-exp"
1385 if(! options::fmfBound
.wasSetByUser()) {
1386 options::fmfBound
.set( true );
1387 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1389 if(! options::fmfInstEngine
.wasSetByUser()) {
1390 options::fmfInstEngine
.set( true );
1391 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1394 if(! options::rewriteDivk.wasSetByUser()) {
1395 options::rewriteDivk.set( true );
1396 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1399 if(! options::stringFMF.wasSetByUser()) {
1400 options::stringFMF.set( true );
1401 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1406 // sygus inference may require datatypes
1407 if (options::sygusInference())
1409 d_logic
= d_logic
.getUnlockedCopy();
1410 d_logic
.enableTheory(THEORY_DATATYPES
);
1414 if ((options::checkModels() || options::checkSynthSol())
1415 && !options::produceAssertions())
1417 Notice() << "SmtEngine: turning on produce-assertions to support "
1418 << "check-models or check-synth-sol." << endl
;
1419 setOption("produce-assertions", SExpr("true"));
1422 if (options::unsatCores() || options::proof())
1424 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE
)
1426 if (options::simplificationMode
.wasSetByUser())
1428 throw OptionException(
1429 "simplification not supported with unsat cores/proofs");
1431 Notice() << "SmtEngine: turning off simplification to support unsat "
1434 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1437 if (options::unconstrainedSimp())
1439 if (options::unconstrainedSimp
.wasSetByUser())
1441 throw OptionException(
1442 "unconstrained simplification not supported with unsat "
1445 Notice() << "SmtEngine: turning off unconstrained simplification to "
1446 "support unsat cores/proofs"
1448 options::unconstrainedSimp
.set(false);
1451 if (options::pbRewrites())
1453 if (options::pbRewrites
.wasSetByUser())
1455 throw OptionException(
1456 "pseudoboolean rewrites not supported with unsat cores/proofs");
1458 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support "
1459 "unsat cores/proofs"
1461 setOption("pb-rewrites", false);
1464 if (options::sortInference())
1466 if (options::sortInference
.wasSetByUser())
1468 throw OptionException(
1469 "sort inference not supported with unsat cores/proofs");
1471 Notice() << "SmtEngine: turning off sort inference to support unsat "
1474 options::sortInference
.set(false);
1477 if (options::preSkolemQuant())
1479 if (options::preSkolemQuant
.wasSetByUser())
1481 throw OptionException(
1482 "pre-skolemization not supported with unsat cores/proofs");
1484 Notice() << "SmtEngine: turning off pre-skolemization to support unsat "
1487 options::preSkolemQuant
.set(false);
1490 if (options::bitvectorToBool())
1492 if (options::bitvectorToBool
.wasSetByUser())
1494 throw OptionException(
1495 "bv-to-bool not supported with unsat cores/proofs");
1497 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat "
1500 options::bitvectorToBool
.set(false);
1503 if (options::boolToBitvector())
1505 if (options::boolToBitvector
.wasSetByUser())
1507 throw OptionException(
1508 "bool-to-bv not supported with unsat cores/proofs");
1510 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat "
1513 options::boolToBitvector
.set(false);
1516 if (options::bvIntroducePow2())
1518 if (options::bvIntroducePow2
.wasSetByUser())
1520 throw OptionException(
1521 "bv-intro-pow2 not supported with unsat cores/proofs");
1523 Notice() << "SmtEngine: turning off bv-intro-pow2 to support "
1524 "unsat-cores/proofs"
1526 setOption("bv-intro-pow2", false);
1529 if (options::repeatSimp())
1531 if (options::repeatSimp
.wasSetByUser())
1533 throw OptionException(
1534 "repeat-simp not supported with unsat cores/proofs");
1536 Notice() << "SmtEngine: turning off repeat-simp to support unsat "
1539 setOption("repeat-simp", false);
1542 if (options::globalNegate())
1544 if (options::globalNegate
.wasSetByUser())
1546 throw OptionException(
1547 "global-negate not supported with unsat cores/proofs");
1549 Notice() << "SmtEngine: turning off global-negate to support unsat "
1552 setOption("global-negate", false);
1557 // by default, nonclausal simplification is off for QF_SAT
1558 if (!options::simplificationMode
.wasSetByUser())
1560 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1561 Trace("smt") << "setting simplification mode to <"
1562 << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1563 // simplification=none works better for SMT LIB benchmarks with
1564 // quantifiers, not others options::simplificationMode.set(qf_sat ||
1565 // quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1566 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
1567 : SIMPLIFICATION_MODE_BATCH
);
1571 if (options::cbqiBv() && d_logic
.isQuantified())
1573 if(options::boolToBitvector
.wasSetByUser()) {
1574 throw OptionException(
1575 "bool-to-bv not supported with CBQI BV for quantified logics");
1577 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1579 options::boolToBitvector
.set(false);
1582 // cases where we need produce models
1583 if (!options::produceModels()
1584 && (options::produceAssignments() || options::sygusRewSynthCheck()
1585 || options::sygusRepairConst()))
1587 Notice() << "SmtEngine: turning on produce-models" << endl
;
1588 setOption("produce-models", SExpr("true"));
1591 // Set the options for the theoryOf
1592 if(!options::theoryOfMode
.wasSetByUser()) {
1593 if(d_logic
.isSharingEnabled() &&
1594 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1595 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1596 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1597 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1598 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1602 // strings require LIA, UF; widen the logic
1603 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1604 LogicInfo
log(d_logic
.getUnlockedCopy());
1605 // Strings requires arith for length constraints, and also UF
1606 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1607 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1608 log
.enableTheory(THEORY_UF
);
1610 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1611 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1612 log
.enableTheory(THEORY_ARITH
);
1613 log
.enableIntegers();
1614 log
.arithOnlyLinear();
1619 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1620 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1621 LogicInfo
log(d_logic
.getUnlockedCopy());
1622 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1623 log
.enableTheory(THEORY_UF
);
1629 // by default, symmetry breaker is on only for QF_UF
1630 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1631 bool qf_uf
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified()
1632 && !options::proof() && !options::unsatCores();
1633 Trace("smt") << "setting uf symmetry breaker to " << qf_uf
<< endl
;
1634 options::ufSymmetryBreaker
.set(qf_uf
);
1637 // If in arrays, set the UF handler to arrays
1638 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1639 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1640 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1642 Theory::setUninterpretedSortOwner(THEORY_UF
);
1645 // Turn on ite simplification for QF_LIA and QF_AUFBV
1646 // WARNING: These checks match much more than just QF_AUFBV and
1647 // QF_LIA logics. --K [2014/10/15]
1648 if(! options::doITESimp
.wasSetByUser()) {
1649 bool qf_aufbv
= !d_logic
.isQuantified() &&
1650 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1651 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1652 d_logic
.isTheoryEnabled(THEORY_BV
);
1653 bool qf_lia
= !d_logic
.isQuantified() &&
1654 d_logic
.isPure(THEORY_ARITH
) &&
1655 d_logic
.isLinear() &&
1656 !d_logic
.isDifferenceLogic() &&
1657 !d_logic
.areRealsUsed();
1659 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1660 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1661 options::doITESimp
.set(iteSimp
);
1663 if(! options::compressItes
.wasSetByUser() ){
1664 bool qf_lia
= !d_logic
.isQuantified() &&
1665 d_logic
.isPure(THEORY_ARITH
) &&
1666 d_logic
.isLinear() &&
1667 !d_logic
.isDifferenceLogic() &&
1668 !d_logic
.areRealsUsed();
1670 bool compressIte
= qf_lia
;
1671 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1672 options::compressItes
.set(compressIte
);
1674 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1675 bool qf_aufbv
= !d_logic
.isQuantified() &&
1676 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1677 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1678 d_logic
.isTheoryEnabled(THEORY_BV
);
1680 bool withCare
= qf_aufbv
;
1681 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1682 options::simplifyWithCareEnabled
.set(withCare
);
1684 // Turn off array eager index splitting for QF_AUFLIA
1685 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1686 if (not d_logic
.isQuantified() &&
1687 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1688 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1689 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1690 Trace("smt") << "setting array eager index splitting to false" << endl
;
1691 options::arraysEagerIndexSplitting
.set(false);
1694 // Turn on model-based arrays for QF_AX (unless models are enabled)
1695 // if(! options::arraysModelBased.wasSetByUser()) {
1696 // if (not d_logic.isQuantified() &&
1697 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1698 // d_logic.isPure(THEORY_ARRAYS) &&
1699 // !options::produceModels() &&
1700 // !options::checkModels()) {
1701 // Trace("smt") << "turning on model-based array solver" << endl;
1702 // options::arraysModelBased.set(true);
1705 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1706 if(! options::repeatSimp
.wasSetByUser()) {
1707 bool repeatSimp
= !d_logic
.isQuantified() &&
1708 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1709 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1710 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1711 !options::unsatCores();
1712 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1713 options::repeatSimp
.set(repeatSimp
);
1715 // Turn on unconstrained simplification for QF_AUFBV
1716 if(!options::unconstrainedSimp
.wasSetByUser() ||
1717 options::incrementalSolving()) {
1718 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1719 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1720 bool uncSimp
= !options::incrementalSolving() &&
1721 !d_logic
.isQuantified() &&
1722 !options::produceModels() &&
1723 !options::produceAssignments() &&
1724 !options::checkModels() &&
1725 !options::unsatCores() &&
1726 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && d_logic
.isTheoryEnabled(THEORY_BV
));
1727 Trace("smt") << "setting unconstrained simplification to " << uncSimp
<< endl
;
1728 options::unconstrainedSimp
.set(uncSimp
);
1730 // Unconstrained simp currently does *not* support model generation
1731 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1732 if (options::produceModels()) {
1733 if (options::produceModels
.wasSetByUser()) {
1734 throw OptionException("Cannot use unconstrained-simp with model generation.");
1736 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1737 setOption("produce-models", SExpr("false"));
1739 if (options::produceAssignments()) {
1740 if (options::produceAssignments
.wasSetByUser()) {
1741 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1743 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1744 setOption("produce-assignments", SExpr("false"));
1746 if (options::checkModels()) {
1747 if (options::checkModels
.wasSetByUser()) {
1748 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1750 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1751 setOption("check-models", SExpr("false"));
1755 if (! options::bvEagerExplanations
.wasSetByUser() &&
1756 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1757 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1758 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1759 options::bvEagerExplanations
.set(true);
1762 if( !options::bitvectorEqualitySolver() ){
1763 Trace("smt") << "disabling bvLazyRewriteExtf since equality solver is disabled" << endl
;
1764 options::bvLazyRewriteExtf
.set(false);
1767 // Turn on arith rewrite equalities only for pure arithmetic
1768 if(! options::arithRewriteEq
.wasSetByUser()) {
1769 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1770 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1771 options::arithRewriteEq
.set(arithRewriteEq
);
1773 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1774 int16_t heuristicPivots
= 5;
1775 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1776 if(d_logic
.isDifferenceLogic()) {
1777 heuristicPivots
= -1;
1778 } else if(!d_logic
.areIntegersUsed()) {
1779 heuristicPivots
= 0;
1782 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1783 options::arithHeuristicPivots
.set(heuristicPivots
);
1785 if(! options::arithPivotThreshold
.wasSetByUser()){
1786 uint16_t pivotThreshold
= 2;
1787 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1788 if(d_logic
.isDifferenceLogic()){
1789 pivotThreshold
= 16;
1792 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1793 options::arithPivotThreshold
.set(pivotThreshold
);
1795 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1796 int16_t varOrderPivots
= -1;
1797 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1798 varOrderPivots
= 200;
1800 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1801 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1803 // Turn off early theory preprocessing if arithRewriteEq is on
1804 if (options::arithRewriteEq()) {
1805 d_earlyTheoryPP
= false;
1807 if (d_logic
.isPure(THEORY_ARITH
) && !d_logic
.areRealsUsed())
1809 if (!options::nlExtTangentPlanesInterleave
.wasSetByUser())
1811 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl
;
1812 options::nlExtTangentPlanesInterleave
.set(true);
1816 // Set decision mode based on logic (if not set by user)
1817 if(!options::decisionMode
.wasSetByUser()) {
1818 decision::DecisionMode decMode
=
1820 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1822 (not d_logic
.isQuantified() &&
1823 d_logic
.isPure(THEORY_BV
)
1825 // QF_AUFBV or QF_ABV or QF_UFBV
1826 (not d_logic
.isQuantified() &&
1827 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) ||
1828 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1829 d_logic
.isTheoryEnabled(THEORY_BV
)
1831 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1832 (not d_logic
.isQuantified() &&
1833 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1834 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1835 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1838 (not d_logic
.isQuantified() &&
1839 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1842 d_logic
.isQuantified() ||
1844 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1845 ? decision::DECISION_STRATEGY_JUSTIFICATION
1846 : decision::DECISION_STRATEGY_INTERNAL
1851 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1853 (not d_logic
.isQuantified() &&
1854 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1855 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1856 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1859 (not d_logic
.isQuantified() &&
1860 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1865 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1866 options::decisionMode
.set(decMode
);
1867 options::decisionStopOnly
.set(stoponly
);
1869 if( options::incrementalSolving() ){
1870 //disable modes not supported by incremental
1871 options::sortInference
.set( false );
1872 options::ufssFairnessMonotone
.set( false );
1873 options::quantEpr
.set( false );
1874 options::globalNegate
.set(false);
1876 if( d_logic
.hasCardinalityConstraints() ){
1877 //must have finite model finding on
1878 options::finiteModelFind
.set( true );
1881 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1882 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1883 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1884 options::instWhenStrictInterleave
.set( false );
1888 //local theory extensions
1889 if( options::localTheoryExt() ){
1890 if( !options::instMaxLevel
.wasSetByUser() ){
1891 options::instMaxLevel
.set( 0 );
1894 if( options::instMaxLevel()!=-1 ){
1895 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1896 options::cbqi
.set(false);
1898 //track instantiations?
1899 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1900 options::trackInstLemmas
.set( true );
1903 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1904 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1905 options::fmfBound
.set( true );
1907 //now have determined whether fmfBoundInt is on/off
1908 //apply fmfBoundInt options
1909 if( options::fmfBound() ){
1910 //must have finite model finding on
1911 options::finiteModelFind
.set( true );
1912 if( ! options::mbqiMode
.wasSetByUser() ||
1913 ( options::mbqiMode()!=quantifiers::MBQI_NONE
&&
1914 options::mbqiMode()!=quantifiers::MBQI_FMC
&&
1915 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL
) ){
1916 //if bounded integers are set, use no MBQI by default
1917 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1919 if( ! options::prenexQuant
.wasSetByUser() ){
1920 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1923 if( options::ufHo() ){
1924 //if higher-order, then current variants of model-based instantiation cannot be used
1925 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1926 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1929 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1930 if( !d_logic
.isPure(THEORY_UF
) ){
1931 //MBQI_ABS is only supported in pure quantified UF
1932 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1935 if( options::fmfFunWellDefinedRelevant() ){
1936 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1937 options::fmfFunWellDefined
.set( true );
1940 if( options::fmfFunWellDefined() ){
1941 if( !options::finiteModelFind
.wasSetByUser() ){
1942 options::finiteModelFind
.set( true );
1946 if( options::quantEpr() ){
1947 if( !options::preSkolemQuant
.wasSetByUser() ){
1948 options::preSkolemQuant
.set( true );
1952 //now, have determined whether finite model find is on/off
1953 //apply finite model finding options
1954 if( options::finiteModelFind() ){
1955 //apply conservative quantifiers splitting
1956 if( !options::quantDynamicSplit
.wasSetByUser() ){
1957 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1959 //do not eliminate extended arithmetic symbols from quantified formulas
1960 if( !options::elimExtArithQuant
.wasSetByUser() ){
1961 options::elimExtArithQuant
.set( false );
1963 if( !options::eMatching
.wasSetByUser() ){
1964 options::eMatching
.set( options::fmfInstEngine() );
1966 if( !options::instWhenMode
.wasSetByUser() ){
1967 //instantiate only on last call
1968 if( options::eMatching() ){
1969 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1972 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1973 if( !options::preSkolemQuant
.wasSetByUser() ){
1974 options::preSkolemQuant
.set( true );
1976 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1977 options::preSkolemQuantNested
.set( true );
1979 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1980 options::fmfOneInstPerRound
.set( true );
1985 //apply counterexample guided instantiation options
1986 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1987 if (options::sygusInference())
1989 if (!options::ceGuidedInst
.wasSetByUser())
1991 options::ceGuidedInst
.set(true);
1993 // optimization: apply preskolemization, makes it succeed more often
1994 if (!options::preSkolemQuant
.wasSetByUser())
1996 options::preSkolemQuant
.set(true);
1998 if (!options::preSkolemQuantNested
.wasSetByUser())
2000 options::preSkolemQuantNested
.set(true);
2003 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
2004 if( !options::ceGuidedInst
.wasSetByUser() ){
2005 options::ceGuidedInst
.set( true );
2008 if( options::ceGuidedInst() ){
2009 //counterexample-guided instantiation for sygus
2010 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
2011 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
2013 if( !options::quantConflictFind
.wasSetByUser() ){
2014 options::quantConflictFind
.set( false );
2016 if( !options::instNoEntail
.wasSetByUser() ){
2017 options::instNoEntail
.set( false );
2019 if (options::sygusRew())
2021 options::sygusRewSynth
.set(true);
2022 options::sygusRewVerify
.set(true);
2024 if (options::sygusRewSynth() || options::sygusRewVerify())
2026 // rewrite rule synthesis implies that sygus stream must be true
2027 options::sygusStream
.set(true);
2029 if (options::sygusStream())
2031 // PBE and streaming modes are incompatible
2032 if (!options::sygusSymBreakPbe
.wasSetByUser())
2034 options::sygusSymBreakPbe
.set(false);
2036 if (!options::sygusUnifPbe
.wasSetByUser())
2038 options::sygusUnifPbe
.set(false);
2041 //do not allow partial functions
2042 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
2043 options::bitvectorDivByZeroConst
.set( true );
2045 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
2046 options::dtRewriteErrorSel
.set( true );
2049 if( !options::miniscopeQuant
.wasSetByUser() ){
2050 options::miniscopeQuant
.set( false );
2052 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
2053 options::miniscopeQuantFreeVar
.set( false );
2056 if( !options::rewriteDivk
.wasSetByUser()) {
2057 options::rewriteDivk
.set( true );
2060 if( !options::macrosQuant
.wasSetByUser()) {
2061 options::macrosQuant
.set( false );
2063 if( !options::cbqiPreRegInst
.wasSetByUser()) {
2064 options::cbqiPreRegInst
.set( true );
2067 //counterexample-guided instantiation for non-sygus
2068 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
2069 if( d_logic
.isQuantified() &&
2070 ( ( options::decisionMode()!=decision::DECISION_STRATEGY_INTERNAL
&&
2071 ( d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_BV
) ) ) ||
2072 d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
) ||
2073 options::cbqiAll() ) ){
2074 if( !options::cbqi
.wasSetByUser() ){
2075 options::cbqi
.set( true );
2077 // check whether we should apply full cbqi
2078 if (d_logic
.isPure(THEORY_BV
))
2080 if (!options::cbqiFullEffort
.wasSetByUser())
2082 options::cbqiFullEffort
.set(true);
2086 if( options::cbqi() ){
2088 if( !options::rewriteDivk
.wasSetByUser()) {
2089 options::rewriteDivk
.set( true );
2091 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
2093 options::cbqiAll
.set( false );
2094 if( !options::quantConflictFind
.wasSetByUser() ){
2095 options::quantConflictFind
.set( false );
2097 if( !options::instNoEntail
.wasSetByUser() ){
2098 options::instNoEntail
.set( false );
2100 if( !options::instWhenMode
.wasSetByUser() && options::cbqiModel() ){
2101 //only instantiation should happen at last call when model is avaiable
2102 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
2105 // only supported in pure arithmetic or pure BV
2106 options::cbqiNestedQE
.set(false);
2109 if (options::cbqiNestedQE()
2110 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL
)
2112 // only complete with prenex = disj_normal or normal
2113 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
2115 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
2118 else if (options::globalNegate())
2120 if (!options::prenexQuant
.wasSetByUser())
2122 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
2126 //implied options...
2127 if( options::strictTriggers() ){
2128 if( !options::userPatternsQuant
.wasSetByUser() ){
2129 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
2132 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
2133 options::quantConflictFind
.set( true );
2135 if( options::cbqiNestedQE() ){
2136 options::prenexQuantUser
.set( true );
2137 if( !options::preSkolemQuant
.wasSetByUser() ){
2138 options::preSkolemQuant
.set( true );
2141 //for induction techniques
2142 if( options::quantInduction() ){
2143 if( !options::dtStcInduction
.wasSetByUser() ){
2144 options::dtStcInduction
.set( true );
2146 if( !options::intWfInduction
.wasSetByUser() ){
2147 options::intWfInduction
.set( true );
2150 if( options::dtStcInduction() ){
2151 //try to remove ITEs from quantified formulas
2152 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
2153 options::iteDtTesterSplitQuant
.set( true );
2155 if( !options::iteLiftQuant
.wasSetByUser() ){
2156 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
2159 if( options::intWfInduction() ){
2160 if( !options::purifyTriggers
.wasSetByUser() ){
2161 options::purifyTriggers
.set( true );
2164 if( options::conjectureNoFilter() ){
2165 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2166 options::conjectureFilterActiveTerms
.set( false );
2168 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2169 options::conjectureFilterCanonical
.set( false );
2171 if( !options::conjectureFilterModel
.wasSetByUser() ){
2172 options::conjectureFilterModel
.set( false );
2175 if( options::conjectureGenPerRound
.wasSetByUser() ){
2176 if( options::conjectureGenPerRound()>0 ){
2177 options::conjectureGen
.set( true );
2179 options::conjectureGen
.set( false );
2182 //can't pre-skolemize nested quantifiers without UF theory
2183 if( !d_logic
.isTheoryEnabled(THEORY_UF
) && options::preSkolemQuant() ){
2184 if( !options::preSkolemQuantNested
.wasSetByUser() ){
2185 options::preSkolemQuantNested
.set( false );
2188 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2189 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
2192 //until bugs 371,431 are fixed
2193 if( ! options::minisatUseElim
.wasSetByUser()){
2194 //AJR: cannot use minisat elim for new implementation of sets TODO: why?
2195 if( d_logic
.isTheoryEnabled(THEORY_SETS
) || d_logic
.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
2196 options::minisatUseElim
.set( false );
2199 else if (options::minisatUseElim()) {
2200 if (options::produceModels()) {
2201 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
2202 setOption("produce-models", SExpr("false"));
2204 if (options::produceAssignments()) {
2205 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2206 setOption("produce-assignments", SExpr("false"));
2208 if (options::checkModels()) {
2209 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2210 setOption("check-models", SExpr("false"));
2214 // For now, these array theory optimizations do not support model-building
2215 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2216 options::arraysOptimizeLinear
.set(false);
2217 options::arraysLazyRIntro1
.set(false);
2220 // Non-linear arithmetic does not support models unless nlExt is enabled
2221 if ((d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()
2222 && !options::nlExt())
2223 || options::globalNegate())
2225 std::string reason
=
2226 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2227 if (options::produceModels()) {
2228 if(options::produceModels
.wasSetByUser()) {
2229 throw OptionException(
2230 std::string("produce-model not supported with " + reason
));
2233 << "SmtEngine: turning off produce-models because unsupported for "
2235 setOption("produce-models", SExpr("false"));
2237 if (options::produceAssignments()) {
2238 if(options::produceAssignments
.wasSetByUser()) {
2239 throw OptionException(
2240 std::string("produce-assignments not supported with " + reason
));
2242 Warning() << "SmtEngine: turning off produce-assignments because "
2245 setOption("produce-assignments", SExpr("false"));
2247 if (options::checkModels()) {
2248 if(options::checkModels
.wasSetByUser()) {
2249 throw OptionException(
2250 std::string("check-models not supported with " + reason
));
2253 << "SmtEngine: turning off check-models because unsupported for "
2255 setOption("check-models", SExpr("false"));
2259 if(options::incrementalSolving() && options::proof()) {
2260 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl
;
2261 setOption("incremental", SExpr("false"));
2264 if (options::proof())
2266 if (options::bitvectorAlgebraicSolver())
2268 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2270 throw OptionException(
2271 "--bv-algebraic-solver is not supported with proofs");
2273 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2275 options::bitvectorAlgebraicSolver
.set(false);
2277 if (options::bitvectorEqualitySolver())
2279 if (options::bitvectorEqualitySolver
.wasSetByUser())
2281 throw OptionException("--bv-eq-solver is not supported with proofs");
2283 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2285 options::bitvectorEqualitySolver
.set(false);
2287 if (options::bitvectorInequalitySolver())
2289 if (options::bitvectorInequalitySolver
.wasSetByUser())
2291 throw OptionException(
2292 "--bv-inequality-solver is not supported with proofs");
2294 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2296 options::bitvectorInequalitySolver
.set(false);
2301 void SmtEngine::setProblemExtended(bool value
)
2303 d_problemExtended
= value
;
2304 if (value
) { d_assumptions
.clear(); }
2307 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2309 SmtScope
smts(this);
2311 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2313 if(Dump
.isOn("benchmark")) {
2314 if(key
== "status") {
2315 string s
= value
.getValue();
2316 BenchmarkStatus status
=
2317 (s
== "sat") ? SMT_SATISFIABLE
:
2318 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2319 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2321 Dump("benchmark") << SetInfoCommand(key
, value
);
2325 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2326 if(key
.length() > 5) {
2327 string prefix
= key
.substr(0, 5);
2328 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2329 string cvc4key
= key
.substr(5);
2330 if(cvc4key
== "logic") {
2331 if(! value
.isAtom()) {
2332 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2334 SmtScope
smts(this);
2335 d_logic
= value
.getValue();
2339 throw UnrecognizedOptionException();
2344 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2345 if(key
== "source" ||
2346 key
== "category" ||
2347 key
== "difficulty" ||
2351 } else if(key
== "name") {
2352 d_filename
= value
.getValue();
2354 } else if(key
== "smt-lib-version") {
2355 language::input::Language ilang
= language::input::LANG_AUTO
;
2356 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2357 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2358 value
.getValue() == "2" ||
2359 value
.getValue() == "2.0" ) {
2360 ilang
= language::input::LANG_SMTLIB_V2_0
;
2361 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2362 value
.getValue() == "2.5" ) {
2363 ilang
= language::input::LANG_SMTLIB_V2_5
;
2364 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2365 value
.getValue() == "2.6" ) {
2366 ilang
= language::input::LANG_SMTLIB_V2_6
;
2368 else if (value
.getValue() == "2.6.1")
2370 ilang
= language::input::LANG_SMTLIB_V2_6_1
;
2374 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2375 throw UnrecognizedOptionException();
2377 options::inputLanguage
.set(ilang
);
2378 // also update the output language
2379 if (!options::outputLanguage
.wasSetByUser())
2381 language::output::Language olang
= language::toOutputLanguage(ilang
);
2382 if (options::outputLanguage() != olang
)
2384 options::outputLanguage
.set(olang
);
2385 *options::out() << language::SetLanguage(olang
);
2389 } else if(key
== "status") {
2391 if(value
.isAtom()) {
2392 s
= value
.getValue();
2394 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2395 throw OptionException("argument to (set-info :status ..) must be "
2396 "`sat' or `unsat' or `unknown'");
2398 d_status
= Result(s
, d_filename
);
2401 throw UnrecognizedOptionException();
2404 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2406 SmtScope
smts(this);
2408 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2409 if(key
== "all-statistics") {
2410 vector
<SExpr
> stats
;
2411 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2412 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2415 v
.push_back((*i
).first
);
2416 v
.push_back((*i
).second
);
2419 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2420 i
!= d_statisticsRegistry
->end();
2423 v
.push_back((*i
).first
);
2424 v
.push_back((*i
).second
);
2427 return SExpr(stats
);
2428 } else if(key
== "error-behavior") {
2429 // immediate-exit | continued-execution
2430 if( options::continuedExecution() || options::interactive() ) {
2431 return SExpr(SExpr::Keyword("continued-execution"));
2433 return SExpr(SExpr::Keyword("immediate-exit"));
2435 } else if(key
== "name") {
2436 return SExpr(Configuration::getName());
2437 } else if(key
== "version") {
2438 return SExpr(Configuration::getVersionString());
2439 } else if(key
== "authors") {
2440 return SExpr(Configuration::about());
2441 } else if(key
== "status") {
2442 // sat | unsat | unknown
2443 switch(d_status
.asSatisfiabilityResult().isSat()) {
2445 return SExpr(SExpr::Keyword("sat"));
2447 return SExpr(SExpr::Keyword("unsat"));
2449 return SExpr(SExpr::Keyword("unknown"));
2451 } else if(key
== "reason-unknown") {
2452 if(!d_status
.isNull() && d_status
.isUnknown()) {
2454 ss
<< d_status
.whyUnknown();
2455 string s
= ss
.str();
2456 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2457 return SExpr(SExpr::Keyword(s
));
2459 throw ModalException("Can't get-info :reason-unknown when the "
2460 "last result wasn't unknown!");
2462 } else if(key
== "assertion-stack-levels") {
2463 AlwaysAssert(d_userLevels
.size() <=
2464 std::numeric_limits
<unsigned long int>::max());
2465 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2466 } else if(key
== "all-options") {
2467 // get the options, like all-statistics
2468 std::vector
< std::vector
<std::string
> > current_options
=
2469 Options::current()->getOptions();
2470 return SExpr::parseListOfListOfAtoms(current_options
);
2472 throw UnrecognizedOptionException();
2476 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2478 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2479 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2481 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2482 << "definition of function " << func
<< ", formal\n"
2483 << " " << *i
<< "\n"
2484 << "has kind " << (*i
).getKind();
2485 throw TypeCheckingException(func
, ss
.str());
2490 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2491 const std::vector
<Expr
>& formals
,
2494 Type formulaType
= formula
.getType(options::typeChecking());
2495 Type funcType
= func
.getType();
2496 // We distinguish here between definitions of constants and functions,
2497 // because the type checking for them is subtly different. Perhaps we
2498 // should instead have SmtEngine::defineFunction() and
2499 // SmtEngine::defineConstant() for better clarity, although then that
2500 // doesn't match the SMT-LIBv2 standard...
2501 if(formals
.size() > 0) {
2502 Type rangeType
= FunctionType(funcType
).getRangeType();
2503 if(! formulaType
.isComparableTo(rangeType
)) {
2505 ss
<< "Type of defined function does not match its declaration\n"
2506 << "The function : " << func
<< "\n"
2507 << "Declared type : " << rangeType
<< "\n"
2508 << "The body : " << formula
<< "\n"
2509 << "Body type : " << formulaType
;
2510 throw TypeCheckingException(func
, ss
.str());
2513 if(! formulaType
.isComparableTo(funcType
)) {
2515 ss
<< "Declared type of defined constant does not match its definition\n"
2516 << "The constant : " << func
<< "\n"
2517 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2518 << "The definition : " << formula
<< "\n"
2519 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2520 throw TypeCheckingException(func
, ss
.str());
2525 void SmtEngine::defineFunction(Expr func
,
2526 const std::vector
<Expr
>& formals
,
2529 SmtScope
smts(this);
2531 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2532 debugCheckFormals(formals
, func
);
2535 ss
<< language::SetLanguage(
2536 language::SetLanguage::getLanguage(Dump
.getStream()))
2538 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2539 addToModelCommandAndDump(
2540 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2542 PROOF(if (options::checkUnsatCores()) {
2543 d_defineCommands
.push_back(c
.clone());
2547 debugCheckFunctionBody(formula
, formals
, func
);
2549 // Substitute out any abstract values in formula
2551 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2553 TNode funcNode
= func
.getTNode();
2554 vector
<Node
> formalsNodes
;
2555 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2556 iend
= formals
.end();
2559 formalsNodes
.push_back((*i
).getNode());
2561 TNode formNode
= form
.getTNode();
2562 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2563 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2564 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2565 // d_haveAdditions = true;
2566 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2567 d_definedFunctions
->insert(funcNode
, def
);
2570 void SmtEngine::defineFunctionsRec(
2571 const std::vector
<Expr
>& funcs
,
2572 const std::vector
<std::vector
<Expr
> >& formals
,
2573 const std::vector
<Expr
>& formulas
)
2575 SmtScope
smts(this);
2576 finalOptionsAreSet();
2578 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2580 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2583 ss
<< "Number of functions, formals, and function bodies passed to "
2584 "defineFunctionsRec do not match:"
2586 << " #functions : " << funcs
.size() << "\n"
2587 << " #arg lists : " << formals
.size() << "\n"
2588 << " #function bodies : " << formulas
.size() << "\n";
2589 throw ModalException(ss
.str());
2591 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2593 // check formal argument list
2594 debugCheckFormals(formals
[i
], funcs
[i
]);
2596 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2599 if (Dump
.isOn("raw-benchmark"))
2601 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2604 ExprManager
* em
= getExprManager();
2605 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2607 // we assert a quantified formula
2609 // make the function application
2610 if (formals
[i
].empty())
2612 // it has no arguments
2613 func_app
= funcs
[i
];
2617 std::vector
<Expr
> children
;
2618 children
.push_back(funcs
[i
]);
2619 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2620 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2622 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2623 if (!formals
[i
].empty())
2625 // set the attribute to denote this is a function definition
2626 std::string
attr_name("fun-def");
2627 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2628 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2629 std::vector
<Expr
> expr_values
;
2630 std::string str_value
;
2631 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2632 // make the quantified formula
2633 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2634 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2636 // assert the quantified formula
2637 // notice we don't call assertFormula directly, since this would
2638 // duplicate the output on raw-benchmark.
2639 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2640 if (d_assertionList
!= NULL
)
2642 d_assertionList
->push_back(e
);
2644 d_private
->addFormula(e
.getNode(), false);
2648 void SmtEngine::defineFunctionRec(Expr func
,
2649 const std::vector
<Expr
>& formals
,
2652 std::vector
<Expr
> funcs
;
2653 funcs
.push_back(func
);
2654 std::vector
<std::vector
<Expr
> > formals_multi
;
2655 formals_multi
.push_back(formals
);
2656 std::vector
<Expr
> formulas
;
2657 formulas
.push_back(formula
);
2658 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2661 bool SmtEngine::isDefinedFunction( Expr func
){
2662 Node nf
= Node::fromExpr( func
);
2663 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2664 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2667 void SmtEnginePrivate::finishInit() {
2668 d_preprocessingPassContext
.reset(new PreprocessingPassContext(&d_smt
));
2669 // TODO: register passes here (this will likely change when we add support for
2670 // actually assembling preprocessing pipelines).
2671 std::unique_ptr
<BoolToBV
> boolToBv(
2672 new BoolToBV(d_preprocessingPassContext
.get()));
2673 std::unique_ptr
<BvAbstraction
> bvAbstract(
2674 new BvAbstraction(d_preprocessingPassContext
.get()));
2675 std::unique_ptr
<BVAckermann
> bvAckermann(
2676 new BVAckermann(d_preprocessingPassContext
.get()));
2677 std::unique_ptr
<BVGauss
> bvGauss(
2678 new BVGauss(d_preprocessingPassContext
.get()));
2679 std::unique_ptr
<BvIntroPow2
> bvIntroPow2(
2680 new BvIntroPow2(d_preprocessingPassContext
.get()));
2681 std::unique_ptr
<BVToBool
> bvToBool(
2682 new BVToBool(d_preprocessingPassContext
.get()));
2683 std::unique_ptr
<IntToBV
> intToBV(
2684 new IntToBV(d_preprocessingPassContext
.get()));
2685 std::unique_ptr
<PseudoBooleanProcessor
> pbProc(
2686 new PseudoBooleanProcessor(d_preprocessingPassContext
.get()));
2687 std::unique_ptr
<RealToInt
> realToInt(
2688 new RealToInt(d_preprocessingPassContext
.get()));
2689 std::unique_ptr
<StaticLearning
> staticLearning(
2690 new StaticLearning(d_preprocessingPassContext
.get()));
2691 std::unique_ptr
<SymBreakerPass
> sbProc(
2692 new SymBreakerPass(d_preprocessingPassContext
.get()));
2693 d_preprocessingPassRegistry
.registerPass("bool-to-bv", std::move(boolToBv
));
2694 d_preprocessingPassRegistry
.registerPass("bv-abstraction",
2695 std::move(bvAbstract
));
2696 d_preprocessingPassRegistry
.registerPass("bv-ackermann",
2697 std::move(bvAckermann
));
2698 d_preprocessingPassRegistry
.registerPass("bv-gauss", std::move(bvGauss
));
2699 d_preprocessingPassRegistry
.registerPass("bv-intro-pow2",
2700 std::move(bvIntroPow2
));
2701 d_preprocessingPassRegistry
.registerPass("bv-to-bool", std::move(bvToBool
));
2702 d_preprocessingPassRegistry
.registerPass("int-to-bv", std::move(intToBV
));
2703 d_preprocessingPassRegistry
.registerPass("pseudo-boolean-processor",
2705 d_preprocessingPassRegistry
.registerPass("real-to-int", std::move(realToInt
));
2706 d_preprocessingPassRegistry
.registerPass("static-learning",
2707 std::move(staticLearning
));
2708 d_preprocessingPassRegistry
.registerPass("sym-break", std::move(sbProc
));
2711 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2713 stack
< triple
<Node
, Node
, bool> > worklist
;
2715 worklist
.push(make_triple(Node(n
), Node(n
), false));
2716 // The worklist is made of triples, each is input / original node then the output / rewritten node
2717 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2721 spendResource(options::preprocessStep());
2722 n
= worklist
.top().first
; // n is the input / original
2723 Node node
= worklist
.top().second
; // node is the output / result
2724 bool childrenPushed
= worklist
.top().third
;
2727 // Working downwards
2728 if(!childrenPushed
) {
2729 Kind k
= n
.getKind();
2731 // we can short circuit (variable) leaves
2733 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2734 if(i
!= d_smt
.d_definedFunctions
->end()) {
2735 // replacement must be closed
2736 if((*i
).second
.getFormals().size() > 0) {
2737 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2740 // don't bother putting in the cache
2741 result
.push((*i
).second
.getFormula());
2744 // don't bother putting in the cache
2749 // maybe it's in the cache
2750 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2751 if(cacheHit
!= cache
.end()) {
2752 TNode ret
= (*cacheHit
).second
;
2753 result
.push(ret
.isNull() ? n
: ret
);
2757 // otherwise expand it
2758 bool doExpand
= k
== kind::APPLY
;
2760 // options that assign substitutions to APPLY_UF
2761 if (options::macrosQuant() || options::sygusInference())
2763 //expand if we have inferred an operator corresponds to a defined function
2764 doExpand
= k
==kind::APPLY_UF
&& d_smt
.isDefinedFunction( n
.getOperator().toExpr() );
2768 vector
<Node
> formals
;
2770 if( n
.getOperator().getKind() == kind::LAMBDA
){
2771 TNode op
= n
.getOperator();
2773 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2774 formals
.push_back( op
[0][i
] );
2778 // application of a user-defined symbol
2779 TNode func
= n
.getOperator();
2780 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2781 if(i
== d_smt
.d_definedFunctions
->end()) {
2782 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2784 DefinedFunction def
= (*i
).second
;
2785 formals
= def
.getFormals();
2787 if(Debug
.isOn("expand")) {
2788 Debug("expand") << "found: " << n
<< endl
;
2789 Debug("expand") << " func: " << func
<< endl
;
2790 string name
= func
.getAttribute(expr::VarNameAttr());
2791 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2793 if(Debug
.isOn("expand")) {
2794 Debug("expand") << " defn: " << def
.getFunction() << endl
2796 if(formals
.size() > 0) {
2797 copy( formals
.begin(), formals
.end() - 1,
2798 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2799 Debug("expand") << formals
.back();
2801 Debug("expand") << "]" << endl
2802 << " " << def
.getFunction().getType() << endl
2803 << " " << def
.getFormula() << endl
;
2806 fm
= def
.getFormula();
2809 Node instance
= fm
.substitute(formals
.begin(),
2812 n
.begin() + formals
.size());
2813 Debug("expand") << "made : " << instance
<< endl
;
2815 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2816 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2817 result
.push(expanded
);
2820 } else if(! expandOnly
) {
2821 // do not do any theory stuff if expandOnly is true
2823 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2826 LogicRequest
req(d_smt
);
2827 node
= t
->expandDefinition(req
, n
);
2830 // the partial functions can fall through, in which case we still
2831 // consider their children
2832 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
2834 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2835 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
2840 // Reconstruct the node from it's (now rewritten) children on the stack
2842 Debug("expand") << "cons : " << node
<< endl
;
2843 if(node
.getNumChildren()>0) {
2844 //cout << "cons : " << node << endl;
2845 NodeBuilder
<> nb(node
.getKind());
2846 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2847 Debug("expand") << "op : " << node
.getOperator() << endl
;
2848 //cout << "op : " << node.getOperator() << endl;
2849 nb
<< node
.getOperator();
2851 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2852 Assert(!result
.empty());
2853 Node expanded
= result
.top();
2855 //cout << "exchld : " << expanded << endl;
2856 Debug("expand") << "exchld : " << expanded
<< endl
;
2861 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2864 } while(!worklist
.empty());
2866 AlwaysAssert(result
.size() == 1);
2868 return result
.top();
2871 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
2873 Node
SmtEnginePrivate::purifyNlTerms(TNode n
, NodeMap
& cache
, NodeMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
) {
2875 NodeMap::iterator find
= bcache
.find(n
);
2876 if (find
!= bcache
.end()) {
2877 return (*find
).second
;
2880 NodeMap::iterator find
= cache
.find(n
);
2881 if (find
!= cache
.end()) {
2882 return (*find
).second
;
2886 if( n
.getNumChildren()>0 ){
2888 && (n
.getKind() == kind::PLUS
|| n
.getKind() == kind::MINUS
))
2890 // don't do it if it rewrites to a constant
2891 Node nr
= Rewriter::rewrite(n
);
2894 // return the rewritten constant
2900 ret
= NodeManager::currentNM()->mkSkolem(
2903 "Variable introduced in purifyNl pass");
2904 Node np
= purifyNlTerms(n
, cache
, bcache
, var_eq
, false);
2905 var_eq
.push_back(np
.eqNode(ret
));
2906 Trace("nl-ext-purify")
2907 << "Purify : " << ret
<< " -> " << np
<< std::endl
;
2912 bool beneathMultNew
= beneathMult
|| n
.getKind()==kind::MULT
;
2913 bool childChanged
= false;
2914 std::vector
< Node
> children
;
2915 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2916 Node nc
= purifyNlTerms( n
[i
], cache
, bcache
, var_eq
, beneathMultNew
);
2917 childChanged
= childChanged
|| nc
!=n
[i
];
2918 children
.push_back( nc
);
2921 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
2933 void SmtEnginePrivate::removeITEs() {
2934 d_smt
.finalOptionsAreSet();
2935 spendResource(options::preprocessStep());
2936 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
2938 // Remove all of the ITE occurrences and normalize
2939 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
2940 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2941 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
2947 // do dumping (before/after any preprocessing pass)
2948 static void dumpAssertions(const char* key
,
2949 const AssertionPipeline
& assertionList
) {
2950 if( Dump
.isOn("assertions") &&
2951 Dump
.isOn(string("assertions:") + key
) ) {
2952 // Push the simplified assertions to the dump output stream
2953 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
2954 TNode n
= assertionList
[i
];
2955 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
2960 // returns false if it learns a conflict
2961 bool SmtEnginePrivate::nonClausalSimplify() {
2962 spendResource(options::preprocessStep());
2963 d_smt
.finalOptionsAreSet();
2965 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
2969 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
2971 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
2972 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2973 Trace("simplify") << "Assertion #" << i
<< " : " << d_assertions
[i
] << std::endl
;
2976 if(d_propagatorNeedsFinish
) {
2977 d_propagator
.finish();
2978 d_propagatorNeedsFinish
= false;
2980 d_propagator
.initialize();
2982 // Assert all the assertions to the propagator
2983 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2984 << "asserting to propagator" << endl
;
2985 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2986 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
2987 // Don't reprocess substitutions
2988 if (d_substitutionsIndex
> 0 && i
== d_substitutionsIndex
) {
2991 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
2992 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
2993 d_propagator
.assertTrue(d_assertions
[i
]);
2996 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2997 << "propagating" << endl
;
2998 if (d_propagator
.propagate()) {
2999 // If in conflict, just return false
3000 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3001 << "conflict in non-clausal propagation" << endl
;
3002 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
3003 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
3004 d_assertions
.clear();
3005 addFormula(falseNode
, false, false);
3006 d_propagatorNeedsFinish
= true;
3011 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals
.size() << " learned literals." << std::endl
;
3012 // No conflict, go through the literals and solve them
3013 SubstitutionMap
constantPropagations(d_smt
.d_context
);
3014 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
3015 SubstitutionMap::iterator pos
;
3017 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
3018 // Simplify the literal we learned wrt previous substitutions
3019 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
3020 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
3021 Assert(d_topLevelSubstitutions
.apply(learnedLiteral
) == learnedLiteral
);
3022 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral
<< std::endl
;
3023 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
3024 if (learnedLiteral
!= learnedLiteralNew
) {
3025 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3027 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral
<< std::endl
;
3029 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
3030 if (learnedLiteralNew
== learnedLiteral
) {
3033 ++d_smt
.d_stats
->d_numConstantProps
;
3034 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3036 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral
<< std::endl
;
3037 // It might just simplify to a constant
3038 if (learnedLiteral
.isConst()) {
3039 if (learnedLiteral
.getConst
<bool>()) {
3040 // If the learned literal simplifies to true, it's redundant
3043 // If the learned literal simplifies to false, we're in conflict
3044 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3046 << d_nonClausalLearnedLiterals
[i
] << endl
;
3047 Assert(!options::unsatCores());
3048 d_assertions
.clear();
3049 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3050 d_propagatorNeedsFinish
= true;
3055 // Solve it with the corresponding theory, possibly adding new
3056 // substitutions to newSubstitutions
3057 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3058 << "solving " << learnedLiteral
<< endl
;
3060 Theory::PPAssertStatus solveStatus
=
3061 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
3063 switch (solveStatus
) {
3064 case Theory::PP_ASSERT_STATUS_SOLVED
: {
3065 // The literal should rewrite to true
3066 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3067 << "solved " << learnedLiteral
<< endl
;
3068 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
3069 // vector<pair<Node, Node> > equations;
3070 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
3071 // if (equations.empty()) {
3074 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3075 // else fall through
3078 case Theory::PP_ASSERT_STATUS_CONFLICT
:
3079 // If in conflict, we return false
3080 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3081 << "conflict while solving "
3082 << learnedLiteral
<< endl
;
3083 Assert(!options::unsatCores());
3084 d_assertions
.clear();
3085 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3086 d_propagatorNeedsFinish
= true;
3089 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
3090 // constant propagation
3093 if (learnedLiteral
[0].isConst()) {
3094 t
= learnedLiteral
[1];
3095 c
= learnedLiteral
[0];
3098 t
= learnedLiteral
[0];
3099 c
= learnedLiteral
[1];
3101 Assert(!t
.isConst());
3102 Assert(constantPropagations
.apply(t
) == t
);
3103 Assert(d_topLevelSubstitutions
.apply(t
) == t
);
3104 Assert(newSubstitutions
.apply(t
) == t
);
3105 constantPropagations
.addSubstitution(t
, c
);
3106 // vector<pair<Node,Node> > equations;
3107 // constantPropagations.simplifyLHS(t, c, equations, true);
3108 // if (!equations.empty()) {
3109 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3110 // d_assertions.clear();
3111 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
3114 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
3118 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
3124 #ifdef CVC4_ASSERTIONS
3125 // NOTE: When debugging this code, consider moving this check inside of the
3126 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3127 // because it is costly for certain inputs (see bug 508).
3129 // Check data structure invariants:
3130 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
3131 // 2. each lhs of constantPropagations rewrites to itself
3132 // 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
3133 // constant propagation too
3134 // 4. each lhs of constantPropagations is different from each rhs
3135 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3136 Assert((*pos
).first
.isVar());
3137 Assert(d_topLevelSubstitutions
.apply((*pos
).first
) == (*pos
).first
);
3138 Assert(d_topLevelSubstitutions
.apply((*pos
).second
) == (*pos
).second
);
3139 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
3141 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3142 Assert((*pos
).second
.isConst());
3143 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
3144 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
3145 // if (newLeft != (*pos).first) {
3146 // newLeft = Rewriter::rewrite(newLeft);
3147 // Assert(newLeft == (*pos).second ||
3148 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3150 // newLeft = constantPropagations.apply((*pos).first);
3151 // if (newLeft != (*pos).first) {
3152 // newLeft = Rewriter::rewrite(newLeft);
3153 // Assert(newLeft == (*pos).second ||
3154 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3156 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
3158 #endif /* CVC4_ASSERTIONS */
3160 // Resize the learnt
3161 Trace("simplify") << "Resize non-clausal learned literals to " << j
<< std::endl
;
3162 d_nonClausalLearnedLiterals
.resize(j
);
3164 unordered_set
<TNode
, TNodeHashFunction
> s
;
3165 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3166 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3167 Node assertion
= d_assertions
[i
];
3168 Node assertionNew
= newSubstitutions
.apply(assertion
);
3169 Trace("debugging") << "assertion = " << assertion
<< endl
;
3170 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3171 if (assertion
!= assertionNew
) {
3172 assertion
= Rewriter::rewrite(assertionNew
);
3173 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
3175 Assert(Rewriter::rewrite(assertion
) == assertion
);
3177 assertionNew
= constantPropagations
.apply(assertion
);
3178 if (assertionNew
== assertion
) {
3181 ++d_smt
.d_stats
->d_numConstantProps
;
3182 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3183 assertion
= Rewriter::rewrite(assertionNew
);
3184 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3186 Trace("debugging") << "\n";
3187 s
.insert(assertion
);
3188 d_assertions
.replace(i
, assertion
);
3189 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3190 << "non-clausal preprocessed: "
3191 << assertion
<< endl
;
3194 // If in incremental mode, add substitutions to the list of assertions
3195 if (d_substitutionsIndex
> 0) {
3196 NodeBuilder
<> substitutionsBuilder(kind::AND
);
3197 substitutionsBuilder
<< d_assertions
[d_substitutionsIndex
];
3198 pos
= newSubstitutions
.begin();
3199 for (; pos
!= newSubstitutions
.end(); ++pos
) {
3200 // Add back this substitution as an assertion
3201 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
3202 Node n
= NodeManager::currentNM()->mkNode(kind::EQUAL
, lhs
, rhs
);
3203 substitutionsBuilder
<< n
;
3204 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
3206 if (substitutionsBuilder
.getNumChildren() > 1) {
3207 d_assertions
.replace(d_substitutionsIndex
,
3208 Rewriter::rewrite(Node(substitutionsBuilder
)));
3211 // If not in incremental mode, must add substitutions to model
3212 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3214 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3215 Node n
= (*pos
).first
;
3216 Node v
= newSubstitutions
.apply((*pos
).second
);
3217 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
3218 m
->addSubstitution( n
, v
);
3223 NodeBuilder
<> learnedBuilder(kind::AND
);
3224 Assert(d_realAssertionsEnd
<= d_assertions
.size());
3225 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
3227 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
3228 Node learned
= d_nonClausalLearnedLiterals
[i
];
3229 Assert(d_topLevelSubstitutions
.apply(learned
) == learned
);
3230 Node learnedNew
= newSubstitutions
.apply(learned
);
3231 if (learned
!= learnedNew
) {
3232 learned
= Rewriter::rewrite(learnedNew
);
3234 Assert(Rewriter::rewrite(learned
) == learned
);
3236 learnedNew
= constantPropagations
.apply(learned
);
3237 if (learnedNew
== learned
) {
3240 ++d_smt
.d_stats
->d_numConstantProps
;
3241 learned
= Rewriter::rewrite(learnedNew
);
3243 if (s
.find(learned
) != s
.end()) {
3247 learnedBuilder
<< learned
;
3248 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3249 << "non-clausal learned : "
3252 d_nonClausalLearnedLiterals
.clear();
3254 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3255 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
3256 Assert(d_topLevelSubstitutions
.apply(cProp
) == cProp
);
3257 Node cPropNew
= newSubstitutions
.apply(cProp
);
3258 if (cProp
!= cPropNew
) {
3259 cProp
= Rewriter::rewrite(cPropNew
);
3260 Assert(Rewriter::rewrite(cProp
) == cProp
);
3262 if (s
.find(cProp
) != s
.end()) {
3266 learnedBuilder
<< cProp
;
3267 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3268 << "non-clausal constant propagation : "
3272 // Add new substitutions to topLevelSubstitutions
3273 // Note that we don't have to keep rhs's in full solved form
3274 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3275 d_topLevelSubstitutions
.addSubstitutions(newSubstitutions
);
3277 if(learnedBuilder
.getNumChildren() > 1) {
3278 d_assertions
.replace(d_realAssertionsEnd
- 1,
3279 Rewriter::rewrite(Node(learnedBuilder
)));
3282 d_propagatorNeedsFinish
= true;
3286 bool SmtEnginePrivate::simpITE() {
3287 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
3289 spendResource(options::preprocessStep());
3291 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
3293 unsigned numAssertionOnEntry
= d_assertions
.size();
3294 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3295 spendResource(options::preprocessStep());
3296 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
3297 d_assertions
.replace(i
, result
);
3298 if(result
.isConst() && !result
.getConst
<bool>()){
3302 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
3303 if(numAssertionOnEntry
< d_assertions
.size()){
3304 compressBeforeRealAssertions(numAssertionOnEntry
);
3309 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
3310 size_t curr
= d_assertions
.size();
3311 if(before
>= curr
||
3312 d_realAssertionsEnd
<= 0 ||
3313 d_realAssertionsEnd
>= curr
){
3318 // original: [0 ... d_realAssertionsEnd)
3320 // ites skolems [d_realAssertionsEnd, before)
3322 // added [before, curr)
3324 Assert(0 < d_realAssertionsEnd
);
3325 Assert(d_realAssertionsEnd
<= before
);
3326 Assert(before
< curr
);
3328 std::vector
<Node
> intoConjunction
;
3329 for(size_t i
= before
; i
<curr
; ++i
){
3330 intoConjunction
.push_back(d_assertions
[i
]);
3332 d_assertions
.resize(before
);
3333 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
3334 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
3335 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
3336 d_assertions
.replace(lastBeforeItes
, newLast
);
3337 Assert(d_assertions
.size() == before
);
3340 void SmtEnginePrivate::unconstrainedSimp() {
3341 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
3342 spendResource(options::preprocessStep());
3343 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
3344 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
3347 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
3348 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3349 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
3350 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3351 // term must appear in map, otherwise how did we get here?!
3352 Assert(j
!= backEdges
.end());
3353 // if term maps to empty, that means it's a top-level assertion
3354 if(!(*j
).second
.empty()) {
3355 traceBackToAssertions((*j
).second
, assertions
);
3357 assertions
.push_back(*i
);
3362 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::unordered_set
<unsigned long>& toRemove
) {
3363 Assert(n
.getKind() == kind::AND
);
3364 size_t removals
= 0;
3365 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
3366 size_t subremovals
= 0;
3368 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
3369 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
3370 NodeBuilder
<> b(kind::AND
);
3371 b
.append(n
.begin(), j
);
3372 if(subremovals
> 0) {
3373 removals
+= subremovals
;
3378 for(++j
; j
!= n
.end(); ++j
) {
3379 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
3381 } else if((*j
).getKind() == kind::AND
) {
3383 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
3384 removals
+= subremovals
;
3393 if(b
.getNumChildren() == 0) {
3396 } else if(b
.getNumChildren() == 1) {
3402 n
= Rewriter::rewrite(n
);
3407 Assert(removals
== 0);
3411 void SmtEnginePrivate::doMiplibTrick() {
3412 Assert(d_realAssertionsEnd
== d_assertions
.size());
3413 Assert(!options::incrementalSolving());
3415 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3416 unordered_set
<unsigned long> removeAssertions
;
3418 NodeManager
* nm
= NodeManager::currentNM();
3419 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
3421 unordered_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
3422 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
3423 if(d_propagator
.isAssigned(*i
)) {
3424 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
3428 vector
<TNode
> assertions
;
3429 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3430 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3431 // if maps to an empty vector, that means the bool var was asserted itself.
3432 if(j
!= backEdges
.end()) {
3433 if(!(*j
).second
.empty()) {
3434 traceBackToAssertions((*j
).second
, assertions
);
3436 assertions
.push_back(*i
);
3439 Debug("miplib") << "for " << *i
<< endl
;
3440 bool eligible
= true;
3441 map
<pair
<Node
, Node
>, uint64_t> marks
;
3442 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
3443 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
3444 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
3445 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
3446 Debug("miplib") << " found: " << *j
<< endl
;
3447 if((*j
).getKind() != kind::IMPLIES
) {
3449 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
3452 Node conj
= BooleanSimplification::simplify((*j
)[0]);
3453 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
3455 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
3458 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
3460 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
3463 if((*j
)[1].getKind() != kind::EQUAL
||
3464 !( ( (*j
)[1][0].isVar() &&
3465 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
3466 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
3467 (*j
)[1][1].isVar() ) )) {
3469 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
3472 if(conj
.getKind() == kind::AND
) {
3474 bool found_x
= false;
3475 map
<TNode
, bool> neg
;
3476 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
3478 posv
.push_back(*ii
);
3480 found_x
= found_x
|| *i
== *ii
;
3481 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
3482 posv
.push_back((*ii
)[0]);
3483 neg
[(*ii
)[0]] = true;
3484 found_x
= found_x
|| *i
== (*ii
)[0];
3487 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
3490 if(d_propagator
.isAssigned(posv
.back())) {
3492 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
3501 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
3504 sort(posv
.begin(), posv
.end());
3505 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
3506 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3507 const pair
<Node
, Node
> pos_var(pos
, var
);
3508 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3510 unsigned countneg
= 0, thepos
= 0;
3511 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3516 mark
|= (0x1 << ii
);
3519 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
3521 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3524 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
3525 marks
[pos_var
] |= (1lu << mark
);
3526 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
3527 if(countneg
== pos
.getNumChildren()) {
3530 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3533 } else if(countneg
== pos
.getNumChildren() - 1) {
3534 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
3535 if(coef
[pos_var
].size() <= thepos
) {
3536 coef
[pos_var
].resize(thepos
+ 1);
3538 coef
[pos_var
][thepos
] = constant
;
3540 if(checks
[pos_var
].size() <= mark
) {
3541 checks
[pos_var
].resize(mark
+ 1);
3543 checks
[pos_var
][mark
] = constant
;
3545 asserts
[pos_var
].push_back(*j
);
3548 if(x
!= *i
&& x
!= (*i
).notNode()) {
3550 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
3553 const bool xneg
= (x
.getKind() == kind::NOT
);
3554 x
= xneg
? x
[0] : x
;
3555 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
3556 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3557 const pair
<Node
, Node
> x_var(x
, var
);
3558 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3559 unsigned mark
= (xneg
? 0 : 1);
3560 if((marks
[x_var
] & (1u << mark
)) != 0) {
3562 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3565 marks
[x_var
] |= (1u << mark
);
3569 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3573 Assert(coef
[x_var
].size() <= 6);
3574 coef
[x_var
].resize(6);
3575 coef
[x_var
][0] = constant
;
3577 asserts
[x_var
].push_back(*j
);
3581 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
3582 const TNode pos
= (*j
).first
.first
;
3583 const TNode var
= (*j
).first
.second
;
3584 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
3585 const uint64_t mark
= (*j
).second
;
3586 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
3587 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
3588 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
3589 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
3590 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
3591 if(mark
!= expected
) {
3592 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
3594 if(mark
!= 3) { // exclude single-var case; nothing to check there
3595 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
3596 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
3597 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
3598 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
3599 if((k
& (k
- 1)) != 0) {
3601 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
3602 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
3603 if((kk
& 0x1) == 1) {
3604 Assert(pos
.getKind() == kind::AND
);
3605 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
3606 sum
+= coef
[pos_var
][v
- 1];
3609 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
3610 if(sum
!= checks
[pos_var
][k
]) {
3612 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
3616 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
3621 eligible
= true; // next is still eligible
3625 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
3626 vector
<Node
> newVars
;
3627 expr::NodeSelfIterator ii
, iiend
;
3628 if(pos
.getKind() == kind::AND
) {
3632 ii
= expr::NodeSelfIterator::self(pos
);
3633 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
3635 for(; ii
!= iiend
; ++ii
) {
3636 Node
& varRef
= intVars
[*ii
];
3637 if(varRef
.isNull()) {
3639 ss
<< "mipvar_" << *ii
;
3640 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
3641 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
3642 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
3643 addFormula(Rewriter::rewrite(geq
.andNode(leq
)), false, false);
3644 SubstitutionMap
nullMap(&d_fakeContext
);
3645 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
3646 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
3647 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3648 "unexpected solution from arith's ppAssert()");
3649 Assert(nullMap
.empty(),
3650 "unexpected substitution from arith's ppAssert()");
3651 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
3652 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3653 "unexpected solution from arith's ppAssert()");
3654 Assert(nullMap
.empty(),
3655 "unexpected substitution from arith's ppAssert()");
3656 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
3657 newVars
.push_back(newVar
);
3660 newVars
.push_back(varRef
);
3662 if(!d_smt
.d_logic
.areIntegersUsed()) {
3663 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
3664 d_smt
.d_logic
.enableIntegers();
3665 d_smt
.d_logic
.lock();
3669 if(pos
.getKind() == kind::AND
) {
3670 NodeBuilder
<> sumb(kind::PLUS
);
3671 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3672 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
3676 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
3678 Debug("miplib") << "vars[] " << var
<< endl
3679 << " eq " << Rewriter::rewrite(sum
) << endl
;
3680 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
3681 if(d_topLevelSubstitutions
.hasSubstitution(newAssertion
[0])) {
3682 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3683 //Warning() << "REPLACE " << newAssertion[1] << endl;
3684 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
3685 Assert(d_topLevelSubstitutions
.getSubstitution(newAssertion
[0]) == newAssertion
[1]);
3686 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3687 d_topLevelSubstitutions
.addSubstitution(newAssertion
[0], newAssertion
[1]);
3688 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
3690 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
3692 newAssertion
= Rewriter::rewrite(newAssertion
);
3693 Debug("miplib") << " " << newAssertion
<< endl
;
3694 addFormula(newAssertion
, false, false);
3695 Debug("miplib") << " assertions to remove: " << endl
;
3696 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
3697 Debug("miplib") << " " << *k
<< endl
;
3698 removeAssertions
.insert((*k
).getId());
3704 if(!removeAssertions
.empty()) {
3705 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
3706 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
3707 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
3708 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
3709 d_assertions
[i
] = d_true
;
3710 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
3711 } else if(d_assertions
[i
].getKind() == kind::AND
) {
3712 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
3714 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
3715 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
3716 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
3719 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
3720 d_assertions
[i
] = Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
]));
3721 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
3724 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
3726 d_realAssertionsEnd
= d_assertions
.size();
3730 // returns false if simplification led to "false"
3731 bool SmtEnginePrivate::simplifyAssertions()
3733 spendResource(options::preprocessStep());
3734 Assert(d_smt
.d_pendingPops
== 0);
3736 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3738 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
3740 dumpAssertions("pre-nonclausal", d_assertions
);
3742 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3743 // Perform non-clausal simplification
3744 Chat() << "...performing nonclausal simplification..." << endl
;
3745 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3746 << "performing non-clausal simplification" << endl
;
3747 bool noConflict
= nonClausalSimplify();
3752 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3753 // do the miplib trick.
3754 if( // check that option is on
3755 options::arithMLTrick() &&
3756 // miplib rewrites aren't safe in incremental mode
3757 ! options::incrementalSolving() &&
3758 // only useful in arith
3759 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
3760 // we add new assertions and need this (in practice, this
3761 // restriction only disables miplib processing during
3762 // re-simplification, which we don't expect to be useful anyway)
3763 d_realAssertionsEnd
== d_assertions
.size() ) {
3764 Chat() << "...fixing miplib encodings..." << endl
;
3765 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3766 << "looking for miplib pseudobooleans..." << endl
;
3768 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
3772 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3773 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
3777 dumpAssertions("post-nonclausal", d_assertions
);
3778 Trace("smt") << "POST nonClausalSimplify" << endl
;
3779 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3781 // before ppRewrite check if only core theory for BV theory
3782 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
3784 dumpAssertions("pre-theorypp", d_assertions
);
3786 // Theory preprocessing
3787 if (d_smt
.d_earlyTheoryPP
) {
3788 Chat() << "...doing early theory preprocessing..." << endl
;
3789 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3790 // Call the theory preprocessors
3791 d_smt
.d_theoryEngine
->preprocessStart();
3792 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3793 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3794 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3795 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3799 dumpAssertions("post-theorypp", d_assertions
);
3800 Trace("smt") << "POST theoryPP" << endl
;
3801 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3803 // ITE simplification
3804 if(options::doITESimp() &&
3805 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
3806 Chat() << "...doing ITE simplification..." << endl
;
3807 bool noConflict
= simpITE();
3809 Chat() << "...ITE simplification found unsat..." << endl
;
3814 dumpAssertions("post-itesimp", d_assertions
);
3815 Trace("smt") << "POST iteSimp" << endl
;
3816 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3818 // Unconstrained simplification
3819 if(options::unconstrainedSimp()) {
3820 Chat() << "...doing unconstrained simplification..." << endl
;
3821 unconstrainedSimp();
3824 dumpAssertions("post-unconstrained", d_assertions
);
3825 Trace("smt") << "POST unconstrainedSimp" << endl
;
3826 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3828 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3829 Chat() << "...doing another round of nonclausal simplification..." << endl
;
3830 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3831 << " doing repeated simplification" << endl
;
3832 bool noConflict
= nonClausalSimplify();
3838 dumpAssertions("post-repeatsimp", d_assertions
);
3839 Trace("smt") << "POST repeatSimp" << endl
;
3840 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3842 } catch(TypeCheckingExceptionPrivate
& tcep
) {
3843 // Calls to this function should have already weeded out any
3844 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3845 // theory could still create a new expression that isn't
3846 // well-typed, and we don't want the C++ runtime to abort our
3847 // process without any error notice.
3849 ss
<< "A bad expression was produced. Original exception follows:\n"
3851 InternalError(ss
.str().c_str());
3856 Result
SmtEngine::check() {
3857 Assert(d_fullyInited
);
3858 Assert(d_pendingPops
== 0);
3860 Trace("smt") << "SmtEngine::check()" << endl
;
3862 ResourceManager
* resourceManager
= d_private
->getResourceManager();
3864 resourceManager
->beginCall();
3866 // Only way we can be out of resource is if cumulative budget is on
3867 if (resourceManager
->cumulativeLimitOn() &&
3868 resourceManager
->out()) {
3869 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
3870 Result::RESOURCEOUT
: Result::TIMEOUT
;
3871 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
3874 // Make sure the prop layer has all of the assertions
3875 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
3876 d_private
->processAssertions();
3877 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
3879 // Turn off stop only for QF_LRA
3880 // TODO: Bring up in a meeting where to put this
3881 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
3883 (not d_logic
.isQuantified() &&
3884 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
3886 if(d_private
->d_iteSkolemMap
.empty()){
3887 options::decisionStopOnly
.set(false);
3888 d_decisionEngine
->clearStrategies();
3889 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
3894 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
3896 Chat() << "solving..." << endl
;
3897 Trace("smt") << "SmtEngine::check(): running check" << endl
;
3898 Result result
= d_propEngine
->checkSat();
3900 resourceManager
->endCall();
3901 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
3902 << ", resources " << resourceManager
->getResourceUsage() << endl
;
3905 return Result(result
, d_filename
);
3908 Result
SmtEngine::quickCheck() {
3909 Assert(d_fullyInited
);
3910 Trace("smt") << "SMT quickCheck()" << endl
;
3911 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
3915 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3917 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3919 if (it
!= cache
.end()) {
3923 size_t sz
= n
.getNumChildren();
3925 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3926 if (it
!= d_iteSkolemMap
.end()) {
3927 skolemSet
.insert(n
);
3934 for (; k
< sz
; ++k
) {
3935 collectSkolems(n
[k
], skolemSet
, cache
);
3941 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3943 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3945 if (it
!= cache
.end()) {
3946 return (*it
).second
;
3949 size_t sz
= n
.getNumChildren();
3951 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3953 if (it
!= d_iteSkolemMap
.end()) {
3954 if (!((*it
).first
< n
)) {
3963 for (; k
< sz
; ++k
) {
3964 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
3974 void SmtEnginePrivate::applySubstitutionsToAssertions() {
3975 if(!options::unsatCores()) {
3976 Chat() << "applying substitutions..." << endl
;
3977 Trace("simplify") << "SmtEnginePrivate::processAssertions(): "
3978 << "applying substitutions" << endl
;
3979 // TODO(b/1255): Substitutions in incremental mode should be managed with a
3980 // proper data structure.
3982 // When solving incrementally, all substitutions are piled into the
3983 // assertion at d_substitutionsIndex: we don't want to apply substitutions
3984 // to this assertion or information will be lost.
3985 unsigned substitutionAssertion
= d_substitutionsIndex
> 0 ? d_substitutionsIndex
: d_assertions
.size();
3986 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3987 if (i
== substitutionAssertion
) {
3990 Trace("simplify") << "applying to " << d_assertions
[i
] << endl
;
3991 spendResource(options::preprocessStep());
3992 d_assertions
.replace(i
, Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
])));
3993 Trace("simplify") << " got " << d_assertions
[i
] << endl
;
3998 void SmtEnginePrivate::processAssertions() {
3999 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
4000 spendResource(options::preprocessStep());
4001 Assert(d_smt
.d_fullyInited
);
4002 Assert(d_smt
.d_pendingPops
== 0);
4004 // Dump the assertions
4005 dumpAssertions("pre-everything", d_assertions
);
4007 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
4008 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
4010 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4012 if (d_assertions
.size() == 0) {
4017 if (options::bvGaussElim())
4019 TimerStat::CodeTimer
gaussElimTimer(d_smt
.d_stats
->d_gaussElimTime
);
4020 d_preprocessingPassRegistry
.getPass("bv-gauss")->apply(&d_assertions
);
4023 if (d_assertionsProcessed
&& options::incrementalSolving()) {
4024 // TODO(b/1255): Substitutions in incremental mode should be managed with a
4025 // proper data structure.
4027 // Placeholder for storing substitutions
4028 d_substitutionsIndex
= d_assertions
.size();
4029 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4032 // Add dummy assertion in last position - to be used as a
4033 // placeholder for any new assertions to get added
4034 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4035 // any assertions added beyond realAssertionsEnd must NOT affect the
4036 // equisatisfiability
4037 d_realAssertionsEnd
= d_assertions
.size();
4039 // Assertions are NOT guaranteed to be rewritten by this point
4041 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
4042 dumpAssertions("pre-definition-expansion", d_assertions
);
4044 Chat() << "expanding definitions..." << endl
;
4045 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
4046 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
4047 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4048 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4049 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
4052 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
4053 dumpAssertions("post-definition-expansion", d_assertions
);
4055 // save the assertions now
4058 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4059 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
4063 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4065 if (options::globalNegate())
4067 // global negation of the formula
4068 quantifiers::GlobalNegate gn
;
4069 gn
.simplify(d_assertions
.ref());
4070 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4073 if( options::nlExtPurify() ){
4074 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4075 unordered_map
<Node
, Node
, NodeHashFunction
> bcache
;
4076 std::vector
< Node
> var_eq
;
4077 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4078 Node a
= d_assertions
[i
];
4079 d_assertions
.replace(i
, purifyNlTerms(a
, cache
, bcache
, var_eq
));
4080 Trace("nl-ext-purify")
4081 << "Purify : " << a
<< " -> " << d_assertions
[i
] << std::endl
;
4083 if( !var_eq
.empty() ){
4084 unsigned lastIndex
= d_assertions
.size()-1;
4085 var_eq
.insert( var_eq
.begin(), d_assertions
[lastIndex
] );
4086 d_assertions
.replace(lastIndex
, NodeManager::currentNM()->mkNode( kind::AND
, var_eq
) );
4090 if( options::ceGuidedInst() ){
4091 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4092 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4093 d_smt
.d_theoryEngine
->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions
[i
] );
4097 if (options::solveRealAsInt()) {
4098 d_preprocessingPassRegistry
.getPass("real-to-int")->apply(&d_assertions
);
4101 if (options::solveIntAsBV() > 0)
4103 d_preprocessingPassRegistry
.getPass("int-to-bv")->apply(&d_assertions
);
4106 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
4107 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
4108 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
4109 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
4110 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4111 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4112 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4115 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
4117 d_preprocessingPassRegistry
.getPass("bv-ackermann")->apply(&d_assertions
);
4120 if (options::bvAbstraction() && !options::incrementalSolving())
4122 d_preprocessingPassRegistry
.getPass("bv-abstraction")->apply(&d_assertions
);
4125 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4127 bool noConflict
= true;
4129 if (options::extRewPrep())
4131 theory::quantifiers::ExtendedRewriter
extr(options::extRewPrepAgg());
4132 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4134 Node a
= d_assertions
[i
];
4135 d_assertions
.replace(i
, extr
.extendedRewrite(a
));
4139 // Unconstrained simplification
4140 if(options::unconstrainedSimp()) {
4141 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl
;
4142 dumpAssertions("pre-unconstrained-simp", d_assertions
);
4143 Chat() << "...doing unconstrained simplification..." << endl
;
4144 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4145 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4147 unconstrainedSimp();
4148 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl
;
4149 dumpAssertions("post-unconstrained-simp", d_assertions
);
4152 if(options::bvIntroducePow2())
4154 d_preprocessingPassRegistry
.getPass("bv-intro-pow2")->apply(&d_assertions
);
4157 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl
;
4158 dumpAssertions("pre-substitution", d_assertions
);
4160 if(options::unsatCores()) {
4161 // special rewriting pass for unsat cores, since many of the passes below are skipped
4162 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4163 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4166 applySubstitutionsToAssertions();
4168 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl
;
4169 dumpAssertions("post-substitution", d_assertions
);
4171 // Assertions ARE guaranteed to be rewritten by this point
4172 #ifdef CVC4_ASSERTIONS
4173 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4175 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
4179 // Lift bit-vectors of size 1 to bool
4180 if(options::bitvectorToBool()) {
4181 dumpAssertions("pre-bv-to-bool", d_assertions
);
4182 Chat() << "...doing bvToBool..." << endl
;
4183 d_preprocessingPassRegistry
.getPass("bv-to-bool")->apply(&d_assertions
);
4184 dumpAssertions("post-bv-to-bool", d_assertions
);
4185 Trace("smt") << "POST bvToBool" << endl
;
4187 // Convert non-top-level Booleans to bit-vectors of size 1
4188 if(options::boolToBitvector()) {
4189 dumpAssertions("pre-bool-to-bv", d_assertions
);
4190 Chat() << "...doing boolToBv..." << endl
;
4191 d_preprocessingPassRegistry
.getPass("bool-to-bv")->apply(&d_assertions
);
4192 dumpAssertions("post-bool-to-bv", d_assertions
);
4193 Trace("smt") << "POST boolToBv" << endl
;
4195 if(options::sepPreSkolemEmp()) {
4196 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4197 Node prev
= d_assertions
[i
];
4198 Node next
= sep::TheorySepRewriter::preprocess( prev
);
4200 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4201 Trace("sep-preprocess") << "*** Preprocess sep " << prev
<< endl
;
4202 Trace("sep-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4207 if( d_smt
.d_logic
.isQuantified() ){
4208 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl
;
4210 dumpAssertions("pre-skolem-quant", d_assertions
);
4211 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4212 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4213 Node prev
= d_assertions
[i
];
4214 Node next
= quantifiers::QuantifiersRewriter::preprocess( prev
);
4216 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4217 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev
<< endl
;
4218 Trace("quantifiers-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4221 dumpAssertions("post-skolem-quant", d_assertions
);
4222 if( options::macrosQuant() ){
4223 //quantifiers macro expansion
4224 quantifiers::QuantifierMacros
qm( d_smt
.d_theoryEngine
->getQuantifiersEngine() );
4227 success
= qm
.simplify( d_assertions
.ref(), true );
4229 //finalize the definitions
4230 qm
.finalizeDefinitions();
4233 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4234 if( options::fmfFunWellDefined() ){
4235 quantifiers::FunDefFmf fdf
;
4236 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
4237 //must carry over current definitions (for incremental)
4238 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
4239 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
4241 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
4242 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
4243 fdf
.d_sorts
[f
] = ft
;
4244 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
4245 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
4246 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
4247 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
4250 fdf
.simplify( d_assertions
.ref() );
4251 //must store new definitions (for incremental)
4252 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
4253 Node f
= fdf
.d_funcs
[i
];
4254 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
4255 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
4256 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
4257 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
4259 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
4262 if (options::sygusInference())
4264 // try recast as sygus
4265 quantifiers::SygusInference si
;
4266 if (si
.simplify(d_assertions
.ref()))
4268 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl
;
4271 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl
;
4274 if( options::sortInference() || options::ufssFairnessMonotone() ){
4275 //sort inference technique
4276 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
4277 si
->simplify( d_assertions
.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4278 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
4279 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
4280 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
4284 if( options::pbRewrites() ){
4285 d_preprocessingPassRegistry
.getPass("pseudo-boolean-processor")
4286 ->apply(&d_assertions
);
4289 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
4290 dumpAssertions("pre-simplify", d_assertions
);
4291 Chat() << "simplifying assertions..." << endl
;
4292 noConflict
= simplifyAssertions();
4294 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
4296 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
4297 dumpAssertions("post-simplify", d_assertions
);
4299 if (options::symmetryBreakerExp())
4301 // apply symmetry breaking
4302 d_preprocessingPassRegistry
.getPass("sym-break")->apply(&d_assertions
);
4305 if(options::doStaticLearning()) {
4306 d_preprocessingPassRegistry
.getPass("static-learning")
4307 ->apply(&d_assertions
);
4309 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4311 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl
;
4312 dumpAssertions("pre-ite-removal", d_assertions
);
4314 Chat() << "removing term ITEs..." << endl
;
4315 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
4316 // Remove ITEs, updating d_iteSkolemMap
4317 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
4319 // This is needed because when solving incrementally, removeITEs may introduce
4320 // skolems that were solved for earlier and thus appear in the substitution
4322 applySubstitutionsToAssertions();
4323 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
4325 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl
;
4326 dumpAssertions("post-ite-removal", d_assertions
);
4328 dumpAssertions("pre-repeat-simplify", d_assertions
);
4329 if(options::repeatSimp()) {
4330 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
4331 Chat() << "re-simplifying assertions..." << endl
;
4332 ScopeCounter
depth(d_simplifyAssertionsDepth
);
4333 noConflict
&= simplifyAssertions();
4335 // Need to fix up assertion list to maintain invariants:
4336 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4337 // during ite removal.
4338 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4340 // cache for expression traversal
4341 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
4343 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4344 // to be moved to the main assertion set
4345 set
<TNode
> skolemSet
;
4346 SubstitutionMap::iterator pos
= d_topLevelSubstitutions
.begin();
4347 for (; pos
!= d_topLevelSubstitutions
.end(); ++pos
) {
4348 collectSkolems((*pos
).first
, skolemSet
, cache
);
4349 collectSkolems((*pos
).second
, skolemSet
, cache
);
4352 // We need to ensure:
4353 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4354 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4355 // If either of these is violated, we must add iteExpr as a proper assertion
4356 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
4357 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
4358 NodeBuilder
<> builder(kind::AND
);
4359 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
4360 vector
<TNode
> toErase
;
4361 for (; it
!= iend
; ++it
) {
4362 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
4363 TNode iteExpr
= d_assertions
[(*it
).second
];
4364 if (iteExpr
.getKind() == kind::ITE
&&
4365 iteExpr
[1].getKind() == kind::EQUAL
&&
4366 iteExpr
[1][0] == (*it
).first
&&
4367 iteExpr
[2].getKind() == kind::EQUAL
&&
4368 iteExpr
[2][0] == (*it
).first
) {
4370 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
4371 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
4372 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
4378 // Move this iteExpr into the main assertions
4379 builder
<< d_assertions
[(*it
).second
];
4380 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
4381 toErase
.push_back((*it
).first
);
4383 if(builder
.getNumChildren() > 1) {
4384 while (!toErase
.empty()) {
4385 d_iteSkolemMap
.erase(toErase
.back());
4388 d_assertions
[d_realAssertionsEnd
- 1] = Rewriter::rewrite(Node(builder
));
4390 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4391 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4393 applySubstitutionsToAssertions();
4394 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4396 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
4398 dumpAssertions("post-repeat-simplify", d_assertions
);
4400 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
4401 if(options::rewriteApplyToConst()) {
4402 Chat() << "Rewriting applies to constants..." << endl
;
4403 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
4404 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4405 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
4408 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
4410 // begin: INVARIANT to maintain: no reordering of assertions or
4411 // introducing new ones
4412 #ifdef CVC4_ASSERTIONS
4413 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
4416 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4418 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
4419 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4421 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl
;
4422 dumpAssertions("pre-theory-preprocessing", d_assertions
);
4424 Chat() << "theory preprocessing..." << endl
;
4425 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
4426 // Call the theory preprocessors
4427 d_smt
.d_theoryEngine
->preprocessStart();
4428 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4429 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
4432 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl
;
4433 dumpAssertions("post-theory-preprocessing", d_assertions
);
4435 // If we are using eager bit-blasting wrap assertions in fake atom so that
4436 // everything gets bit-blasted to internal SAT solver
4437 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4438 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4439 TNode atom
= d_assertions
[i
];
4440 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
4441 d_assertions
.replace(i
, eager_atom
);
4442 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
4443 m
->addSubstitution(eager_atom
, atom
);
4447 //notify theory engine new preprocessed assertions
4448 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
4450 // Push the formula to decision engine
4452 Chat() << "pushing to decision engine..." << endl
;
4453 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
4454 d_smt
.d_decisionEngine
->addAssertions
4455 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
4458 // end: INVARIANT to maintain: no reordering of assertions or
4459 // introducing new ones
4461 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
4462 dumpAssertions("post-everything", d_assertions
);
4464 // Push the formula to SAT
4466 Chat() << "converting to CNF..." << endl
;
4467 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
4468 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4469 Chat() << "+ " << d_assertions
[i
] << std::endl
;
4470 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
4474 d_assertionsProcessed
= true;
4476 d_assertions
.clear();
4477 d_iteSkolemMap
.clear();
4480 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
4487 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
4489 // Give it to proof manager
4492 // n is an input assertion
4493 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4495 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
4498 // n is the result of an unknown preprocessing step, add it to dependency map to null
4499 ProofManager::currentPM()->addDependence(n
, Node::null());
4501 // rewrite rules are by default in the unsat core because
4502 // they need to be applied until saturation
4503 if(options::unsatCores() &&
4504 n
.getKind() == kind::REWRITE_RULE
){
4505 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
4509 // Add the normalized formula to the queue
4510 d_assertions
.push_back(n
);
4511 //d_assertions.push_back(Rewriter::rewrite(n));
4514 void SmtEngine::ensureBoolean(const Expr
& e
)
4516 Type type
= e
.getType(options::typeChecking());
4517 Type boolType
= d_exprManager
->booleanType();
4518 if(type
!= boolType
) {
4520 ss
<< "Expected " << boolType
<< "\n"
4521 << "The assertion : " << e
<< "\n"
4522 << "Its type : " << type
;
4523 throw TypeCheckingException(e
, ss
.str());
4527 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
4529 return checkSatisfiability(assumption
, inUnsatCore
, false);
4532 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4534 return checkSatisfiability(assumptions
, inUnsatCore
, false);
4537 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
4539 Assert(!assumption
.isNull());
4540 return checkSatisfiability(assumption
, inUnsatCore
, true);
4543 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4545 return checkSatisfiability(assumptions
, inUnsatCore
, true);
4548 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
4552 return checkSatisfiability(
4553 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
4558 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
4564 SmtScope
smts(this);
4565 finalOptionsAreSet();
4568 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4569 << assumptions
<< ")" << endl
;
4571 if(d_queryMade
&& !options::incrementalSolving()) {
4572 throw ModalException("Cannot make multiple queries unless "
4573 "incremental solving is enabled "
4574 "(try --incremental)");
4577 // check to see if a postsolve() is pending
4578 if(d_needPostsolve
) {
4579 d_theoryEngine
->postsolve();
4580 d_needPostsolve
= false;
4582 // Note that a query has been made
4584 // reset global negation
4585 d_globalNegation
= false;
4587 bool didInternalPush
= false;
4589 setProblemExtended(true);
4593 size_t size
= assumptions
.size();
4596 /* Assume: not (BIGAND assumptions) */
4597 d_assumptions
.push_back(
4598 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
4602 /* Assume: not expr */
4603 d_assumptions
.push_back(assumptions
[0].notExpr());
4608 /* Assume: BIGAND assumptions */
4609 d_assumptions
= assumptions
;
4612 if (!d_assumptions
.empty())
4615 didInternalPush
= true;
4618 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4619 for (Expr e
: d_assumptions
)
4621 // Substitute out any abstract values in ex.
4622 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
4623 Assert(e
.getExprManager() == d_exprManager
);
4624 // Ensure expr is type-checked at this point.
4627 /* Add assumption */
4628 if (d_assertionList
!= NULL
)
4630 d_assertionList
->push_back(e
);
4632 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4635 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
4637 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4638 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4640 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4642 // flipped if we did a global negation
4643 if (d_globalNegation
)
4645 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
4646 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4648 r
= Result(Result::SAT
);
4650 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4652 // only if satisfaction complete
4653 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
4655 r
= Result(Result::UNSAT
);
4659 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4662 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
4665 d_needPostsolve
= true;
4667 // Dump the query if requested
4668 if (Dump
.isOn("benchmark"))
4670 size_t size
= assumptions
.size();
4671 // the expr already got dumped out if assertion-dumping is on
4672 if (isQuery
&& size
== 1)
4674 Dump("benchmark") << QueryCommand(assumptions
[0]);
4678 Dump("benchmark") << CheckSatCommand();
4682 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
,
4688 if (didInternalPush
)
4693 // Remember the status
4696 setProblemExtended(false);
4698 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4699 << assumptions
<< ") => " << r
<< endl
;
4701 // Check that SAT results generate a model correctly.
4702 if(options::checkModels()) {
4703 // TODO (#1693) check model when unknown result?
4704 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4709 // Check that UNSAT results generate a proof correctly.
4710 if(options::checkProofs()) {
4711 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4712 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
4716 // Check that UNSAT results generate an unsat core correctly.
4717 if(options::checkUnsatCores()) {
4718 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4719 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
4723 // Check that synthesis solutions satisfy the conjecture
4724 if (options::checkSynthSol()
4725 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4727 checkSynthSolution();
4731 } catch (UnsafeInterruptException
& e
) {
4732 AlwaysAssert(d_private
->getResourceManager()->out());
4733 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
4734 Result::RESOURCEOUT
: Result::TIMEOUT
;
4735 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
4739 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
4741 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
4742 SmtScope
smts(this);
4743 if (!options::unsatAssumptions())
4745 throw ModalException(
4746 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4749 if (d_status
.isNull()
4750 || d_status
.asSatisfiabilityResult() != Result::UNSAT
4751 || d_problemExtended
)
4753 throw RecoverableModalException(
4754 "Cannot get unsat assumptions unless immediately preceded by "
4755 "UNSAT/VALID response.");
4757 finalOptionsAreSet();
4758 if (Dump
.isOn("benchmark"))
4760 Dump("benchmark") << GetUnsatCoreCommand();
4762 UnsatCore core
= getUnsatCore();
4764 for (const Expr
& e
: d_assumptions
)
4766 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
4771 Result
SmtEngine::checkSynth(const Expr
& e
)
4773 SmtScope
smts(this);
4774 Trace("smt") << "Check synth: " << e
<< std::endl
;
4775 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
4777 if (options::sygusQePreproc())
4779 // the following does quantifier elimination as a preprocess step
4780 // for "non-ground single invocation synthesis conjectures":
4781 // exists f. forall xy. P[ f(x), x, y ]
4782 // We run quantifier elimination:
4783 // exists y. P[ z, x, y ] ----> Q[ z, x ]
4784 // Where we replace the original conjecture with:
4785 // exists f. forall x. Q[ f(x), x ]
4786 // For more details, see Example 6 of Reynolds et al. SYNT 2017.
4787 Node conj
= Node::fromExpr(e
);
4788 if (conj
.getKind() == kind::FORALL
&& conj
[1].getKind() == kind::EXISTS
)
4790 Node conj_se
= Node::fromExpr(expandDefinitions(conj
[1][1].toExpr()));
4792 Trace("smt-synth") << "Compute single invocation for " << conj_se
<< "..."
4794 quantifiers::SingleInvocationPartition sip
;
4795 std::vector
<Node
> funcs
;
4796 funcs
.insert(funcs
.end(), conj
[0].begin(), conj
[0].end());
4797 sip
.init(funcs
, conj_se
.negate());
4798 Trace("smt-synth") << "...finished, got:" << std::endl
;
4799 sip
.debugPrint("smt-synth");
4801 if (!sip
.isPurelySingleInvocation() && sip
.isNonGroundSingleInvocation())
4803 // create new smt engine to do quantifier elimination
4804 SmtEngine
smt_qe(d_exprManager
);
4805 smt_qe
.setLogic(getLogicInfo());
4806 Trace("smt-synth") << "Property is non-ground single invocation, run "
4807 "QE to obtain single invocation."
4809 NodeManager
* nm
= NodeManager::currentNM();
4810 // partition variables
4811 std::vector
<Node
> all_vars
;
4812 sip
.getAllVariables(all_vars
);
4813 std::vector
<Node
> si_vars
;
4814 sip
.getSingleInvocationVariables(si_vars
);
4815 std::vector
<Node
> qe_vars
;
4816 std::vector
<Node
> nqe_vars
;
4817 for (unsigned i
= 0, size
= all_vars
.size(); i
< size
; i
++)
4819 Node v
= all_vars
[i
];
4820 if (std::find(si_vars
.begin(), si_vars
.end(), v
) == si_vars
.end())
4822 qe_vars
.push_back(v
);
4826 nqe_vars
.push_back(v
);
4829 std::vector
<Node
> orig
;
4830 std::vector
<Node
> subs
;
4831 // skolemize non-qe variables
4832 for (unsigned i
= 0; i
< nqe_vars
.size(); i
++)
4834 Node k
= nm
->mkSkolem("k",
4835 nqe_vars
[i
].getType(),
4836 "qe for non-ground single invocation");
4837 orig
.push_back(nqe_vars
[i
]);
4839 Trace("smt-synth") << " subs : " << nqe_vars
[i
] << " -> " << k
4842 std::vector
<Node
> funcs
;
4843 sip
.getFunctions(funcs
);
4844 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
4847 Node fi
= sip
.getFunctionInvocationFor(f
);
4848 Node fv
= sip
.getFirstOrderVariableForFunction(f
);
4849 Assert(!fi
.isNull());
4854 "qe for function in non-ground single invocation");
4856 Trace("smt-synth") << " subs : " << fi
<< " -> " << k
<< std::endl
;
4858 Node conj_se_ngsi
= sip
.getFullSpecification();
4859 Trace("smt-synth") << "Full specification is " << conj_se_ngsi
4861 Node conj_se_ngsi_subs
= conj_se_ngsi
.substitute(
4862 orig
.begin(), orig
.end(), subs
.begin(), subs
.end());
4863 Assert(!qe_vars
.empty());
4865 nm
->mkNode(kind::EXISTS
,
4866 nm
->mkNode(kind::BOUND_VAR_LIST
, qe_vars
),
4867 conj_se_ngsi_subs
.negate());
4869 Trace("smt-synth") << "Run quantifier elimination on "
4870 << conj_se_ngsi_subs
<< std::endl
;
4871 Expr qe_res
= smt_qe
.doQuantifierElimination(
4872 conj_se_ngsi_subs
.toExpr(), true, false);
4873 Trace("smt-synth") << "Result : " << qe_res
<< std::endl
;
4875 // create single invocation conjecture
4876 Node qe_res_n
= Node::fromExpr(qe_res
);
4877 qe_res_n
= qe_res_n
.substitute(
4878 subs
.begin(), subs
.end(), orig
.begin(), orig
.end());
4879 if (!nqe_vars
.empty())
4881 qe_res_n
= nm
->mkNode(kind::EXISTS
,
4882 nm
->mkNode(kind::BOUND_VAR_LIST
, nqe_vars
),
4885 Assert(conj
.getNumChildren() == 3);
4886 qe_res_n
= nm
->mkNode(kind::FORALL
, conj
[0], qe_res_n
, conj
[2]);
4887 Trace("smt-synth") << "Converted conjecture after QE : " << qe_res_n
4889 e_check
= qe_res_n
.toExpr();
4894 return checkSatisfiability( e_check
, true, false );
4897 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
4899 Assert(ex
.getExprManager() == d_exprManager
);
4900 SmtScope
smts(this);
4901 finalOptionsAreSet();
4904 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
4906 if (Dump
.isOn("raw-benchmark")) {
4907 Dump("raw-benchmark") << AssertCommand(ex
);
4910 // Substitute out any abstract values in ex
4911 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4914 if(d_assertionList
!= NULL
) {
4915 d_assertionList
->push_back(e
);
4917 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4918 return quickCheck().asValidityResult();
4919 }/* SmtEngine::assertFormula() */
4921 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
4925 Expr
SmtEngine::simplify(const Expr
& ex
)
4927 Assert(ex
.getExprManager() == d_exprManager
);
4928 SmtScope
smts(this);
4929 finalOptionsAreSet();
4931 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
4933 if(Dump
.isOn("benchmark")) {
4934 Dump("benchmark") << SimplifyCommand(ex
);
4937 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4938 if( options::typeChecking() ) {
4939 e
.getType(true); // ensure expr is type-checked at this point
4942 // Make sure all preprocessing is done
4943 d_private
->processAssertions();
4944 Node n
= d_private
->simplify(Node::fromExpr(e
));
4945 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4949 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
4951 d_private
->spendResource(options::preprocessStep());
4953 Assert(ex
.getExprManager() == d_exprManager
);
4954 SmtScope
smts(this);
4955 finalOptionsAreSet();
4957 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
4959 // Substitute out any abstract values in ex.
4960 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4961 if(options::typeChecking()) {
4962 // Ensure expr is type-checked at this point.
4965 if(Dump
.isOn("benchmark")) {
4966 Dump("benchmark") << ExpandDefinitionsCommand(e
);
4968 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4969 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
4970 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4975 // TODO(#1108): Simplify the error reporting of this method.
4976 Expr
SmtEngine::getValue(const Expr
& ex
) const
4978 Assert(ex
.getExprManager() == d_exprManager
);
4979 SmtScope
smts(this);
4981 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
4982 if(Dump
.isOn("benchmark")) {
4983 Dump("benchmark") << GetValueCommand(ex
);
4986 if(!options::produceModels()) {
4988 "Cannot get value when produce-models options is off.";
4989 throw ModalException(msg
);
4991 if(d_status
.isNull() ||
4992 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
4993 d_problemExtended
) {
4995 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
4996 throw RecoverableModalException(msg
);
4999 // Substitute out any abstract values in ex.
5000 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5002 // Ensure expr is type-checked at this point.
5003 e
.getType(options::typeChecking());
5005 // do not need to apply preprocessing substitutions (should be recorded
5006 // in model already)
5008 Node n
= Node::fromExpr(e
);
5009 Trace("smt") << "--- getting value of " << n
<< endl
;
5010 TypeNode expectedType
= n
.getType();
5012 // Expand, then normalize
5013 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5014 n
= d_private
->expandDefinitions(n
, cache
);
5015 // There are two ways model values for terms are computed (for historical
5016 // reasons). One way is that used in check-model; the other is that
5017 // used by the Model classes. It's not clear to me exactly how these
5018 // two are different, but they need to be unified. This ugly hack here
5019 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
5022 if(!n
.getType().isFunction()) {
5023 n
= Rewriter::rewrite(n
);
5026 Trace("smt") << "--- getting value of " << n
<< endl
;
5027 TheoryModel
* m
= d_theoryEngine
->getModel();
5030 resultNode
= m
->getValue(n
);
5032 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
5033 resultNode
= postprocess(resultNode
, expectedType
);
5034 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
5035 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
5036 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
5038 // type-check the result we got
5039 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
5040 "Run with -t smt for details.");
5042 // ensure it's a constant
5043 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
5045 if(options::abstractValues() && resultNode
.getType().isArray()) {
5046 resultNode
= d_private
->mkAbstractValue(resultNode
);
5047 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
5050 return resultNode
.toExpr();
5053 bool SmtEngine::addToAssignment(const Expr
& ex
) {
5054 SmtScope
smts(this);
5055 finalOptionsAreSet();
5057 // Substitute out any abstract values in ex
5058 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5059 Type type
= e
.getType(options::typeChecking());
5061 PrettyCheckArgument(
5062 type
.isBoolean(), e
,
5063 "expected Boolean-typed variable or function application "
5064 "in addToAssignment()" );
5065 Node n
= e
.getNode();
5066 // must be an APPLY of a zero-ary defined function, or a variable
5067 PrettyCheckArgument(
5068 ( ( n
.getKind() == kind::APPLY
&&
5069 ( d_definedFunctions
->find(n
.getOperator()) !=
5070 d_definedFunctions
->end() ) &&
5071 n
.getNumChildren() == 0 ) ||
5073 "expected variable or defined-function application "
5074 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
5075 if(!options::produceAssignments()) {
5078 if(d_assignments
== NULL
) {
5079 d_assignments
= new(true) AssignmentSet(d_context
);
5081 d_assignments
->insert(n
);
5086 // TODO(#1108): Simplify the error reporting of this method.
5087 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
5089 Trace("smt") << "SMT getAssignment()" << endl
;
5090 SmtScope
smts(this);
5091 finalOptionsAreSet();
5092 if(Dump
.isOn("benchmark")) {
5093 Dump("benchmark") << GetAssignmentCommand();
5095 if(!options::produceAssignments()) {
5097 "Cannot get the current assignment when "
5098 "produce-assignments option is off.";
5099 throw ModalException(msg
);
5101 if(d_status
.isNull() ||
5102 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5103 d_problemExtended
) {
5105 "Cannot get the current assignment unless immediately "
5106 "preceded by SAT/INVALID or UNKNOWN response.";
5107 throw RecoverableModalException(msg
);
5110 vector
<pair
<Expr
,Expr
>> res
;
5111 if (d_assignments
!= nullptr)
5113 TypeNode boolType
= d_nodeManager
->booleanType();
5114 TheoryModel
* m
= d_theoryEngine
->getModel();
5115 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
5116 iend
= d_assignments
->key_end();
5121 Assert(as
.getType() == boolType
);
5123 Trace("smt") << "--- getting value of " << as
<< endl
;
5125 // Expand, then normalize
5126 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5127 Node n
= d_private
->expandDefinitions(as
, cache
);
5128 n
= Rewriter::rewrite(n
);
5130 Trace("smt") << "--- getting value of " << n
<< endl
;
5134 resultNode
= m
->getValue(n
);
5137 // type-check the result we got
5138 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
5140 // ensure it's a constant
5141 Assert(resultNode
.isConst());
5143 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
5144 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
5145 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
5151 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
5152 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
5153 SmtScope
smts(this);
5154 // If we aren't yet fully inited, the user might still turn on
5155 // produce-models. So let's keep any commands around just in
5156 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5157 // sort "U" in QF_UF before setLogic() is run and we still want to
5158 // support finding card(U) with --finite-model-find, and (2) to
5159 // decouple SmtEngine and ExprManager if the user does a few
5160 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5161 // and expects to find their cardinalities in the model.
5162 if(/* userVisible && */
5163 (!d_fullyInited
|| options::produceModels()) &&
5164 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
5166 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
5167 d_modelGlobalCommands
.push_back(c
.clone());
5169 d_modelCommands
->push_back(c
.clone());
5172 if(Dump
.isOn(dumpTag
)) {
5176 d_dumpCommands
.push_back(c
.clone());
5181 // TODO(#1108): Simplify the error reporting of this method.
5182 Model
* SmtEngine::getModel() {
5183 Trace("smt") << "SMT getModel()" << endl
;
5184 SmtScope
smts(this);
5186 finalOptionsAreSet();
5188 if(Dump
.isOn("benchmark")) {
5189 Dump("benchmark") << GetModelCommand();
5192 if(d_status
.isNull() ||
5193 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5194 d_problemExtended
) {
5196 "Cannot get the current model unless immediately "
5197 "preceded by SAT/INVALID or UNKNOWN response.";
5198 throw RecoverableModalException(msg
);
5200 if(!options::produceModels()) {
5202 "Cannot get model when produce-models options is off.";
5203 throw ModalException(msg
);
5205 TheoryModel
* m
= d_theoryEngine
->getModel();
5206 m
->d_inputName
= d_filename
;
5210 void SmtEngine::checkUnsatCore() {
5211 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5213 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
5214 UnsatCore core
= getUnsatCore();
5216 SmtEngine
coreChecker(d_exprManager
);
5217 coreChecker
.setLogic(getLogicInfo());
5220 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
5221 for (; itg
!= d_defineCommands
.end(); ++itg
) {
5222 (*itg
)->invoke(&coreChecker
);
5226 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
5227 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
5228 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
5229 coreChecker
.assertFormula(*i
);
5231 const bool checkUnsatCores
= options::checkUnsatCores();
5234 options::checkUnsatCores
.set(false);
5235 options::checkProofs
.set(false);
5236 r
= coreChecker
.checkSat();
5238 options::checkUnsatCores
.set(checkUnsatCores
);
5241 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
5242 if(r
.asSatisfiabilityResult().isUnknown()) {
5243 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5246 if(r
.asSatisfiabilityResult().isSat()) {
5247 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5251 void SmtEngine::checkModel(bool hardFailure
) {
5252 // --check-model implies --produce-assertions, which enables the
5253 // assertion list, so we should be ok.
5254 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
5256 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
5258 // Throughout, we use Notice() to give diagnostic output.
5260 // If this function is running, the user gave --check-model (or equivalent),
5261 // and if Notice() is on, the user gave --verbose (or equivalent).
5263 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
5264 TheoryModel
* m
= d_theoryEngine
->getModel();
5266 // check-model is not guaranteed to succeed if approximate values were used
5267 if (m
->hasApproximations())
5270 << "WARNING: running check-model on a model with approximate values..."
5274 // Check individual theory assertions
5275 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
5280 // We have a "fake context" for the substitution map (we don't need it
5281 // to be context-dependent)
5282 context::Context fakeContext
;
5283 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
5285 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
5286 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
5287 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
5289 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5290 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
5292 // We have a DECLARE-FUN:
5294 // We'll first do some checks, then add to our substitution map
5295 // the mapping: function symbol |-> value
5297 Expr func
= c
->getFunction();
5298 Node val
= m
->getValue(func
);
5300 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
5302 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5303 // function symbol (since then the definition is recursive)
5304 if (val
.getKind() == kind::LAMBDA
) {
5305 // first apply the model substitutions we have so far
5306 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
5307 Node n
= substitutions
.apply(val
[1]);
5308 Debug("boolean-terms") << "++ got " << n
<< endl
;
5309 // now check if n contains func by doing a substitution
5310 // [func->func2] and checking equality of the Nodes.
5311 // (this just a way to check if func is in n.)
5312 SubstitutionMap
subs(&fakeContext
);
5313 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
5314 subs
.addSubstitution(func
, func2
);
5315 if(subs
.apply(n
) != n
) {
5316 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
5318 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5319 << "considering model value for " << func
<< endl
5320 << "body of lambda is: " << val
<< endl
;
5322 ss
<< "body substitutes to: " << n
<< endl
;
5324 ss
<< "so " << func
<< " is defined in terms of itself." << endl
5325 << "Run with `--check-models -v' for additional diagnostics.";
5326 InternalError(ss
.str());
5330 // (2) check that the value is actually a value
5331 else if (!val
.isConst()) {
5332 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
5334 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5335 << "model value for " << func
<< endl
5336 << " is " << val
<< endl
5337 << "and that is not a constant (.isConst() == false)." << endl
5338 << "Run with `--check-models -v' for additional diagnostics.";
5339 InternalError(ss
.str());
5342 // (3) check that it's the correct (sub)type
5343 // This was intended to be a more general check, but for now we can't do that because
5344 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5345 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
5346 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
5348 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5349 << "model value for " << func
<< endl
5350 << " is " << val
<< endl
5351 << "value type is " << val
.getType() << endl
5352 << "should be of type " << func
.getType() << endl
5353 << "Run with `--check-models -v' for additional diagnostics.";
5354 InternalError(ss
.str());
5357 // (4) checks complete, add the substitution
5358 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
5359 substitutions
.addSubstitution(func
, val
);
5363 // Now go through all our user assertions checking if they're satisfied.
5364 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
5365 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
5366 Node n
= Node::fromExpr(*i
);
5368 // Apply any define-funs from the problem.
5370 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5371 n
= d_private
->expandDefinitions(n
, cache
);
5373 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
5375 // Apply our model value substitutions.
5376 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5377 n
= substitutions
.apply(n
);
5378 Debug("boolean-terms") << "++ got " << n
<< endl
;
5379 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
5381 if( n
.getKind() != kind::REWRITE_RULE
){
5382 // In case it's a quantifier (or contains one), look up its value before
5383 // simplifying, or the quantifier might be irreparably altered.
5385 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
5387 // Note this "skip" is done here, rather than above. This is
5388 // because (1) the quantifier could in principle simplify to false,
5389 // which should be reported, and (2) checking for the quantifier
5390 // above, before simplification, doesn't catch buried quantifiers
5391 // anyway (those not at the top-level).
5392 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5397 // Simplify the result.
5398 n
= d_private
->simplify(n
);
5399 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
5401 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5402 n
= d_private
->d_iteRemover
.replace(n
);
5403 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
5405 // Apply our model value substitutions (again), as things may have been simplified.
5406 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5407 n
= substitutions
.apply(n
);
5408 Debug("boolean-terms") << "++ got " << n
<< endl
;
5409 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
5411 // As a last-ditch effort, ask model to simplify it.
5412 // Presently, this is only an issue for quantifiers, which can have a value
5413 // but don't show up in our substitution map above.
5415 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
5417 if( d_logic
.isQuantified() ){
5418 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5419 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5420 // hence we use a relaxed version of check model here.
5421 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5422 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
5423 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
5424 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
5425 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
5429 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
5431 // The result should be == true.
5432 if(n
!= NodeManager::currentNM()->mkConst(true)) {
5433 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5436 ss
<< "SmtEngine::checkModel(): "
5437 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5438 << "assertion: " << *i
<< endl
5439 << "simplifies to: " << n
<< endl
5440 << "expected `true'." << endl
5441 << "Run with `--check-models -v' for additional diagnostics.";
5443 InternalError(ss
.str());
5445 Warning() << ss
.str() << endl
;
5449 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
5452 void SmtEngine::checkSynthSolution()
5454 NodeManager
* nm
= NodeManager::currentNM();
5455 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
5456 map
<Node
, Node
> sol_map
;
5457 /* Get solutions and build auxiliary vectors for substituting */
5458 d_theoryEngine
->getSynthSolutions(sol_map
);
5459 if (sol_map
.empty())
5461 Trace("check-synth-sol") << "No solution to check!\n";
5464 Trace("check-synth-sol") << "Got solution map:\n";
5465 std::vector
<Node
> function_vars
, function_sols
;
5466 for (const auto& pair
: sol_map
)
5468 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
5469 function_vars
.push_back(pair
.first
);
5470 function_sols
.push_back(pair
.second
);
5472 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5473 /* Start new SMT engine to check solutions */
5474 SmtEngine
solChecker(d_exprManager
);
5475 solChecker
.setLogic(getLogicInfo());
5476 setOption("check-synth-sol", SExpr("false"));
5478 Trace("check-synth-sol") << "Retrieving assertions\n";
5479 // Build conjecture from original assertions
5480 if (d_assertionList
== NULL
)
5482 Trace("check-synth-sol") << "No assertions to check\n";
5485 for (AssertionList::const_iterator i
= d_assertionList
->begin();
5486 i
!= d_assertionList
->end();
5489 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
5490 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
5491 Node conj
= Node::fromExpr(*i
);
5492 // Apply any define-funs from the problem.
5494 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5495 conj
= d_private
->expandDefinitions(conj
, cache
);
5497 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
5498 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
5500 // Apply solution map to conjecture body
5502 /* Whether property is quantifier free */
5503 if (conj
[1].getKind() != kind::EXISTS
)
5505 conjBody
= conj
[1].substitute(function_vars
.begin(),
5506 function_vars
.end(),
5507 function_sols
.begin(),
5508 function_sols
.end());
5512 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
5513 function_vars
.end(),
5514 function_sols
.begin(),
5515 function_sols
.end());
5517 /* Skolemize property */
5518 std::vector
<Node
> vars
, skos
;
5519 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
5521 vars
.push_back(conj
[1][0][j
]);
5522 std::stringstream ss
;
5524 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
5525 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
5526 << skos
.back() << "\n";
5528 conjBody
= conjBody
.substitute(
5529 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
5531 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5532 << conjBody
<< endl
;
5533 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5535 solChecker
.assertFormula(conjBody
.toExpr());
5536 Result r
= solChecker
.checkSat();
5537 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
5538 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
5539 if (r
.asSatisfiabilityResult().isUnknown())
5542 "SmtEngine::checkSynthSolution(): could not check solution, result "
5545 else if (r
.asSatisfiabilityResult().isSat())
5548 "SmtEngine::checkSynthSolution(): produced solution leads to "
5549 "satisfiable negated conjecture.");
5551 solChecker
.resetAssertions();
5555 // TODO(#1108): Simplify the error reporting of this method.
5556 UnsatCore
SmtEngine::getUnsatCore() {
5557 Trace("smt") << "SMT getUnsatCore()" << endl
;
5558 SmtScope
smts(this);
5559 finalOptionsAreSet();
5560 if(Dump
.isOn("benchmark")) {
5561 Dump("benchmark") << GetUnsatCoreCommand();
5564 if(!options::unsatCores()) {
5565 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
5567 if(d_status
.isNull() ||
5568 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5569 d_problemExtended
) {
5570 throw RecoverableModalException(
5571 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5575 d_proofManager
->traceUnsatCore();// just to trigger core creation
5576 return UnsatCore(this, d_proofManager
->extractUnsatCore());
5577 #else /* IS_PROOFS_BUILD */
5578 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
5579 #endif /* IS_PROOFS_BUILD */
5582 // TODO(#1108): Simplify the error reporting of this method.
5583 const Proof
& SmtEngine::getProof()
5585 Trace("smt") << "SMT getProof()" << endl
;
5586 SmtScope
smts(this);
5587 finalOptionsAreSet();
5588 if(Dump
.isOn("benchmark")) {
5589 Dump("benchmark") << GetProofCommand();
5592 if(!options::proof()) {
5593 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5595 if(d_status
.isNull() ||
5596 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5597 d_problemExtended
) {
5598 throw RecoverableModalException(
5599 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5603 return ProofManager::getProof(this);
5604 #else /* IS_PROOFS_BUILD */
5605 throw ModalException("This build of CVC4 doesn't have proof support.");
5606 #endif /* IS_PROOFS_BUILD */
5609 void SmtEngine::printInstantiations( std::ostream
& out
) {
5610 SmtScope
smts(this);
5611 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5612 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
5614 if( d_theoryEngine
){
5615 d_theoryEngine
->printInstantiations( out
);
5619 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5620 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
5624 void SmtEngine::printSynthSolution( std::ostream
& out
) {
5625 SmtScope
smts(this);
5626 if( d_theoryEngine
){
5627 d_theoryEngine
->printSynthSolution( out
);
5633 void SmtEngine::getSynthSolutions(std::map
<Expr
, Expr
>& sol_map
)
5635 SmtScope
smts(this);
5636 map
<Node
, Node
> sol_mapn
;
5637 Assert(d_theoryEngine
!= nullptr);
5638 d_theoryEngine
->getSynthSolutions(sol_mapn
);
5639 for (std::pair
<const Node
, Node
>& s
: sol_mapn
)
5641 sol_map
[s
.first
.toExpr()] = s
.second
.toExpr();
5645 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
5647 SmtScope
smts(this);
5648 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
5649 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
5651 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
5652 Node n_e
= Node::fromExpr( e
);
5653 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
5655 throw ModalException(
5656 "Expecting a quantified formula as argument to get-qe.");
5658 //tag the quantified formula with the quant-elim attribute
5659 TypeNode t
= NodeManager::currentNM()->booleanType();
5660 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
5661 std::vector
< Node
> node_values
;
5662 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
5663 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
5664 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
5665 std::vector
< Node
> e_children
;
5666 e_children
.push_back( n_e
[0] );
5667 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
5669 e_children
.push_back( n_attr
);
5670 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
5671 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
5672 Assert( nn_e
.getNumChildren()==3 );
5673 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
5674 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
5675 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
5676 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
5678 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
5679 InternalError(ss
.str().c_str());
5681 std::vector
< Node
> inst_qs
;
5682 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
5683 Assert( inst_qs
.size()<=1 );
5685 if( inst_qs
.size()==1 ){
5686 Node top_q
= inst_qs
[0];
5687 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5688 Assert( top_q
.getKind()==kind::FORALL
);
5689 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
5690 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
5691 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
5692 if (n_e
.getKind() == kind::EXISTS
)
5694 ret_n
= Rewriter::rewrite(ret_n
.negate());
5697 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
5699 return ret_n
.toExpr();
5701 return NodeManager::currentNM()
5702 ->mkConst(n_e
.getKind() == kind::EXISTS
)
5707 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
5708 SmtScope
smts(this);
5709 if( d_theoryEngine
){
5710 std::vector
< Node
> qs_n
;
5711 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
5712 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
5713 qs
.push_back( qs_n
[i
].toExpr() );
5720 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
5721 SmtScope
smts(this);
5722 if( d_theoryEngine
){
5723 std::vector
< Node
> insts_n
;
5724 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
5725 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
5726 insts
.push_back( insts_n
[i
].toExpr() );
5733 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
5734 SmtScope
smts(this);
5735 Assert(options::trackInstLemmas());
5736 if( d_theoryEngine
){
5737 std::vector
< std::vector
< Node
> > tvecs_n
;
5738 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
5739 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
5740 std::vector
< Expr
> tvec
;
5741 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
5742 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
5744 tvecs
.push_back( tvec
);
5751 vector
<Expr
> SmtEngine::getAssertions() {
5752 SmtScope
smts(this);
5753 finalOptionsAreSet();
5755 if(Dump
.isOn("benchmark")) {
5756 Dump("benchmark") << GetAssertionsCommand();
5758 Trace("smt") << "SMT getAssertions()" << endl
;
5759 if(!options::produceAssertions()) {
5761 "Cannot query the current assertion list when not in produce-assertions mode.";
5762 throw ModalException(msg
);
5764 Assert(d_assertionList
!= NULL
);
5765 // copy the result out
5766 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
5769 void SmtEngine::push()
5771 SmtScope
smts(this);
5772 finalOptionsAreSet();
5774 Trace("smt") << "SMT push()" << endl
;
5775 d_private
->notifyPush();
5776 d_private
->processAssertions();
5777 if(Dump
.isOn("benchmark")) {
5778 Dump("benchmark") << PushCommand();
5780 if(!options::incrementalSolving()) {
5781 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5784 // check to see if a postsolve() is pending
5785 if(d_needPostsolve
) {
5786 d_theoryEngine
->postsolve();
5787 d_needPostsolve
= false;
5790 // The problem isn't really "extended" yet, but this disallows
5791 // get-model after a push, simplifying our lives somewhat and
5792 // staying symmtric with pop.
5793 setProblemExtended(true);
5795 d_userLevels
.push_back(d_userContext
->getLevel());
5797 Trace("userpushpop") << "SmtEngine: pushed to level "
5798 << d_userContext
->getLevel() << endl
;
5801 void SmtEngine::pop() {
5802 SmtScope
smts(this);
5803 finalOptionsAreSet();
5804 Trace("smt") << "SMT pop()" << endl
;
5805 if(Dump
.isOn("benchmark")) {
5806 Dump("benchmark") << PopCommand();
5808 if(!options::incrementalSolving()) {
5809 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5811 if(d_userLevels
.size() == 0) {
5812 throw ModalException("Cannot pop beyond the first user frame");
5815 // check to see if a postsolve() is pending
5816 if(d_needPostsolve
) {
5817 d_theoryEngine
->postsolve();
5818 d_needPostsolve
= false;
5821 // The problem isn't really "extended" yet, but this disallows
5822 // get-model after a pop, simplifying our lives somewhat. It might
5823 // not be strictly necessary to do so, since the pops occur lazily,
5824 // but also it would be weird to have a legally-executed (get-model)
5825 // that only returns a subset of the assignment (because the rest
5826 // is no longer in scope!).
5827 setProblemExtended(true);
5829 AlwaysAssert(d_userContext
->getLevel() > 0);
5830 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
5831 while (d_userLevels
.back() < d_userContext
->getLevel()) {
5834 d_userLevels
.pop_back();
5836 // Clear out assertion queues etc., in case anything is still in there
5837 d_private
->notifyPop();
5839 Trace("userpushpop") << "SmtEngine: popped to level "
5840 << d_userContext
->getLevel() << endl
;
5841 // FIXME: should we reset d_status here?
5842 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5845 void SmtEngine::internalPush() {
5846 Assert(d_fullyInited
);
5847 Trace("smt") << "SmtEngine::internalPush()" << endl
;
5849 if(options::incrementalSolving()) {
5850 d_private
->processAssertions();
5851 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5852 d_userContext
->push();
5853 // the d_context push is done inside of the SAT solver
5854 d_propEngine
->push();
5858 void SmtEngine::internalPop(bool immediate
) {
5859 Assert(d_fullyInited
);
5860 Trace("smt") << "SmtEngine::internalPop()" << endl
;
5861 if(options::incrementalSolving()) {
5869 void SmtEngine::doPendingPops() {
5870 Assert(d_pendingPops
== 0 || options::incrementalSolving());
5871 while(d_pendingPops
> 0) {
5872 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5873 d_propEngine
->pop();
5874 // the d_context pop is done inside of the SAT solver
5875 d_userContext
->pop();
5880 void SmtEngine::reset()
5882 SmtScope
smts(this);
5883 ExprManager
*em
= d_exprManager
;
5884 Trace("smt") << "SMT reset()" << endl
;
5885 if(Dump
.isOn("benchmark")) {
5886 Dump("benchmark") << ResetCommand();
5889 opts
.copyValues(d_originalOptions
);
5891 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
5892 new(this) SmtEngine(em
);
5895 void SmtEngine::resetAssertions()
5897 SmtScope
smts(this);
5900 Trace("smt") << "SMT resetAssertions()" << endl
;
5901 if(Dump
.isOn("benchmark")) {
5902 Dump("benchmark") << ResetAssertionsCommand();
5905 while(!d_userLevels
.empty()) {
5909 // Also remember the global push/pop around everything.
5910 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
5911 d_context
->popto(0);
5912 d_userContext
->popto(0);
5913 DeleteAndClearCommandVector(d_modelGlobalCommands
);
5914 d_userContext
->push();
5918 void SmtEngine::interrupt()
5920 if(!d_fullyInited
) {
5923 d_propEngine
->interrupt();
5924 d_theoryEngine
->interrupt();
5927 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
5928 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
5930 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
5931 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
5934 unsigned long SmtEngine::getResourceUsage() const {
5935 return d_private
->getResourceManager()->getResourceUsage();
5938 unsigned long SmtEngine::getTimeUsage() const {
5939 return d_private
->getResourceManager()->getTimeUsage();
5942 unsigned long SmtEngine::getResourceRemaining() const
5944 return d_private
->getResourceManager()->getResourceRemaining();
5947 unsigned long SmtEngine::getTimeRemaining() const
5949 return d_private
->getResourceManager()->getTimeRemaining();
5952 Statistics
SmtEngine::getStatistics() const
5954 return Statistics(*d_statisticsRegistry
);
5957 SExpr
SmtEngine::getStatistic(std::string name
) const
5959 return d_statisticsRegistry
->getStatistic(name
);
5962 void SmtEngine::safeFlushStatistics(int fd
) const {
5963 d_statisticsRegistry
->safeFlushInformation(fd
);
5966 void SmtEngine::setUserAttribute(const std::string
& attr
,
5968 const std::vector
<Expr
>& expr_values
,
5969 const std::string
& str_value
)
5971 SmtScope
smts(this);
5972 std::vector
<Node
> node_values
;
5973 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
5974 node_values
.push_back( expr_values
[i
].getNode() );
5976 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
5979 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
5980 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
5981 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
5982 Command
* c
= d_modelGlobalCommands
[i
];
5983 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5985 if( dfc
->getFunction()==f
){
5986 dfc
->setPrintInModel( p
);
5990 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
5991 Command
* c
= (*d_modelCommands
)[i
];
5992 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5994 if( dfc
->getFunction()==f
){
5995 dfc
->setPrintInModel( p
);
6001 void SmtEngine::beforeSearch()
6004 throw ModalException(
6005 "SmtEngine::beforeSearch called after initialization.");
6010 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
6012 NodeManagerScope
nms(d_nodeManager
);
6013 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
6015 if(Dump
.isOn("benchmark")) {
6016 Dump("benchmark") << SetOptionCommand(key
, value
);
6019 if(key
== "command-verbosity") {
6020 if(!value
.isAtom()) {
6021 const vector
<SExpr
>& cs
= value
.getChildren();
6022 if(cs
.size() == 2 &&
6023 (cs
[0].isKeyword() || cs
[0].isString()) &&
6024 cs
[1].isInteger()) {
6025 string c
= cs
[0].getValue();
6026 const Integer
& v
= cs
[1].getIntegerValue();
6027 if(v
< 0 || v
> 2) {
6028 throw OptionException("command-verbosity must be 0, 1, or 2");
6030 d_commandVerbosity
[c
] = v
;
6034 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
6037 if(!value
.isAtom()) {
6038 throw OptionException("bad value for :" + key
);
6041 string optionarg
= value
.getValue();
6042 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6043 nodeManagerOptions
.setOption(key
, optionarg
);
6046 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
6048 NodeManagerScope
nms(d_nodeManager
);
6050 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
6052 if(key
.length() >= 18 &&
6053 key
.compare(0, 18, "command-verbosity:") == 0) {
6054 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
6055 if(i
!= d_commandVerbosity
.end()) {
6056 return SExpr((*i
).second
);
6058 i
= d_commandVerbosity
.find("*");
6059 if(i
!= d_commandVerbosity
.end()) {
6060 return SExpr((*i
).second
);
6062 return SExpr(Integer(2));
6065 if(Dump
.isOn("benchmark")) {
6066 Dump("benchmark") << GetOptionCommand(key
);
6069 if(key
== "command-verbosity") {
6070 vector
<SExpr
> result
;
6071 SExpr defaultVerbosity
;
6072 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
6073 i
!= d_commandVerbosity
.end();
6076 v
.push_back(SExpr((*i
).first
));
6077 v
.push_back(SExpr((*i
).second
));
6078 if((*i
).first
== "*") {
6079 // put the default at the end of the SExpr
6080 defaultVerbosity
= SExpr(v
);
6082 result
.push_back(SExpr(v
));
6085 // put the default at the end of the SExpr
6086 if(!defaultVerbosity
.isAtom()) {
6087 result
.push_back(defaultVerbosity
);
6089 // ensure the default is always listed
6091 v
.push_back(SExpr("*"));
6092 v
.push_back(SExpr(Integer(2)));
6093 result
.push_back(SExpr(v
));
6095 return SExpr(result
);
6098 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6099 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
6102 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
6103 AlwaysAssert(!d_fullyInited
,
6104 "Cannot set replay stream once fully initialized");
6105 d_replayStream
= replayStream
;
6108 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
6109 return d_private
->getExpressionName(e
, name
);
6112 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
6113 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
6114 d_private
->setExpressionName(e
,name
);
6117 }/* CVC4 namespace */