diff options
Diffstat (limited to 'src')
101 files changed, 19175 insertions, 2235 deletions
diff --git a/src/Makefile.am b/src/Makefile.am index 7112d5a55..4f00b061b 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -39,6 +39,7 @@ libcvc4_la_LIBADD = \ @builddir@/proof/libproof.la \ @builddir@/prop/libprop.la \ @builddir@/prop/minisat/libminisat.la \ + @builddir@/prop/bvminisat/libbvminisat.la \ @builddir@/printer/libprinter.la \ @builddir@/smt/libsmt.la \ @builddir@/theory/libtheory.la \ @@ -50,6 +51,7 @@ libcvc4_noinst_la_LIBADD = \ @builddir@/proof/libproof.la \ @builddir@/prop/libprop.la \ @builddir@/prop/minisat/libminisat.la \ + @builddir@/prop/bvminisat/libbvminisat.la \ @builddir@/printer/libprinter.la \ @builddir@/smt/libsmt.la \ @builddir@/theory/libtheory.la \ diff --git a/src/expr/expr_template.h b/src/expr/expr_template.h index 56396da01..7a6c0179d 100644 --- a/src/expr/expr_template.h +++ b/src/expr/expr_template.h @@ -65,7 +65,7 @@ namespace expr { }/* CVC4::expr namespace */ namespace prop { - class SatSolver; + class TheoryProxy; }/* CVC4::prop namespace */ class ExprManagerMapCollection; @@ -536,7 +536,7 @@ protected: friend class NodeManager; friend class TypeCheckingException; friend class expr::pickle::Pickler; - friend class prop::SatSolver; + friend class prop::TheoryProxy; friend NodeTemplate<true> expr::exportInternal(NodeTemplate<false> n, ExprManager* from, ExprManager* to, ExprManagerMapCollection& vmap); friend std::ostream& CVC4::operator<<(std::ostream& out, const Expr& e); diff --git a/src/prop/Makefile.am b/src/prop/Makefile.am index 30be07d7c..e6c8752d6 100644 --- a/src/prop/Makefile.am +++ b/src/prop/Makefile.am @@ -2,17 +2,21 @@ AM_CPPFLAGS = \ -D__BUILDING_CVC4LIB \ -D __STDC_LIMIT_MACROS \ -D __STDC_FORMAT_MACROS \ - -I@srcdir@/../include -I@srcdir@/.. -I@builddir@/.. -I@srcdir@/minisat + -I@srcdir@/../include -I@srcdir@/.. -I@builddir@/.. -I@srcdir@/minisat -I@srcdir@/bvminisat AM_CXXFLAGS = -Wall -Wno-parentheses -Wno-unknown-pragmas $(FLAG_VISIBILITY_HIDDEN) noinst_LTLIBRARIES = libprop.la libprop_la_SOURCES = \ + registrar.h \ prop_engine.cpp \ prop_engine.h \ sat.h \ sat.cpp \ cnf_stream.h \ - cnf_stream.cpp + cnf_stream.cpp \ + sat_module.h \ + sat_module.cpp + +SUBDIRS = minisat bvminisat -SUBDIRS = minisat diff --git a/src/prop/bvminisat/LICENSE b/src/prop/bvminisat/LICENSE new file mode 100644 index 000000000..22816ff39 --- /dev/null +++ b/src/prop/bvminisat/LICENSE @@ -0,0 +1,21 @@ +MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson + Copyright (c) 2007-2010 Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/prop/bvminisat/Makefile.am b/src/prop/bvminisat/Makefile.am new file mode 100644 index 000000000..480e4e83c --- /dev/null +++ b/src/prop/bvminisat/Makefile.am @@ -0,0 +1,42 @@ +AM_CPPFLAGS = \ + -D__BUILDING_CVC4LIB \ + -D __STDC_LIMIT_MACROS \ + -D __STDC_FORMAT_MACROS \ + -I@srcdir@/ -I@srcdir@/../.. -I@builddir@/../.. -I@srcdir@/../../include +AM_CXXFLAGS = -Wall -Wno-parentheses -Wno-unknown-pragmas $(FLAG_VISIBILITY_HIDDEN) + +noinst_LTLIBRARIES = libbvminisat.la +libbvminisat_la_SOURCES = \ + core/Dimacs.h \ + core/Solver.cc \ + core/Solver.h \ + core/SolverTypes.h \ + simp/SimpSolver.cc \ + simp/SimpSolver.h \ + mtl/Alg.h \ + mtl/Alloc.h \ + mtl/Heap.h \ + mtl/IntTypes.h \ + mtl/Map.h \ + mtl/Queue.h \ + mtl/Sort.h \ + mtl/Vec.h \ + mtl/XAlloc.h \ + utils/Options.h + +EXTRA_DIST = \ + core/Main.cc \ + core/Makefile \ + doc/ReleaseNotes-2.2.0.txt \ + simp/Main.cc \ + simp/Makefile \ + README \ + LICENSE \ + mtl/config.mk \ + mtl/template.mk \ + utils/Options.cc \ + utils/ParseUtils.h \ + utils/System.h \ + utils/System.cc \ + Makefile + diff --git a/src/prop/bvminisat/README b/src/prop/bvminisat/README new file mode 100644 index 000000000..e5e5617d8 --- /dev/null +++ b/src/prop/bvminisat/README @@ -0,0 +1,24 @@ +================================================================================ +DIRECTORY OVERVIEW: + +mtl/ Mini Template Library +utils/ Generic helper code (I/O, Parsing, CPU-time, etc) +core/ A core version of the solver +simp/ An extended solver with simplification capabilities +README +LICENSE + +================================================================================ +BUILDING: (release version: without assertions, statically linked, etc) + +export MROOT=<minisat-dir> (or setenv in cshell) +cd { core | simp } +gmake rs +cp minisat_static <install-dir>/minisat + +================================================================================ +EXAMPLES: + +Run minisat with same heuristics as version 2.0: + +> minisat <cnf-file> -no-luby -rinc=1.5 -phase-saving=0 -rnd-freq=0.02 diff --git a/src/prop/bvminisat/core/Dimacs.h b/src/prop/bvminisat/core/Dimacs.h new file mode 100644 index 000000000..64df4f635 --- /dev/null +++ b/src/prop/bvminisat/core/Dimacs.h @@ -0,0 +1,89 @@ +/****************************************************************************************[Dimacs.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Dimacs_h +#define BVMinisat_Dimacs_h + +#include <stdio.h> + +#include "utils/ParseUtils.h" +#include "core/SolverTypes.h" + +namespace BVMinisat { + +//================================================================================================= +// DIMACS Parser: + +template<class B, class Solver> +static void readClause(B& in, Solver& S, vec<Lit>& lits) { + int parsed_lit, var; + lits.clear(); + for (;;){ + parsed_lit = parseInt(in); + if (parsed_lit == 0) break; + var = abs(parsed_lit)-1; + while (var >= S.nVars()) S.newVar(); + lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) ); + } +} + +template<class B, class Solver> +static void parse_DIMACS_main(B& in, Solver& S) { + vec<Lit> lits; + int vars = 0; + int clauses = 0; + int cnt = 0; + for (;;){ + skipWhitespace(in); + if (*in == EOF) break; + else if (*in == 'p'){ + if (eagerMatch(in, "p cnf")){ + vars = parseInt(in); + clauses = parseInt(in); + // SATRACE'06 hack + // if (clauses > 4000000) + // S.eliminate(true); + }else{ + printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3); + } + } else if (*in == 'c' || *in == 'p') + skipLine(in); + else{ + cnt++; + readClause(in, S, lits); + S.addClause_(lits); } + } + if (vars != S.nVars()) + fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of variables.\n"); + if (cnt != clauses) + fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of clauses.\n"); +} + +// Inserts problem into solver. +// +template<class Solver> +static void parse_DIMACS(gzFile input_stream, Solver& S) { + StreamBuffer in(input_stream); + parse_DIMACS_main(in, S); } + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/core/Main.cc b/src/prop/bvminisat/core/Main.cc new file mode 100644 index 000000000..95cfe7bfe --- /dev/null +++ b/src/prop/bvminisat/core/Main.cc @@ -0,0 +1,192 @@ +/*****************************************************************************************[Main.cc] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include <errno.h> + +#include <signal.h> +#include <zlib.h> + +#include "utils/System.h" +#include "utils/ParseUtils.h" +#include "utils/Options.h" +#include "core/Dimacs.h" +#include "core/Solver.h" + +using namespace BVMinisat; + +//================================================================================================= + + +void printStats(Solver& solver) +{ + double cpu_time = cpuTime(); + double mem_used = memUsedPeak(); + printf("restarts : %"PRIu64"\n", solver.starts); + printf("conflicts : %-12"PRIu64" (%.0f /sec)\n", solver.conflicts , solver.conflicts /cpu_time); + printf("decisions : %-12"PRIu64" (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions /cpu_time); + printf("propagations : %-12"PRIu64" (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time); + printf("conflict literals : %-12"PRIu64" (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals); + if (mem_used != 0) printf("Memory used : %.2f MB\n", mem_used); + printf("CPU time : %g s\n", cpu_time); +} + + +static Solver* solver; +// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case +// for this feature of the Solver as it may take longer than an immediate call to '_exit()'. +static void SIGINT_interrupt(int signum) { solver->interrupt(); } + +// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls +// destructors and may cause deadlocks if a malloc/free function happens to be running (these +// functions are guarded by locks for multithreaded use). +static void SIGINT_exit(int signum) { + printf("\n"); printf("*** INTERRUPTED ***\n"); + if (solver->verbosity > 0){ + printStats(*solver); + printf("\n"); printf("*** INTERRUPTED ***\n"); } + _exit(1); } + + +//================================================================================================= +// Main: + + +int main(int argc, char** argv) +{ + try { + setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n where input may be either in plain or gzipped DIMACS.\n"); + // printf("This is MiniSat 2.0 beta\n"); + +#if defined(__linux__) + fpu_control_t oldcw, newcw; + _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw); + printf("WARNING: for repeatability, setting FPU to use double precision\n"); +#endif + // Extra options: + // + IntOption verb ("MAIN", "verb", "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2)); + IntOption cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX)); + IntOption mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX)); + + parseOptions(argc, argv, true); + + Solver S; + double initial_time = cpuTime(); + + S.verbosity = verb; + + solver = &S; + // Use signal handlers that forcibly quit until the solver will be able to respond to + // interrupts: + signal(SIGINT, SIGINT_exit); + signal(SIGXCPU,SIGINT_exit); + + // Set limit on CPU-time: + if (cpu_lim != INT32_MAX){ + rlimit rl; + getrlimit(RLIMIT_CPU, &rl); + if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){ + rl.rlim_cur = cpu_lim; + if (setrlimit(RLIMIT_CPU, &rl) == -1) + printf("WARNING! Could not set resource limit: CPU-time.\n"); + } } + + // Set limit on virtual memory: + if (mem_lim != INT32_MAX){ + rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024; + rlimit rl; + getrlimit(RLIMIT_AS, &rl); + if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){ + rl.rlim_cur = new_mem_lim; + if (setrlimit(RLIMIT_AS, &rl) == -1) + printf("WARNING! Could not set resource limit: Virtual memory.\n"); + } } + + if (argc == 1) + printf("Reading from standard input... Use '--help' for help.\n"); + + gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb"); + if (in == NULL) + printf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1); + + if (S.verbosity > 0){ + printf("============================[ Problem Statistics ]=============================\n"); + printf("| |\n"); } + + parse_DIMACS(in, S); + gzclose(in); + FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL; + + if (S.verbosity > 0){ + printf("| Number of variables: %12d |\n", S.nVars()); + printf("| Number of clauses: %12d |\n", S.nClauses()); } + + double parsed_time = cpuTime(); + if (S.verbosity > 0){ + printf("| Parse time: %12.2f s |\n", parsed_time - initial_time); + printf("| |\n"); } + + // Change to signal-handlers that will only notify the solver and allow it to terminate + // voluntarily: + signal(SIGINT, SIGINT_interrupt); + signal(SIGXCPU,SIGINT_interrupt); + + if (!S.simplify()){ + if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res); + if (S.verbosity > 0){ + printf("===============================================================================\n"); + printf("Solved by unit propagation\n"); + printStats(S); + printf("\n"); } + printf("UNSATISFIABLE\n"); + exit(20); + } + + vec<Lit> dummy; + lbool ret = S.solveLimited(dummy); + if (S.verbosity > 0){ + printStats(S); + printf("\n"); } + printf(ret == l_True ? "SATISFIABLE\n" : ret == l_False ? "UNSATISFIABLE\n" : "INDETERMINATE\n"); + if (res != NULL){ + if (ret == l_True){ + fprintf(res, "SAT\n"); + for (int i = 0; i < S.nVars(); i++) + if (S.model[i] != l_Undef) + fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1); + fprintf(res, " 0\n"); + }else if (ret == l_False) + fprintf(res, "UNSAT\n"); + else + fprintf(res, "INDET\n"); + fclose(res); + } + +#ifdef NDEBUG + exit(ret == l_True ? 10 : ret == l_False ? 20 : 0); // (faster than "return", which will invoke the destructor for 'Solver') +#else + return (ret == l_True ? 10 : ret == l_False ? 20 : 0); +#endif + } catch (OutOfMemoryException&){ + printf("===============================================================================\n"); + printf("INDETERMINATE\n"); + exit(0); + } +} diff --git a/src/prop/bvminisat/core/Makefile b/src/prop/bvminisat/core/Makefile new file mode 100644 index 000000000..5de1f7295 --- /dev/null +++ b/src/prop/bvminisat/core/Makefile @@ -0,0 +1,4 @@ +EXEC = minisat +DEPDIR = mtl utils + +include $(MROOT)/mtl/template.mk diff --git a/src/prop/bvminisat/core/Solver.cc b/src/prop/bvminisat/core/Solver.cc new file mode 100644 index 000000000..af342dbbc --- /dev/null +++ b/src/prop/bvminisat/core/Solver.cc @@ -0,0 +1,940 @@ +/***************************************************************************************[Solver.cc] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include <math.h> + +#include "mtl/Sort.h" +#include "core/Solver.h" +#include <iostream> + +using namespace BVMinisat; + +// purely debugging functions +void printDebug2 (BVMinisat::Lit l) { + std::cout<< (sign(l) ? "-" : "") << var(l) + 1 << std::endl; +} + +void printDebug2 (BVMinisat::Clause& c) { + for (int i = 0; i < c.size(); i++) { + std::cout << (sign(c[i]) ? "-" : "") << var(c[i]) + 1 << " "; + } + std::cout << std::endl; +} + + + +//================================================================================================= +// Options: + + +static const char* _cat = "CORE"; + +static DoubleOption opt_var_decay (_cat, "var-decay", "The variable activity decay factor", 0.95, DoubleRange(0, false, 1, false)); +static DoubleOption opt_clause_decay (_cat, "cla-decay", "The clause activity decay factor", 0.999, DoubleRange(0, false, 1, false)); +static DoubleOption opt_random_var_freq (_cat, "rnd-freq", "The frequency with which the decision heuristic tries to choose a random variable", 0, DoubleRange(0, true, 1, true)); +static DoubleOption opt_random_seed (_cat, "rnd-seed", "Used by the random variable selection", 91648253, DoubleRange(0, false, HUGE_VAL, false)); +static IntOption opt_ccmin_mode (_cat, "ccmin-mode", "Controls conflict clause minimization (0=none, 1=basic, 2=deep)", 2, IntRange(0, 2)); +static IntOption opt_phase_saving (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)", 2, IntRange(0, 2)); +static BoolOption opt_rnd_init_act (_cat, "rnd-init", "Randomize the initial activity", false); +static BoolOption opt_luby_restart (_cat, "luby", "Use the Luby restart sequence", true); +static IntOption opt_restart_first (_cat, "rfirst", "The base restart interval", 100, IntRange(1, INT32_MAX)); +static DoubleOption opt_restart_inc (_cat, "rinc", "Restart interval increase factor", 2, DoubleRange(1, false, HUGE_VAL, false)); +static DoubleOption opt_garbage_frac (_cat, "gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered", 0.20, DoubleRange(0, false, HUGE_VAL, false)); + + +//================================================================================================= +// Constructor/Destructor: + + +Solver::Solver() : + + // Parameters (user settable): + // + verbosity (0) + , var_decay (opt_var_decay) + , clause_decay (opt_clause_decay) + , random_var_freq (opt_random_var_freq) + , random_seed (opt_random_seed) + , luby_restart (opt_luby_restart) + , ccmin_mode (opt_ccmin_mode) + , phase_saving (opt_phase_saving) + , rnd_pol (false) + , rnd_init_act (opt_rnd_init_act) + , garbage_frac (opt_garbage_frac) + , restart_first (opt_restart_first) + , restart_inc (opt_restart_inc) + + // Parameters (the rest): + // + , learntsize_factor((double)1/(double)3), learntsize_inc(1.1) + + // Parameters (experimental): + // + , learntsize_adjust_start_confl (100) + , learntsize_adjust_inc (1.5) + + // Statistics: (formerly in 'SolverStats') + // + , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0) + , dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0) + + , ok (true) + , cla_inc (1) + , var_inc (1) + , watches (WatcherDeleted(ca)) + , qhead (0) + , simpDB_assigns (-1) + , simpDB_props (0) + , order_heap (VarOrderLt(activity)) + , progress_estimate (0) + , remove_satisfied (true) + + // Resource constraints: + // + , conflict_budget (-1) + , propagation_budget (-1) + , asynch_interrupt (false) +{} + + +Solver::~Solver() +{ +} + + +//================================================================================================= +// Minor methods: + + +// Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be +// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). +// +Var Solver::newVar(bool sign, bool dvar) +{ + int v = nVars(); + watches .init(mkLit(v, false)); + watches .init(mkLit(v, true )); + assigns .push(l_Undef); + vardata .push(mkVarData(CRef_Undef, 0)); + //activity .push(0); + activity .push(rnd_init_act ? drand(random_seed) * 0.00001 : 0); + seen .push(0); + polarity .push(sign); + decision .push(); + trail .capacity(v+1); + setDecisionVar(v, dvar); + + return v; +} + + +bool Solver::addClause_(vec<Lit>& ps) +{ + assert(decisionLevel() == 0); + if (!ok) return false; + + // Check if clause is satisfied and remove false/duplicate literals: + sort(ps); + Lit p; int i, j; + for (i = j = 0, p = lit_Undef; i < ps.size(); i++) + if (value(ps[i]) == l_True || ps[i] == ~p) + return true; + else if (value(ps[i]) != l_False && ps[i] != p) + ps[j++] = p = ps[i]; + ps.shrink(i - j); + + if (ps.size() == 0) + return ok = false; + else if (ps.size() == 1){ + uncheckedEnqueue(ps[0]); + return ok = (propagate() == CRef_Undef); + }else{ + CRef cr = ca.alloc(ps, false); + clauses.push(cr); + attachClause(cr); + } + + return true; +} + + +void Solver::attachClause(CRef cr) { + const Clause& c = ca[cr]; + assert(c.size() > 1); + watches[~c[0]].push(Watcher(cr, c[1])); + watches[~c[1]].push(Watcher(cr, c[0])); + if (c.learnt()) learnts_literals += c.size(); + else clauses_literals += c.size(); } + + +void Solver::detachClause(CRef cr, bool strict) { + const Clause& c = ca[cr]; + assert(c.size() > 1); + + if (strict){ + remove(watches[~c[0]], Watcher(cr, c[1])); + remove(watches[~c[1]], Watcher(cr, c[0])); + }else{ + // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause) + watches.smudge(~c[0]); + watches.smudge(~c[1]); + } + + if (c.learnt()) learnts_literals -= c.size(); + else clauses_literals -= c.size(); } + + +void Solver::removeClause(CRef cr) { + Clause& c = ca[cr]; + detachClause(cr); + // Don't leave pointers to free'd memory! + if (locked(c)) vardata[var(c[0])].reason = CRef_Undef; + c.mark(1); + ca.free(cr); +} + + +bool Solver::satisfied(const Clause& c) const { + for (int i = 0; i < c.size(); i++) + if (value(c[i]) == l_True) + return true; + return false; } + + +// Revert to the state at given level (keeping all assignment at 'level' but not beyond). +// +void Solver::cancelUntil(int level) { + if (decisionLevel() > level){ + for (int c = trail.size()-1; c >= trail_lim[level]; c--){ + Var x = var(trail[c]); + assigns [x] = l_Undef; + if (phase_saving > 1 || (phase_saving == 1) && c > trail_lim.last()) + polarity[x] = sign(trail[c]); + insertVarOrder(x); } + qhead = trail_lim[level]; + trail.shrink(trail.size() - trail_lim[level]); + trail_lim.shrink(trail_lim.size() - level); + } } + + +//================================================================================================= +// Major methods: + + +Lit Solver::pickBranchLit() +{ + Var next = var_Undef; + + // Random decision: + if (drand(random_seed) < random_var_freq && !order_heap.empty()){ + next = order_heap[irand(random_seed,order_heap.size())]; + if (value(next) == l_Undef && decision[next]) + rnd_decisions++; } + + // Activity based decision: + while (next == var_Undef || value(next) != l_Undef || !decision[next]) + if (order_heap.empty()){ + next = var_Undef; + break; + }else + next = order_heap.removeMin(); + + return next == var_Undef ? lit_Undef : mkLit(next, rnd_pol ? drand(random_seed) < 0.5 : polarity[next]); +} + + +/*_________________________________________________________________________________________________ +| +| analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void] +| +| Description: +| Analyze conflict and produce a reason clause. +| +| Pre-conditions: +| * 'out_learnt' is assumed to be cleared. +| * Current decision level must be greater than root level. +| +| Post-conditions: +| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. +| * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the +| rest of literals. There may be others from the same level though. +| +|________________________________________________________________________________________________@*/ +void Solver::analyze(CRef confl, vec<Lit>& out_learnt, int& out_btlevel) +{ + int pathC = 0; + Lit p = lit_Undef; + + // Generate conflict clause: + // + out_learnt.push(); // (leave room for the asserting literal) + int index = trail.size() - 1; + + do{ + assert(confl != CRef_Undef); // (otherwise should be UIP) + Clause& c = ca[confl]; + + if (c.learnt()) + claBumpActivity(c); + + for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ + Lit q = c[j]; + + if (!seen[var(q)] && level(var(q)) > 0){ + varBumpActivity(var(q)); + seen[var(q)] = 1; + if (level(var(q)) >= decisionLevel()) + pathC++; + else + out_learnt.push(q); + } + } + + // Select next clause to look at: + while (!seen[var(trail[index--])]); + p = trail[index+1]; + confl = reason(var(p)); + seen[var(p)] = 0; + pathC--; + + }while (pathC > 0); + out_learnt[0] = ~p; + + // Simplify conflict clause: + // + int i, j; + out_learnt.copyTo(analyze_toclear); + if (ccmin_mode == 2){ + uint32_t abstract_level = 0; + for (i = 1; i < out_learnt.size(); i++) + abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict) + + for (i = j = 1; i < out_learnt.size(); i++) + if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level)) + out_learnt[j++] = out_learnt[i]; + + }else if (ccmin_mode == 1){ + for (i = j = 1; i < out_learnt.size(); i++){ + Var x = var(out_learnt[i]); + + if (reason(x) == CRef_Undef) + out_learnt[j++] = out_learnt[i]; + else{ + Clause& c = ca[reason(var(out_learnt[i]))]; + for (int k = 1; k < c.size(); k++) + if (!seen[var(c[k])] && level(var(c[k])) > 0){ + out_learnt[j++] = out_learnt[i]; + break; } + } + } + }else + i = j = out_learnt.size(); + + max_literals += out_learnt.size(); + out_learnt.shrink(i - j); + tot_literals += out_learnt.size(); + + // Find correct backtrack level: + // + if (out_learnt.size() == 1) + out_btlevel = 0; + else{ + int max_i = 1; + // Find the first literal assigned at the next-highest level: + for (int i = 2; i < out_learnt.size(); i++) + if (level(var(out_learnt[i])) > level(var(out_learnt[max_i]))) + max_i = i; + // Swap-in this literal at index 1: + Lit p = out_learnt[max_i]; + out_learnt[max_i] = out_learnt[1]; + out_learnt[1] = p; + out_btlevel = level(var(p)); + } + + for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) +} + + +// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is +// visiting literals at levels that cannot be removed later. +bool Solver::litRedundant(Lit p, uint32_t abstract_levels) +{ + analyze_stack.clear(); analyze_stack.push(p); + int top = analyze_toclear.size(); + while (analyze_stack.size() > 0){ + assert(reason(var(analyze_stack.last())) != CRef_Undef); + Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop(); + + for (int i = 1; i < c.size(); i++){ + Lit p = c[i]; + if (!seen[var(p)] && level(var(p)) > 0){ + if (reason(var(p)) != CRef_Undef && (abstractLevel(var(p)) & abstract_levels) != 0){ + seen[var(p)] = 1; + analyze_stack.push(p); + analyze_toclear.push(p); + }else{ + for (int j = top; j < analyze_toclear.size(); j++) + seen[var(analyze_toclear[j])] = 0; + analyze_toclear.shrink(analyze_toclear.size() - top); + return false; + } + } + } + } + + return true; +} + + +/*_________________________________________________________________________________________________ +| +| analyzeFinal : (p : Lit) -> [void] +| +| Description: +| Specialized analysis procedure to express the final conflict in terms of assumptions. +| Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and +| stores the result in 'out_conflict'. +|________________________________________________________________________________________________@*/ +void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict) +{ + out_conflict.clear(); + out_conflict.push(p); + + if (decisionLevel() == 0) + return; + + seen[var(p)] = 1; + + for (int i = trail.size()-1; i >= trail_lim[0]; i--){ + Var x = var(trail[i]); + if (seen[x]){ + if (reason(x) == CRef_Undef){ + assert(level(x) > 0); + out_conflict.push(~trail[i]); + }else{ + Clause& c = ca[reason(x)]; + for (int j = 1; j < c.size(); j++) + if (level(var(c[j])) > 0) + seen[var(c[j])] = 1; + } + seen[x] = 0; + } + } + + seen[var(p)] = 0; +} + + +void Solver::uncheckedEnqueue(Lit p, CRef from) +{ + assert(value(p) == l_Undef); + assigns[var(p)] = lbool(!sign(p)); + vardata[var(p)] = mkVarData(from, decisionLevel()); + trail.push_(p); +} + + +/*_________________________________________________________________________________________________ +| +| propagate : [void] -> [Clause*] +| +| Description: +| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, +| otherwise CRef_Undef. +| +| Post-conditions: +| * the propagation queue is empty, even if there was a conflict. +|________________________________________________________________________________________________@*/ +CRef Solver::propagate() +{ + CRef confl = CRef_Undef; + int num_props = 0; + watches.cleanAll(); + + while (qhead < trail.size()){ + Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. + vec<Watcher>& ws = watches[p]; + Watcher *i, *j, *end; + num_props++; + + for (i = j = (Watcher*)ws, end = i + ws.size(); i != end;){ + // Try to avoid inspecting the clause: + Lit blocker = i->blocker; + if (value(blocker) == l_True){ + *j++ = *i++; continue; } + + // Make sure the false literal is data[1]: + CRef cr = i->cref; + Clause& c = ca[cr]; + Lit false_lit = ~p; + if (c[0] == false_lit) + c[0] = c[1], c[1] = false_lit; + assert(c[1] == false_lit); + i++; + + // If 0th watch is true, then clause is already satisfied. + Lit first = c[0]; + Watcher w = Watcher(cr, first); + if (first != blocker && value(first) == l_True){ + *j++ = w; continue; } + + // Look for new watch: + for (int k = 2; k < c.size(); k++) + if (value(c[k]) != l_False){ + c[1] = c[k]; c[k] = false_lit; + watches[~c[1]].push(w); + goto NextClause; } + + // Did not find watch -- clause is unit under assignment: + *j++ = w; + if (value(first) == l_False){ + confl = cr; + qhead = trail.size(); + // Copy the remaining watches: + while (i < end) + *j++ = *i++; + }else + uncheckedEnqueue(first, cr); + + NextClause:; + } + ws.shrink(i - j); + } + propagations += num_props; + simpDB_props -= num_props; + + return confl; +} + + +/*_________________________________________________________________________________________________ +| +| reduceDB : () -> [void] +| +| Description: +| Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked +| clauses are clauses that are reason to some assignment. Binary clauses are never removed. +|________________________________________________________________________________________________@*/ +struct reduceDB_lt { + ClauseAllocator& ca; + reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {} + bool operator () (CRef x, CRef y) { + return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); } +}; +void Solver::reduceDB() +{ + int i, j; + double extra_lim = cla_inc / learnts.size(); // Remove any clause below this activity + + sort(learnts, reduceDB_lt(ca)); + // Don't delete binary or locked clauses. From the rest, delete clauses from the first half + // and clauses with activity smaller than 'extra_lim': + for (i = j = 0; i < learnts.size(); i++){ + Clause& c = ca[learnts[i]]; + if (c.size() > 2 && !locked(c) && (i < learnts.size() / 2 || c.activity() < extra_lim)) + removeClause(learnts[i]); + else + learnts[j++] = learnts[i]; + } + learnts.shrink(i - j); + checkGarbage(); +} + + +void Solver::removeSatisfied(vec<CRef>& cs) +{ + int i, j; + for (i = j = 0; i < cs.size(); i++){ + Clause& c = ca[cs[i]]; + if (satisfied(c)) + removeClause(cs[i]); + else + cs[j++] = cs[i]; + } + cs.shrink(i - j); +} + + +void Solver::rebuildOrderHeap() +{ + vec<Var> vs; + for (Var v = 0; v < nVars(); v++) + if (decision[v] && value(v) == l_Undef) + vs.push(v); + order_heap.build(vs); +} + + +/*_________________________________________________________________________________________________ +| +| simplify : [void] -> [bool] +| +| Description: +| Simplify the clause database according to the current top-level assigment. Currently, the only +| thing done here is the removal of satisfied clauses, but more things can be put here. +|________________________________________________________________________________________________@*/ +bool Solver::simplify() +{ + assert(decisionLevel() == 0); + + if (!ok || propagate() != CRef_Undef) + return ok = false; + + if (nAssigns() == simpDB_assigns || (simpDB_props > 0)) + return true; + + // Remove satisfied clauses: + removeSatisfied(learnts); + if (remove_satisfied) // Can be turned off. + removeSatisfied(clauses); + checkGarbage(); + rebuildOrderHeap(); + + simpDB_assigns = nAssigns(); + simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now) + + return true; +} + + +/*_________________________________________________________________________________________________ +| +| search : (nof_conflicts : int) (params : const SearchParams&) -> [lbool] +| +| Description: +| Search for a model the specified number of conflicts. +| NOTE! Use negative value for 'nof_conflicts' indicate infinity. +| +| Output: +| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If +| all variables are decision variables, this means that the clause set is satisfiable. 'l_False' +| if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. +|________________________________________________________________________________________________@*/ +lbool Solver::search(int nof_conflicts) +{ + assert(ok); + int backtrack_level; + int conflictC = 0; + vec<Lit> learnt_clause; + starts++; + + for (;;){ + CRef confl = propagate(); + if (confl != CRef_Undef){ + // CONFLICT + conflicts++; conflictC++; + if (decisionLevel() == 0) return l_False; + + learnt_clause.clear(); + analyze(confl, learnt_clause, backtrack_level); + cancelUntil(backtrack_level); + + if (learnt_clause.size() == 1){ + uncheckedEnqueue(learnt_clause[0]); + }else{ + CRef cr = ca.alloc(learnt_clause, true); + learnts.push(cr); + attachClause(cr); + claBumpActivity(ca[cr]); + uncheckedEnqueue(learnt_clause[0], cr); + } + + varDecayActivity(); + claDecayActivity(); + + if (--learntsize_adjust_cnt == 0){ + learntsize_adjust_confl *= learntsize_adjust_inc; + learntsize_adjust_cnt = (int)learntsize_adjust_confl; + max_learnts *= learntsize_inc; + + if (verbosity >= 1) + printf("| %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n", + (int)conflicts, + (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals, + (int)max_learnts, nLearnts(), (double)learnts_literals/nLearnts(), progressEstimate()*100); + } + + }else{ + // NO CONFLICT + if (nof_conflicts >= 0 && conflictC >= nof_conflicts || !withinBudget()){ + // Reached bound on number of conflicts: + progress_estimate = progressEstimate(); + cancelUntil(0); + return l_Undef; } + + // Simplify the set of problem clauses: + if (decisionLevel() == 0 && !simplify()) + return l_False; + + if (learnts.size()-nAssigns() >= max_learnts) + // Reduce the set of learnt clauses: + reduceDB(); + + Lit next = lit_Undef; + while (decisionLevel() < assumptions.size()){ + // Perform user provided assumption: + Lit p = assumptions[decisionLevel()]; + if (value(p) == l_True){ + // Dummy decision level: + newDecisionLevel(); + }else if (value(p) == l_False){ + analyzeFinal(~p, conflict); + return l_False; + }else{ + next = p; + break; + } + } + + if (next == lit_Undef){ + // New variable decision: + decisions++; + next = pickBranchLit(); + + if (next == lit_Undef) + // Model found: + return l_True; + } + + // Increase decision level and enqueue 'next' + newDecisionLevel(); + uncheckedEnqueue(next); + } + } +} + + +double Solver::progressEstimate() const +{ + double progress = 0; + double F = 1.0 / nVars(); + + for (int i = 0; i <= decisionLevel(); i++){ + int beg = i == 0 ? 0 : trail_lim[i - 1]; + int end = i == decisionLevel() ? trail.size() : trail_lim[i]; + progress += pow(F, i) * (end - beg); + } + + return progress / nVars(); +} + +/* + Finite subsequences of the Luby-sequence: + + 0: 1 + 1: 1 1 2 + 2: 1 1 2 1 1 2 4 + 3: 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8 + ... + + + */ + +static double luby(double y, int x){ + + // Find the finite subsequence that contains index 'x', and the + // size of that subsequence: + int size, seq; + for (size = 1, seq = 0; size < x+1; seq++, size = 2*size+1); + + while (size-1 != x){ + size = (size-1)>>1; + seq--; + x = x % size; + } + + return pow(y, seq); +} + +// NOTE: assumptions passed in member-variable 'assumptions'. +lbool Solver::solve_() +{ + model.clear(); + conflict.clear(); + if (!ok) return l_False; + + solves++; + + max_learnts = nClauses() * learntsize_factor; + learntsize_adjust_confl = learntsize_adjust_start_confl; + learntsize_adjust_cnt = (int)learntsize_adjust_confl; + lbool status = l_Undef; + + if (verbosity >= 1){ + printf("============================[ Search Statistics ]==============================\n"); + printf("| Conflicts | ORIGINAL | LEARNT | Progress |\n"); + printf("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |\n"); + printf("===============================================================================\n"); + } + + // Search: + int curr_restarts = 0; + while (status == l_Undef){ + double rest_base = luby_restart ? luby(restart_inc, curr_restarts) : pow(restart_inc, curr_restarts); + status = search(rest_base * restart_first); + if (!withinBudget()) break; + curr_restarts++; + } + + if (verbosity >= 1) + printf("===============================================================================\n"); + + + if (status == l_True){ + // Extend & copy model: + model.growTo(nVars()); + for (int i = 0; i < nVars(); i++) model[i] = value(i); + }else if (status == l_False && conflict.size() == 0) + ok = false; + + cancelUntil(0); + return status; +} + +//================================================================================================= +// Writing CNF to DIMACS: +// +// FIXME: this needs to be rewritten completely. + +static Var mapVar(Var x, vec<Var>& map, Var& max) +{ + if (map.size() <= x || map[x] == -1){ + map.growTo(x+1, -1); + map[x] = max++; + } + return map[x]; +} + + +void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max) +{ + if (satisfied(c)) return; + + for (int i = 0; i < c.size(); i++) + if (value(c[i]) != l_False) + fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", mapVar(var(c[i]), map, max)+1); + fprintf(f, "0\n"); +} + + +void Solver::toDimacs(const char *file, const vec<Lit>& assumps) +{ + FILE* f = fopen(file, "wr"); + if (f == NULL) + fprintf(stderr, "could not open file %s\n", file), exit(1); + toDimacs(f, assumps); + fclose(f); +} + + +void Solver::toDimacs(FILE* f, const vec<Lit>& assumps) +{ + // Handle case when solver is in contradictory state: + if (!ok){ + fprintf(f, "p cnf 1 2\n1 0\n-1 0\n"); + return; } + + vec<Var> map; Var max = 0; + + // Cannot use removeClauses here because it is not safe + // to deallocate them at this point. Could be improved. + int cnt = 0; + for (int i = 0; i < clauses.size(); i++) + if (!satisfied(ca[clauses[i]])) + cnt++; + + for (int i = 0; i < clauses.size(); i++) + if (!satisfied(ca[clauses[i]])){ + Clause& c = ca[clauses[i]]; + for (int j = 0; j < c.size(); j++) + if (value(c[j]) != l_False) + mapVar(var(c[j]), map, max); + } + + // Assumptions are added as unit clauses: + cnt += assumptions.size(); + + fprintf(f, "p cnf %d %d\n", max, cnt); + + for (int i = 0; i < assumptions.size(); i++){ + assert(value(assumptions[i]) != l_False); + fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1); + } + + for (int i = 0; i < clauses.size(); i++) + toDimacs(f, ca[clauses[i]], map, max); + + if (verbosity > 0) + printf("Wrote %d clauses with %d variables.\n", cnt, max); +} + + +//================================================================================================= +// Garbage Collection methods: + +void Solver::relocAll(ClauseAllocator& to) +{ + // All watchers: + // + // for (int i = 0; i < watches.size(); i++) + watches.cleanAll(); + for (int v = 0; v < nVars(); v++) + for (int s = 0; s < 2; s++){ + Lit p = mkLit(v, s); + // printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1); + vec<Watcher>& ws = watches[p]; + for (int j = 0; j < ws.size(); j++) + ca.reloc(ws[j].cref, to); + } + + // All reasons: + // + for (int i = 0; i < trail.size(); i++){ + Var v = var(trail[i]); + + if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)]))) + ca.reloc(vardata[v].reason, to); + } + + // All learnt: + // + for (int i = 0; i < learnts.size(); i++) + ca.reloc(learnts[i], to); + + // All original: + // + for (int i = 0; i < clauses.size(); i++) + ca.reloc(clauses[i], to); +} + + +void Solver::garbageCollect() +{ + // Initialize the next region to a size corresponding to the estimated utilization degree. This + // is not precise but should avoid some unnecessary reallocations for the new region: + ClauseAllocator to(ca.size() - ca.wasted()); + + relocAll(to); + if (verbosity >= 2) + printf("| Garbage collection: %12d bytes => %12d bytes |\n", + ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size); + to.moveTo(ca); +} + diff --git a/src/prop/bvminisat/core/Solver.h b/src/prop/bvminisat/core/Solver.h new file mode 100644 index 000000000..f364a2937 --- /dev/null +++ b/src/prop/bvminisat/core/Solver.h @@ -0,0 +1,374 @@ +/****************************************************************************************[Solver.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Solver_h +#define BVMinisat_Solver_h + +#include "prop/bvminisat/core/SolverTypes.h" +#include "prop/bvminisat/mtl/Vec.h" +#include "prop/bvminisat/mtl/Heap.h" +#include "prop/bvminisat/mtl/Alg.h" +#include "prop/bvminisat/utils/Options.h" + + +namespace BVMinisat { + +//================================================================================================= +// Solver -- the main class: + +class Solver { +public: + + // Constructor/Destructor: + // + Solver(); + virtual ~Solver(); + + // Problem specification: + // + Var newVar (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode. + + bool addClause (const vec<Lit>& ps); // Add a clause to the solver. + bool addEmptyClause(); // Add the empty clause, making the solver contradictory. + bool addClause (Lit p); // Add a unit clause to the solver. + bool addClause (Lit p, Lit q); // Add a binary clause to the solver. + bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver. + bool addClause_( vec<Lit>& ps); // Add a clause to the solver without making superflous internal copy. Will + // change the passed vector 'ps'. + + // Solving: + // + bool simplify (); // Removes already satisfied clauses. + bool solve (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions. + lbool solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints). + bool solve (); // Search without assumptions. + bool solve (Lit p); // Search for a model that respects a single assumption. + bool solve (Lit p, Lit q); // Search for a model that respects two assumptions. + bool solve (Lit p, Lit q, Lit r); // Search for a model that respects three assumptions. + bool okay () const; // FALSE means solver is in a conflicting state + + void toDimacs (FILE* f, const vec<Lit>& assumps); // Write CNF to file in DIMACS-format. + void toDimacs (const char *file, const vec<Lit>& assumps); + void toDimacs (FILE* f, Clause& c, vec<Var>& map, Var& max); + + // Convenience versions of 'toDimacs()': + void toDimacs (const char* file); + void toDimacs (const char* file, Lit p); + void toDimacs (const char* file, Lit p, Lit q); + void toDimacs (const char* file, Lit p, Lit q, Lit r); + + // Variable mode: + // + void setPolarity (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'. + void setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic. + + // Read state: + // + lbool value (Var x) const; // The current value of a variable. + lbool value (Lit p) const; // The current value of a literal. + lbool modelValue (Var x) const; // The value of a variable in the last model. The last call to solve must have been satisfiable. + lbool modelValue (Lit p) const; // The value of a literal in the last model. The last call to solve must have been satisfiable. + int nAssigns () const; // The current number of assigned literals. + int nClauses () const; // The current number of original clauses. + int nLearnts () const; // The current number of learnt clauses. + int nVars () const; // The current number of variables. + int nFreeVars () const; + + // Resource contraints: + // + void setConfBudget(int64_t x); + void setPropBudget(int64_t x); + void budgetOff(); + void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver. + void clearInterrupt(); // Clear interrupt indicator flag. + + // Memory managment: + // + virtual void garbageCollect(); + void checkGarbage(double gf); + void checkGarbage(); + + // Extra results: (read-only member variable) + // + vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any). + vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions), + // this vector represent the final conflict clause expressed in the assumptions. + + // Mode of operation: + // + int verbosity; + double var_decay; + double clause_decay; + double random_var_freq; + double random_seed; + bool luby_restart; + int ccmin_mode; // Controls conflict clause minimization (0=none, 1=basic, 2=deep). + int phase_saving; // Controls the level of phase saving (0=none, 1=limited, 2=full). + bool rnd_pol; // Use random polarities for branching heuristics. + bool rnd_init_act; // Initialize variable activities with a small random value. + double garbage_frac; // The fraction of wasted memory allowed before a garbage collection is triggered. + + int restart_first; // The initial restart limit. (default 100) + double restart_inc; // The factor with which the restart limit is multiplied in each restart. (default 1.5) + double learntsize_factor; // The intitial limit for learnt clauses is a factor of the original clauses. (default 1 / 3) + double learntsize_inc; // The limit for learnt clauses is multiplied with this factor each restart. (default 1.1) + + int learntsize_adjust_start_confl; + double learntsize_adjust_inc; + + // Statistics: (read-only member variable) + // + uint64_t solves, starts, decisions, rnd_decisions, propagations, conflicts; + uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals; + + +protected: + + // Helper structures: + // + struct VarData { CRef reason; int level; }; + static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; } + + struct Watcher { + CRef cref; + Lit blocker; + Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {} + bool operator==(const Watcher& w) const { return cref == w.cref; } + bool operator!=(const Watcher& w) const { return cref != w.cref; } + }; + + struct WatcherDeleted + { + const ClauseAllocator& ca; + WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {} + bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; } + }; + + struct VarOrderLt { + const vec<double>& activity; + bool operator () (Var x, Var y) const { return activity[x] > activity[y]; } + VarOrderLt(const vec<double>& act) : activity(act) { } + }; + + // Solver state: + // + bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used! + vec<CRef> clauses; // List of problem clauses. + vec<CRef> learnts; // List of learnt clauses. + double cla_inc; // Amount to bump next clause with. + vec<double> activity; // A heuristic measurement of the activity of a variable. + double var_inc; // Amount to bump next variable with. + OccLists<Lit, vec<Watcher>, WatcherDeleted> + watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true). + vec<lbool> assigns; // The current assignments. + vec<char> polarity; // The preferred polarity of each variable. + vec<char> decision; // Declares if a variable is eligible for selection in the decision heuristic. + vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made. + vec<int> trail_lim; // Separator indices for different decision levels in 'trail'. + vec<VarData> vardata; // Stores reason and level for each variable. + int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat). + int simpDB_assigns; // Number of top-level assignments since last execution of 'simplify()'. + int64_t simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplify()'. + vec<Lit> assumptions; // Current set of assumptions provided to solve by the user. + Heap<VarOrderLt> order_heap; // A priority queue of variables ordered with respect to the variable activity. + double progress_estimate;// Set by 'search()'. + bool remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'. + + ClauseAllocator ca; + + // Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is + // used, exept 'seen' wich is used in several places. + // + vec<char> seen; + vec<Lit> analyze_stack; + vec<Lit> analyze_toclear; + vec<Lit> add_tmp; + + double max_learnts; + double learntsize_adjust_confl; + int learntsize_adjust_cnt; + + // Resource contraints: + // + int64_t conflict_budget; // -1 means no budget. + int64_t propagation_budget; // -1 means no budget. + bool asynch_interrupt; + + // Main internal methods: + // + void insertVarOrder (Var x); // Insert a variable in the decision order priority queue. + Lit pickBranchLit (); // Return the next decision variable. + void newDecisionLevel (); // Begins a new decision level. + void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined. + bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise. + CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause. + void cancelUntil (int level); // Backtrack until a certain level. + void analyze (CRef confl, vec<Lit>& out_learnt, int& out_btlevel); // (bt = backtrack) + void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION? + bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()') + lbool search (int nof_conflicts); // Search for a given number of conflicts. + lbool solve_ (); // Main solve method (assumptions given in 'assumptions'). + void reduceDB (); // Reduce the set of learnt clauses. + void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses. + void rebuildOrderHeap (); + + // Maintaining Variable/Clause activity: + // + void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead. + void varBumpActivity (Var v, double inc); // Increase a variable with the current 'bump' value. + void varBumpActivity (Var v); // Increase a variable with the current 'bump' value. + void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead. + void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value. + + // Operations on clauses: + // + void attachClause (CRef cr); // Attach a clause to watcher lists. + void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists. + void removeClause (CRef cr); // Detach and free a clause. + bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state. + bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state. + + void relocAll (ClauseAllocator& to); + + // Misc: + // + int decisionLevel () const; // Gives the current decisionlevel. + uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels. + CRef reason (Var x) const; + int level (Var x) const; + double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ... + bool withinBudget () const; + + // Static helpers: + // + + // Returns a random float 0 <= x < 1. Seed must never be 0. + static inline double drand(double& seed) { + seed *= 1389796; + int q = (int)(seed / 2147483647); + seed -= (double)q * 2147483647; + return seed / 2147483647; } + + // Returns a random integer 0 <= x < size. Seed must never be 0. + static inline int irand(double& seed, int size) { + return (int)(drand(seed) * size); } +}; + + +//================================================================================================= +// Implementation of inline methods: + +inline CRef Solver::reason(Var x) const { return vardata[x].reason; } +inline int Solver::level (Var x) const { return vardata[x].level; } + +inline void Solver::insertVarOrder(Var x) { + if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); } + +inline void Solver::varDecayActivity() { var_inc *= (1 / var_decay); } +inline void Solver::varBumpActivity(Var v) { varBumpActivity(v, var_inc); } +inline void Solver::varBumpActivity(Var v, double inc) { + if ( (activity[v] += inc) > 1e100 ) { + // Rescale: + for (int i = 0; i < nVars(); i++) + activity[i] *= 1e-100; + var_inc *= 1e-100; } + + // Update order_heap with respect to new activity: + if (order_heap.inHeap(v)) + order_heap.decrease(v); } + +inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); } +inline void Solver::claBumpActivity (Clause& c) { + if ( (c.activity() += cla_inc) > 1e20 ) { + // Rescale: + for (int i = 0; i < learnts.size(); i++) + ca[learnts[i]].activity() *= 1e-20; + cla_inc *= 1e-20; } } + +inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); } +inline void Solver::checkGarbage(double gf){ + if (ca.wasted() > ca.size() * gf) + garbageCollect(); } + +// NOTE: enqueue does not set the ok flag! (only public methods do) +inline bool Solver::enqueue (Lit p, CRef from) { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); } +inline bool Solver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); } +inline bool Solver::addEmptyClause () { add_tmp.clear(); return addClause_(add_tmp); } +inline bool Solver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); } +inline bool Solver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); } +inline bool Solver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); } +inline bool Solver::locked (const Clause& c) const { return value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c; } +inline void Solver::newDecisionLevel() { trail_lim.push(trail.size()); } + +inline int Solver::decisionLevel () const { return trail_lim.size(); } +inline uint32_t Solver::abstractLevel (Var x) const { return 1 << (level(x) & 31); } +inline lbool Solver::value (Var x) const { return assigns[x]; } +inline lbool Solver::value (Lit p) const { return assigns[var(p)] ^ sign(p); } +inline lbool Solver::modelValue (Var x) const { return model[x]; } +inline lbool Solver::modelValue (Lit p) const { return model[var(p)] ^ sign(p); } +inline int Solver::nAssigns () const { return trail.size(); } +inline int Solver::nClauses () const { return clauses.size(); } +inline int Solver::nLearnts () const { return learnts.size(); } +inline int Solver::nVars () const { return vardata.size(); } +inline int Solver::nFreeVars () const { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); } +inline void Solver::setPolarity (Var v, bool b) { polarity[v] = b; } +inline void Solver::setDecisionVar(Var v, bool b) +{ + if ( b && !decision[v]) dec_vars++; + else if (!b && decision[v]) dec_vars--; + + decision[v] = b; + insertVarOrder(v); +} +inline void Solver::setConfBudget(int64_t x){ conflict_budget = conflicts + x; } +inline void Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; } +inline void Solver::interrupt(){ asynch_interrupt = true; } +inline void Solver::clearInterrupt(){ asynch_interrupt = false; } +inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; } +inline bool Solver::withinBudget() const { + return !asynch_interrupt && + (conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) && + (propagation_budget < 0 || propagations < (uint64_t)propagation_budget); } + +// FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a +// pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or +// all calls to solve must return an 'lbool'. I'm not yet sure which I prefer. +inline bool Solver::solve () { budgetOff(); assumptions.clear(); return solve_() == l_True; } +inline bool Solver::solve (Lit p) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; } +inline bool Solver::solve (Lit p, Lit q) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; } +inline bool Solver::solve (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; } +inline bool Solver::solve (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; } +inline lbool Solver::solveLimited (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); } +inline bool Solver::okay () const { return ok; } + +inline void Solver::toDimacs (const char* file){ vec<Lit> as; toDimacs(file, as); } +inline void Solver::toDimacs (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); } +inline void Solver::toDimacs (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); } +inline void Solver::toDimacs (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); } + + +//================================================================================================= +// Debug etc: + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/core/SolverTypes.h b/src/prop/bvminisat/core/SolverTypes.h new file mode 100644 index 000000000..3709715b9 --- /dev/null +++ b/src/prop/bvminisat/core/SolverTypes.h @@ -0,0 +1,408 @@ +/***********************************************************************************[SolverTypes.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_SolverTypes_h +#define BVMinisat_SolverTypes_h + +#include <assert.h> + +#include "prop/bvminisat/mtl/IntTypes.h" +#include "prop/bvminisat/mtl/Alg.h" +#include "prop/bvminisat/mtl/Vec.h" +#include "prop/bvminisat/mtl/Map.h" +#include "prop/bvminisat/mtl/Alloc.h" + +namespace BVMinisat { + +//================================================================================================= +// Variables, literals, lifted booleans, clauses: + + +// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N, +// so that they can be used as array indices. + +typedef int Var; +#define var_Undef (-1) + + +struct Lit { + int x; + + // Use this as a constructor: + friend Lit mkLit(Var var, bool sign = false); + + bool operator == (Lit p) const { return x == p.x; } + bool operator != (Lit p) const { return x != p.x; } + bool operator < (Lit p) const { return x < p.x; } // '<' makes p, ~p adjacent in the ordering. +}; + + +inline Lit mkLit (Var var, bool sign) { Lit p; p.x = var + var + (int)sign; return p; } +inline Lit operator ~(Lit p) { Lit q; q.x = p.x ^ 1; return q; } +inline Lit operator ^(Lit p, bool b) { Lit q; q.x = p.x ^ (unsigned int)b; return q; } +inline bool sign (Lit p) { return p.x & 1; } +inline int var (Lit p) { return p.x >> 1; } + +// Mapping Literals to and from compact integers suitable for array indexing: +inline int toInt (Var v) { return v; } +inline int toInt (Lit p) { return p.x; } +inline Lit toLit (int i) { Lit p; p.x = i; return p; } + +//const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special constants. +//const Lit lit_Error = mkLit(var_Undef, true ); // } + +const Lit lit_Undef = { -2 }; // }- Useful special constants. +const Lit lit_Error = { -1 }; // } + + +//================================================================================================= +// Lifted booleans: +// +// NOTE: this implementation is optimized for the case when comparisons between values are mostly +// between one variable and one constant. Some care had to be taken to make sure that gcc +// does enough constant propagation to produce sensible code, and this appears to be somewhat +// fragile unfortunately. + +#define l_True (lbool((uint8_t)0)) // gcc does not do constant propagation if these are real constants. +#define l_False (lbool((uint8_t)1)) +#define l_Undef (lbool((uint8_t)2)) + +class lbool { + uint8_t value; + +public: + explicit lbool(uint8_t v) : value(v) { } + + lbool() : value(0) { } + explicit lbool(bool x) : value(!x) { } + + bool operator == (lbool b) const { return ((b.value&2) & (value&2)) | (!(b.value&2)&(value == b.value)); } + bool operator != (lbool b) const { return !(*this == b); } + lbool operator ^ (bool b) const { return lbool((uint8_t)(value^(uint8_t)b)); } + + lbool operator && (lbool b) const { + uint8_t sel = (this->value << 1) | (b.value << 3); + uint8_t v = (0xF7F755F4 >> sel) & 3; + return lbool(v); } + + lbool operator || (lbool b) const { + uint8_t sel = (this->value << 1) | (b.value << 3); + uint8_t v = (0xFCFCF400 >> sel) & 3; + return lbool(v); } + + friend int toInt (lbool l); + friend lbool toLbool(int v); +}; +inline int toInt (lbool l) { return l.value; } +inline lbool toLbool(int v) { return lbool((uint8_t)v); } + +//================================================================================================= +// Clause -- a simple class for representing a clause: + +class Clause; +typedef RegionAllocator<uint32_t>::Ref CRef; + +class Clause { + struct { + unsigned mark : 2; + unsigned learnt : 1; + unsigned has_extra : 1; + unsigned reloced : 1; + unsigned size : 27; } header; + union { Lit lit; float act; uint32_t abs; CRef rel; } data[0]; + + friend class ClauseAllocator; + + // NOTE: This constructor cannot be used directly (doesn't allocate enough memory). + template<class V> + Clause(const V& ps, bool use_extra, bool learnt) { + header.mark = 0; + header.learnt = learnt; + header.has_extra = use_extra; + header.reloced = 0; + header.size = ps.size(); + + for (int i = 0; i < ps.size(); i++) + data[i].lit = ps[i]; + + if (header.has_extra){ + if (header.learnt) + data[header.size].act = 0; + else + calcAbstraction(); } + } + +public: + void calcAbstraction() { + assert(header.has_extra); + uint32_t abstraction = 0; + for (int i = 0; i < size(); i++) + abstraction |= 1 << (var(data[i].lit) & 31); + data[header.size].abs = abstraction; } + + + int size () const { return header.size; } + void shrink (int i) { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; } + void pop () { shrink(1); } + bool learnt () const { return header.learnt; } + bool has_extra () const { return header.has_extra; } + uint32_t mark () const { return header.mark; } + void mark (uint32_t m) { header.mark = m; } + const Lit& last () const { return data[header.size-1].lit; } + + bool reloced () const { return header.reloced; } + CRef relocation () const { return data[0].rel; } + void relocate (CRef c) { header.reloced = 1; data[0].rel = c; } + + // NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for + // subsumption operations to behave correctly. + Lit& operator [] (int i) { return data[i].lit; } + Lit operator [] (int i) const { return data[i].lit; } + operator const Lit* (void) const { return (Lit*)data; } + + float& activity () { assert(header.has_extra); return data[header.size].act; } + uint32_t abstraction () const { assert(header.has_extra); return data[header.size].abs; } + + Lit subsumes (const Clause& other) const; + void strengthen (Lit p); +}; + + +//================================================================================================= +// ClauseAllocator -- a simple class for allocating memory for clauses: + + +const CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef; +class ClauseAllocator : public RegionAllocator<uint32_t> +{ + static int clauseWord32Size(int size, bool has_extra){ + return (sizeof(Clause) + (sizeof(Lit) * (size + (int)has_extra))) / sizeof(uint32_t); } + public: + bool extra_clause_field; + + ClauseAllocator(uint32_t start_cap) : RegionAllocator<uint32_t>(start_cap), extra_clause_field(false){} + ClauseAllocator() : extra_clause_field(false){} + + void moveTo(ClauseAllocator& to){ + to.extra_clause_field = extra_clause_field; + RegionAllocator<uint32_t>::moveTo(to); } + + template<class Lits> + CRef alloc(const Lits& ps, bool learnt = false) + { + assert(sizeof(Lit) == sizeof(uint32_t)); + assert(sizeof(float) == sizeof(uint32_t)); + bool use_extra = learnt | extra_clause_field; + + CRef cid = RegionAllocator<uint32_t>::alloc(clauseWord32Size(ps.size(), use_extra)); + new (lea(cid)) Clause(ps, use_extra, learnt); + + return cid; + } + + // Deref, Load Effective Address (LEA), Inverse of LEA (AEL): + Clause& operator[](Ref r) { return (Clause&)RegionAllocator<uint32_t>::operator[](r); } + const Clause& operator[](Ref r) const { return (Clause&)RegionAllocator<uint32_t>::operator[](r); } + Clause* lea (Ref r) { return (Clause*)RegionAllocator<uint32_t>::lea(r); } + const Clause* lea (Ref r) const { return (Clause*)RegionAllocator<uint32_t>::lea(r); } + Ref ael (const Clause* t){ return RegionAllocator<uint32_t>::ael((uint32_t*)t); } + + void free(CRef cid) + { + Clause& c = operator[](cid); + RegionAllocator<uint32_t>::free(clauseWord32Size(c.size(), c.has_extra())); + } + + void reloc(CRef& cr, ClauseAllocator& to) + { + Clause& c = operator[](cr); + + if (c.reloced()) { cr = c.relocation(); return; } + + cr = to.alloc(c, c.learnt()); + c.relocate(cr); + + // Copy extra data-fields: + // (This could be cleaned-up. Generalize Clause-constructor to be applicable here instead?) + to[cr].mark(c.mark()); + if (to[cr].learnt()) to[cr].activity() = c.activity(); + else if (to[cr].has_extra()) to[cr].calcAbstraction(); + } +}; + + +//================================================================================================= +// OccLists -- a class for maintaining occurence lists with lazy deletion: + +template<class Idx, class Vec, class Deleted> +class OccLists +{ + vec<Vec> occs; + vec<char> dirty; + vec<Idx> dirties; + Deleted deleted; + + public: + OccLists(const Deleted& d) : deleted(d) {} + + void init (const Idx& idx){ occs.growTo(toInt(idx)+1); dirty.growTo(toInt(idx)+1, 0); } + // Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; } + Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; } + Vec& lookup (const Idx& idx){ if (dirty[toInt(idx)]) clean(idx); return occs[toInt(idx)]; } + + void cleanAll (); + void clean (const Idx& idx); + void smudge (const Idx& idx){ + if (dirty[toInt(idx)] == 0){ + dirty[toInt(idx)] = 1; + dirties.push(idx); + } + } + + void clear(bool free = true){ + occs .clear(free); + dirty .clear(free); + dirties.clear(free); + } +}; + + +template<class Idx, class Vec, class Deleted> +void OccLists<Idx,Vec,Deleted>::cleanAll() +{ + for (int i = 0; i < dirties.size(); i++) + // Dirties may contain duplicates so check here if a variable is already cleaned: + if (dirty[toInt(dirties[i])]) + clean(dirties[i]); + dirties.clear(); +} + + +template<class Idx, class Vec, class Deleted> +void OccLists<Idx,Vec,Deleted>::clean(const Idx& idx) +{ + Vec& vec = occs[toInt(idx)]; + int i, j; + for (i = j = 0; i < vec.size(); i++) + if (!deleted(vec[i])) + vec[j++] = vec[i]; + vec.shrink(i - j); + dirty[toInt(idx)] = 0; +} + + +//================================================================================================= +// CMap -- a class for mapping clauses to values: + + +template<class T> +class CMap +{ + struct CRefHash { + uint32_t operator()(CRef cr) const { return (uint32_t)cr; } }; + + typedef Map<CRef, T, CRefHash> HashTable; + HashTable map; + + public: + // Size-operations: + void clear () { map.clear(); } + int size () const { return map.elems(); } + + + // Insert/Remove/Test mapping: + void insert (CRef cr, const T& t){ map.insert(cr, t); } + void growTo (CRef cr, const T& t){ map.insert(cr, t); } // NOTE: for compatibility + void remove (CRef cr) { map.remove(cr); } + bool has (CRef cr, T& t) { return map.peek(cr, t); } + + // Vector interface (the clause 'c' must already exist): + const T& operator [] (CRef cr) const { return map[cr]; } + T& operator [] (CRef cr) { return map[cr]; } + + // Iteration (not transparent at all at the moment): + int bucket_count() const { return map.bucket_count(); } + const vec<typename HashTable::Pair>& bucket(int i) const { return map.bucket(i); } + + // Move contents to other map: + void moveTo(CMap& other){ map.moveTo(other.map); } + + // TMP debug: + void debug(){ + printf(" --- size = %d, bucket_count = %d\n", size(), map.bucket_count()); } +}; + + +/*_________________________________________________________________________________________________ +| +| subsumes : (other : const Clause&) -> Lit +| +| Description: +| Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other' +| by subsumption resolution. +| +| Result: +| lit_Error - No subsumption or simplification +| lit_Undef - Clause subsumes 'other' +| p - The literal p can be deleted from 'other' +|________________________________________________________________________________________________@*/ +inline Lit Clause::subsumes(const Clause& other) const +{ + //if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0) + //if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0)) + assert(!header.learnt); assert(!other.header.learnt); + assert(header.has_extra); assert(other.header.has_extra); + if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0) + return lit_Error; + + Lit ret = lit_Undef; + const Lit* c = (const Lit*)(*this); + const Lit* d = (const Lit*)other; + + for (unsigned i = 0; i < header.size; i++) { + // search for c[i] or ~c[i] + for (unsigned j = 0; j < other.header.size; j++) + if (c[i] == d[j]) + goto ok; + else if (ret == lit_Undef && c[i] == ~d[j]){ + ret = c[i]; + goto ok; + } + + // did not find it + return lit_Error; + ok:; + } + + return ret; +} + +inline void Clause::strengthen(Lit p) +{ + remove(*this, p); + calcAbstraction(); +} + + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/doc/ReleaseNotes-2.2.0.txt b/src/prop/bvminisat/doc/ReleaseNotes-2.2.0.txt new file mode 100644 index 000000000..7f084de2b --- /dev/null +++ b/src/prop/bvminisat/doc/ReleaseNotes-2.2.0.txt @@ -0,0 +1,79 @@ +Release Notes for MiniSat 2.2.0 +=============================== + +Changes since version 2.0: + + * Started using a more standard release numbering. + + * Includes some now well-known heuristics: phase-saving and luby + restarts. The old heuristics are still present and can be activated + if needed. + + * Detection/Handling of out-of-memory and vector capacity + overflow. This is fairly new and relatively untested. + + * Simple resource controls: CPU-time, memory, number of + conflicts/decisions. + + * CPU-time limiting is implemented by a more general, but simple, + asynchronous interruption feature. This means that the solving + procedure can be interrupted from another thread or in a signal + handler. + + * Improved portability with respect to building on Solaris and with + Visual Studio. This is not regularly tested and chances are that + this have been broken since, but should be fairly easy to fix if + so. + + * Changed C++ file-extention to the less problematic ".cc". + + * Source code is now namespace-protected + + * Introducing a new Clause Memory Allocator that brings reduced + memory consumption on 64-bit architechtures and improved + performance (to some extent). The allocator uses a region-based + approach were all references to clauses are represented as a 32-bit + index into a global memory region that contains all clauses. To + free up and compact memory it uses a simple copying garbage + collector. + + * Improved unit-propagation by Blocking Literals. For each entry in + the watcher lists, pair the pointer to a clause with some + (arbitrary) literal from the clause. The idea is that if the + literal is currently true (i.e. the clause is satisfied) the + watchers of the clause does not need to be altered. This can thus + be detected without touching the clause's memory at all. As often + as can be done cheaply, the blocking literal for entries to the + watcher list of a literal 'p' is set to the other literal watched + in the corresponding clause. + + * Basic command-line/option handling system. Makes it easy to specify + options in the class that they affect, and whenever that class is + used in an executable, parsing of options and help messages are + brought in automatically. + + * General clean-up and various minor bug-fixes. + + * Changed implementation of variable-elimination/model-extension: + + - The interface is changed so that arbitrary remembering is no longer + possible. If you need to mention some variable again in the future, + this variable has to be frozen. + + - When eliminating a variable, only clauses that contain the variable + with one sign is necessary to store. Thereby making the other sign + a "default" value when extending models. + + - The memory consumption for eliminated clauses is further improved + by storing all eliminated clauses in a single contiguous vector. + + * Some common utility code (I/O, Parsing, CPU-time, etc) is ripped + out and placed in a separate "utils" directory. + + * The DIMACS parse is refactored so that it can be reused in other + applications (not very elegant, but at least possible). + + * Some simple improvements to scalability of preprocessing, using + more lazy clause removal from data-structures and a couple of + ad-hoc limits (the longest clause that can be produced in variable + elimination, and the longest clause used in backward subsumption). diff --git a/src/prop/bvminisat/mtl/Alg.h b/src/prop/bvminisat/mtl/Alg.h new file mode 100644 index 000000000..f3ecdecc5 --- /dev/null +++ b/src/prop/bvminisat/mtl/Alg.h @@ -0,0 +1,84 @@ +/*******************************************************************************************[Alg.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Alg_h +#define BVMinisat_Alg_h + +#include "prop/bvminisat/mtl/Vec.h" + +namespace BVMinisat { + +//================================================================================================= +// Useful functions on vector-like types: + +//================================================================================================= +// Removing and searching for elements: +// + +template<class V, class T> +static inline void remove(V& ts, const T& t) +{ + int j = 0; + for (; j < ts.size() && ts[j] != t; j++); + assert(j < ts.size()); + for (; j < ts.size()-1; j++) ts[j] = ts[j+1]; + ts.pop(); +} + + +template<class V, class T> +static inline bool find(V& ts, const T& t) +{ + int j = 0; + for (; j < ts.size() && ts[j] != t; j++); + return j < ts.size(); +} + + +//================================================================================================= +// Copying vectors with support for nested vector types: +// + +// Base case: +template<class T> +static inline void copy(const T& from, T& to) +{ + to = from; +} + +// Recursive case: +template<class T> +static inline void copy(const vec<T>& from, vec<T>& to, bool append = false) +{ + if (!append) + to.clear(); + for (int i = 0; i < from.size(); i++){ + to.push(); + copy(from[i], to.last()); + } +} + +template<class T> +static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); } + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/Alloc.h b/src/prop/bvminisat/mtl/Alloc.h new file mode 100644 index 000000000..f4303044f --- /dev/null +++ b/src/prop/bvminisat/mtl/Alloc.h @@ -0,0 +1,131 @@ +/*****************************************************************************************[Alloc.h] +Copyright (c) 2008-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + + +#ifndef BVMinisat_Alloc_h +#define BVMinisat_Alloc_h + +#include "prop/bvminisat/mtl/XAlloc.h" +#include "prop/bvminisat/mtl/Vec.h" + +namespace BVMinisat { + +//================================================================================================= +// Simple Region-based memory allocator: + +template<class T> +class RegionAllocator +{ + T* memory; + uint32_t sz; + uint32_t cap; + uint32_t wasted_; + + void capacity(uint32_t min_cap); + + public: + // TODO: make this a class for better type-checking? + typedef uint32_t Ref; + enum { Ref_Undef = UINT32_MAX }; + enum { Unit_Size = sizeof(uint32_t) }; + + explicit RegionAllocator(uint32_t start_cap = 1024*1024) : memory(NULL), sz(0), cap(0), wasted_(0){ capacity(start_cap); } + ~RegionAllocator() + { + if (memory != NULL) + ::free(memory); + } + + + uint32_t size () const { return sz; } + uint32_t wasted () const { return wasted_; } + + Ref alloc (int size); + void free (int size) { wasted_ += size; } + + // Deref, Load Effective Address (LEA), Inverse of LEA (AEL): + T& operator[](Ref r) { assert(r >= 0 && r < sz); return memory[r]; } + const T& operator[](Ref r) const { assert(r >= 0 && r < sz); return memory[r]; } + + T* lea (Ref r) { assert(r >= 0 && r < sz); return &memory[r]; } + const T* lea (Ref r) const { assert(r >= 0 && r < sz); return &memory[r]; } + Ref ael (const T* t) { assert((void*)t >= (void*)&memory[0] && (void*)t < (void*)&memory[sz-1]); + return (Ref)(t - &memory[0]); } + + void moveTo(RegionAllocator& to) { + if (to.memory != NULL) ::free(to.memory); + to.memory = memory; + to.sz = sz; + to.cap = cap; + to.wasted_ = wasted_; + + memory = NULL; + sz = cap = wasted_ = 0; + } + + +}; + +template<class T> +void RegionAllocator<T>::capacity(uint32_t min_cap) +{ + if (cap >= min_cap) return; + + uint32_t prev_cap = cap; + while (cap < min_cap){ + // NOTE: Multiply by a factor (13/8) without causing overflow, then add 2 and make the + // result even by clearing the least significant bit. The resulting sequence of capacities + // is carefully chosen to hit a maximum capacity that is close to the '2^32-1' limit when + // using 'uint32_t' as indices so that as much as possible of this space can be used. + uint32_t delta = ((cap >> 1) + (cap >> 3) + 2) & ~1; + cap += delta; + + if (cap <= prev_cap) + throw OutOfMemoryException(); + } + // printf(" .. (%p) cap = %u\n", this, cap); + + assert(cap > 0); + memory = (T*)xrealloc(memory, sizeof(T)*cap); +} + + +template<class T> +typename RegionAllocator<T>::Ref +RegionAllocator<T>::alloc(int size) +{ + // printf("ALLOC called (this = %p, size = %d)\n", this, size); fflush(stdout); + assert(size > 0); + capacity(sz + size); + + uint32_t prev_sz = sz; + sz += size; + + // Handle overflow: + if (sz < prev_sz) + throw OutOfMemoryException(); + + return prev_sz; +} + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/Heap.h b/src/prop/bvminisat/mtl/Heap.h new file mode 100644 index 000000000..d57824ba1 --- /dev/null +++ b/src/prop/bvminisat/mtl/Heap.h @@ -0,0 +1,148 @@ +/******************************************************************************************[Heap.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Heap_h +#define BVMinisat_Heap_h + +#include "prop/bvminisat/mtl/Vec.h" + +namespace BVMinisat { + +//================================================================================================= +// A heap implementation with support for decrease/increase key. + + +template<class Comp> +class Heap { + Comp lt; // The heap is a minimum-heap with respect to this comparator + vec<int> heap; // Heap of integers + vec<int> indices; // Each integers position (index) in the Heap + + // Index "traversal" functions + static inline int left (int i) { return i*2+1; } + static inline int right (int i) { return (i+1)*2; } + static inline int parent(int i) { return (i-1) >> 1; } + + + void percolateUp(int i) + { + int x = heap[i]; + int p = parent(i); + + while (i != 0 && lt(x, heap[p])){ + heap[i] = heap[p]; + indices[heap[p]] = i; + i = p; + p = parent(p); + } + heap [i] = x; + indices[x] = i; + } + + + void percolateDown(int i) + { + int x = heap[i]; + while (left(i) < heap.size()){ + int child = right(i) < heap.size() && lt(heap[right(i)], heap[left(i)]) ? right(i) : left(i); + if (!lt(heap[child], x)) break; + heap[i] = heap[child]; + indices[heap[i]] = i; + i = child; + } + heap [i] = x; + indices[x] = i; + } + + + public: + Heap(const Comp& c) : lt(c) { } + + int size () const { return heap.size(); } + bool empty () const { return heap.size() == 0; } + bool inHeap (int n) const { return n < indices.size() && indices[n] >= 0; } + int operator[](int index) const { assert(index < heap.size()); return heap[index]; } + + + void decrease (int n) { assert(inHeap(n)); percolateUp (indices[n]); } + void increase (int n) { assert(inHeap(n)); percolateDown(indices[n]); } + + + // Safe variant of insert/decrease/increase: + void update(int n) + { + if (!inHeap(n)) + insert(n); + else { + percolateUp(indices[n]); + percolateDown(indices[n]); } + } + + + void insert(int n) + { + indices.growTo(n+1, -1); + assert(!inHeap(n)); + + indices[n] = heap.size(); + heap.push(n); + percolateUp(indices[n]); + } + + + int removeMin() + { + int x = heap[0]; + heap[0] = heap.last(); + indices[heap[0]] = 0; + indices[x] = -1; + heap.pop(); + if (heap.size() > 1) percolateDown(0); + return x; + } + + + // Rebuild the heap from scratch, using the elements in 'ns': + void build(vec<int>& ns) { + for (int i = 0; i < heap.size(); i++) + indices[heap[i]] = -1; + heap.clear(); + + for (int i = 0; i < ns.size(); i++){ + indices[ns[i]] = i; + heap.push(ns[i]); } + + for (int i = heap.size() / 2 - 1; i >= 0; i--) + percolateDown(i); + } + + void clear(bool dealloc = false) + { + for (int i = 0; i < heap.size(); i++) + indices[heap[i]] = -1; + heap.clear(dealloc); + } +}; + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/IntTypes.h b/src/prop/bvminisat/mtl/IntTypes.h new file mode 100644 index 000000000..19ca38bea --- /dev/null +++ b/src/prop/bvminisat/mtl/IntTypes.h @@ -0,0 +1,42 @@ +/**************************************************************************************[IntTypes.h] +Copyright (c) 2009-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_IntTypes_h +#define BVMinisat_IntTypes_h + +#ifdef __sun + // Not sure if there are newer versions that support C99 headers. The + // needed features are implemented in the headers below though: + +# include <sys/int_types.h> +# include <sys/int_fmtio.h> +# include <sys/int_limits.h> + +#else + +# include <stdint.h> +# include <inttypes.h> + +#endif + +#include <limits.h> + +//================================================================================================= + +#endif diff --git a/src/prop/bvminisat/mtl/Map.h b/src/prop/bvminisat/mtl/Map.h new file mode 100644 index 000000000..8bd5659bc --- /dev/null +++ b/src/prop/bvminisat/mtl/Map.h @@ -0,0 +1,193 @@ +/*******************************************************************************************[Map.h] +Copyright (c) 2006-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Map_h +#define BVMinisat_Map_h + +#include "prop/bvminisat/mtl/IntTypes.h" +#include "prop/bvminisat/mtl/Vec.h" + +namespace BVMinisat { + +//================================================================================================= +// Default hash/equals functions +// + +template<class K> struct Hash { uint32_t operator()(const K& k) const { return hash(k); } }; +template<class K> struct Equal { bool operator()(const K& k1, const K& k2) const { return k1 == k2; } }; + +template<class K> struct DeepHash { uint32_t operator()(const K* k) const { return hash(*k); } }; +template<class K> struct DeepEqual { bool operator()(const K* k1, const K* k2) const { return *k1 == *k2; } }; + +static inline uint32_t hash(uint32_t x){ return x; } +static inline uint32_t hash(uint64_t x){ return (uint32_t)x; } +static inline uint32_t hash(int32_t x) { return (uint32_t)x; } +static inline uint32_t hash(int64_t x) { return (uint32_t)x; } + + +//================================================================================================= +// Some primes +// + +static const int nprimes = 25; +static const int primes [nprimes] = { 31, 73, 151, 313, 643, 1291, 2593, 5233, 10501, 21013, 42073, 84181, 168451, 337219, 674701, 1349473, 2699299, 5398891, 10798093, 21596719, 43193641, 86387383, 172775299, 345550609, 691101253 }; + +//================================================================================================= +// Hash table implementation of Maps +// + +template<class K, class D, class H = Hash<K>, class E = Equal<K> > +class Map { + public: + struct Pair { K key; D data; }; + + private: + H hash; + E equals; + + vec<Pair>* table; + int cap; + int size; + + // Don't allow copying (error prone): + Map<K,D,H,E>& operator = (Map<K,D,H,E>& other) { assert(0); } + Map (Map<K,D,H,E>& other) { assert(0); } + + bool checkCap(int new_size) const { return new_size > cap; } + + int32_t index (const K& k) const { return hash(k) % cap; } + void _insert (const K& k, const D& d) { + vec<Pair>& ps = table[index(k)]; + ps.push(); ps.last().key = k; ps.last().data = d; } + + void rehash () { + const vec<Pair>* old = table; + + int old_cap = cap; + int newsize = primes[0]; + for (int i = 1; newsize <= cap && i < nprimes; i++) + newsize = primes[i]; + + table = new vec<Pair>[newsize]; + cap = newsize; + + for (int i = 0; i < old_cap; i++){ + for (int j = 0; j < old[i].size(); j++){ + _insert(old[i][j].key, old[i][j].data); }} + + delete [] old; + + // printf(" --- rehashing, old-cap=%d, new-cap=%d\n", cap, newsize); + } + + + public: + + Map () : table(NULL), cap(0), size(0) {} + Map (const H& h, const E& e) : hash(h), equals(e), table(NULL), cap(0), size(0){} + ~Map () { delete [] table; } + + // PRECONDITION: the key must already exist in the map. + const D& operator [] (const K& k) const + { + assert(size != 0); + const D* res = NULL; + const vec<Pair>& ps = table[index(k)]; + for (int i = 0; i < ps.size(); i++) + if (equals(ps[i].key, k)) + res = &ps[i].data; + assert(res != NULL); + return *res; + } + + // PRECONDITION: the key must already exist in the map. + D& operator [] (const K& k) + { + assert(size != 0); + D* res = NULL; + vec<Pair>& ps = table[index(k)]; + for (int i = 0; i < ps.size(); i++) + if (equals(ps[i].key, k)) + res = &ps[i].data; + assert(res != NULL); + return *res; + } + + // PRECONDITION: the key must *NOT* exist in the map. + void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; } + bool peek (const K& k, D& d) const { + if (size == 0) return false; + const vec<Pair>& ps = table[index(k)]; + for (int i = 0; i < ps.size(); i++) + if (equals(ps[i].key, k)){ + d = ps[i].data; + return true; } + return false; + } + + bool has (const K& k) const { + if (size == 0) return false; + const vec<Pair>& ps = table[index(k)]; + for (int i = 0; i < ps.size(); i++) + if (equals(ps[i].key, k)) + return true; + return false; + } + + // PRECONDITION: the key must exist in the map. + void remove(const K& k) { + assert(table != NULL); + vec<Pair>& ps = table[index(k)]; + int j = 0; + for (; j < ps.size() && !equals(ps[j].key, k); j++); + assert(j < ps.size()); + ps[j] = ps.last(); + ps.pop(); + size--; + } + + void clear () { + cap = size = 0; + delete [] table; + table = NULL; + } + + int elems() const { return size; } + int bucket_count() const { return cap; } + + // NOTE: the hash and equality objects are not moved by this method: + void moveTo(Map& other){ + delete [] other.table; + + other.table = table; + other.cap = cap; + other.size = size; + + table = NULL; + size = cap = 0; + } + + // NOTE: given a bit more time, I could make a more C++-style iterator out of this: + const vec<Pair>& bucket(int i) const { return table[i]; } +}; + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/Queue.h b/src/prop/bvminisat/mtl/Queue.h new file mode 100644 index 000000000..83321ba95 --- /dev/null +++ b/src/prop/bvminisat/mtl/Queue.h @@ -0,0 +1,69 @@ +/*****************************************************************************************[Queue.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Queue_h +#define BVMinisat_Queue_h + +#include "prop/bvminisat/mtl/Vec.h" + +namespace BVMinisat { + +//================================================================================================= + +template<class T> +class Queue { + vec<T> buf; + int first; + int end; + +public: + typedef T Key; + + Queue() : buf(1), first(0), end(0) {} + + void clear (bool dealloc = false) { buf.clear(dealloc); buf.growTo(1); first = end = 0; } + int size () const { return (end >= first) ? end - first : end - first + buf.size(); } + + const T& operator [] (int index) const { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; } + T& operator [] (int index) { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; } + + T peek () const { assert(first != end); return buf[first]; } + void pop () { assert(first != end); first++; if (first == buf.size()) first = 0; } + void insert(T elem) { // INVARIANT: buf[end] is always unused + buf[end++] = elem; + if (end == buf.size()) end = 0; + if (first == end){ // Resize: + vec<T> tmp((buf.size()*3 + 1) >> 1); + //**/printf("queue alloc: %d elems (%.1f MB)\n", tmp.size(), tmp.size() * sizeof(T) / 1000000.0); + int i = 0; + for (int j = first; j < buf.size(); j++) tmp[i++] = buf[j]; + for (int j = 0 ; j < end ; j++) tmp[i++] = buf[j]; + first = 0; + end = buf.size(); + tmp.moveTo(buf); + } + } +}; + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/Sort.h b/src/prop/bvminisat/mtl/Sort.h new file mode 100644 index 000000000..9bab9a0df --- /dev/null +++ b/src/prop/bvminisat/mtl/Sort.h @@ -0,0 +1,98 @@ +/******************************************************************************************[Sort.h] +Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Sort_h +#define BVMinisat_Sort_h + +#include "mtl/Vec.h" + +//================================================================================================= +// Some sorting algorithms for vec's + + +namespace BVMinisat { + +template<class T> +struct LessThan_default { + bool operator () (T x, T y) { return x < y; } +}; + + +template <class T, class LessThan> +void selectionSort(T* array, int size, LessThan lt) +{ + int i, j, best_i; + T tmp; + + for (i = 0; i < size-1; i++){ + best_i = i; + for (j = i+1; j < size; j++){ + if (lt(array[j], array[best_i])) + best_i = j; + } + tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp; + } +} +template <class T> static inline void selectionSort(T* array, int size) { + selectionSort(array, size, LessThan_default<T>()); } + +template <class T, class LessThan> +void sort(T* array, int size, LessThan lt) +{ + if (size <= 15) + selectionSort(array, size, lt); + + else{ + T pivot = array[size / 2]; + T tmp; + int i = -1; + int j = size; + + for(;;){ + do i++; while(lt(array[i], pivot)); + do j--; while(lt(pivot, array[j])); + + if (i >= j) break; + + tmp = array[i]; array[i] = array[j]; array[j] = tmp; + } + + sort(array , i , lt); + sort(&array[i], size-i, lt); + } +} +template <class T> static inline void sort(T* array, int size) { + sort(array, size, LessThan_default<T>()); } + + +//================================================================================================= +// For 'vec's: + + +template <class T, class LessThan> void sort(vec<T>& v, LessThan lt) { + sort((T*)v, v.size(), lt); } +template <class T> void sort(vec<T>& v) { + sort(v, LessThan_default<T>()); } + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/Vec.h b/src/prop/bvminisat/mtl/Vec.h new file mode 100644 index 000000000..8c568dfe9 --- /dev/null +++ b/src/prop/bvminisat/mtl/Vec.h @@ -0,0 +1,130 @@ +/*******************************************************************************************[Vec.h] +Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Vec_h +#define BVMinisat_Vec_h + +#include <assert.h> +#include <new> + +#include "prop/bvminisat/mtl/IntTypes.h" +#include "prop/bvminisat/mtl/XAlloc.h" + +namespace BVMinisat { + +//================================================================================================= +// Automatically resizable arrays +// +// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc) + +template<class T> +class vec { + T* data; + int sz; + int cap; + + // Don't allow copying (error prone): + vec<T>& operator = (vec<T>& other) { assert(0); return *this; } + vec (vec<T>& other) { assert(0); } + + // Helpers for calculating next capacity: + static inline int imax (int x, int y) { int mask = (y-x) >> (sizeof(int)*8-1); return (x&mask) + (y&(~mask)); } + //static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; } + static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; } + +public: + // Constructors: + vec() : data(NULL) , sz(0) , cap(0) { } + explicit vec(int size) : data(NULL) , sz(0) , cap(0) { growTo(size); } + vec(int size, const T& pad) : data(NULL) , sz(0) , cap(0) { growTo(size, pad); } + ~vec() { clear(true); } + + // Pointer to first element: + operator T* (void) { return data; } + + // Size operations: + int size (void) const { return sz; } + void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); } + void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; } + int capacity (void) const { return cap; } + void capacity (int min_cap); + void growTo (int size); + void growTo (int size, const T& pad); + void clear (bool dealloc = false); + + // Stack interface: + void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; } + void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; } + void push_ (const T& elem) { assert(sz < cap); data[sz++] = elem; } + void pop (void) { assert(sz > 0); sz--, data[sz].~T(); } + // NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but + // in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not + // happen given the way capacities are calculated (below). Essentially, all capacities are + // even, but INT_MAX is odd. + + const T& last (void) const { return data[sz-1]; } + T& last (void) { return data[sz-1]; } + + // Vector interface: + const T& operator [] (int index) const { return data[index]; } + T& operator [] (int index) { return data[index]; } + + // Duplicatation (preferred instead): + void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; } + void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; } +}; + + +template<class T> +void vec<T>::capacity(int min_cap) { + if (cap >= min_cap) return; + int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1); // NOTE: grow by approximately 3/2 + if (add > INT_MAX - cap || (((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM)) + throw OutOfMemoryException(); + } + + +template<class T> +void vec<T>::growTo(int size, const T& pad) { + if (sz >= size) return; + capacity(size); + for (int i = sz; i < size; i++) data[i] = pad; + sz = size; } + + +template<class T> +void vec<T>::growTo(int size) { + if (sz >= size) return; + capacity(size); + for (int i = sz; i < size; i++) new (&data[i]) T(); + sz = size; } + + +template<class T> +void vec<T>::clear(bool dealloc) { + if (data != NULL){ + for (int i = 0; i < sz; i++) data[i].~T(); + sz = 0; + if (dealloc) free(data), data = NULL, cap = 0; } } + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/XAlloc.h b/src/prop/bvminisat/mtl/XAlloc.h new file mode 100644 index 000000000..7b89d1803 --- /dev/null +++ b/src/prop/bvminisat/mtl/XAlloc.h @@ -0,0 +1,45 @@ +/****************************************************************************************[XAlloc.h] +Copyright (c) 2009-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + + +#ifndef BVMinisat_XAlloc_h +#define BVMinisat_XAlloc_h + +#include <errno.h> +#include <stdlib.h> + +namespace BVMinisat { + +//================================================================================================= +// Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing: + +class OutOfMemoryException{}; +static inline void* xrealloc(void *ptr, size_t size) +{ + void* mem = realloc(ptr, size); + if (mem == NULL && errno == ENOMEM){ + throw OutOfMemoryException(); + }else + return mem; +} + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/mtl/config.mk b/src/prop/bvminisat/mtl/config.mk new file mode 100644 index 000000000..b5c36fc6b --- /dev/null +++ b/src/prop/bvminisat/mtl/config.mk @@ -0,0 +1,6 @@ +## +## This file is for system specific configurations. For instance, on +## some systems the path to zlib needs to be added. Example: +## +## CFLAGS += -I/usr/local/include +## LFLAGS += -L/usr/local/lib diff --git a/src/prop/bvminisat/mtl/template.mk b/src/prop/bvminisat/mtl/template.mk new file mode 100644 index 000000000..3f443fc38 --- /dev/null +++ b/src/prop/bvminisat/mtl/template.mk @@ -0,0 +1,107 @@ +## +## Template makefile for Standard, Profile, Debug, Release, and Release-static versions +## +## eg: "make rs" for a statically linked release version. +## "make d" for a debug version (no optimizations). +## "make" for the standard version (optimized, but with debug information and assertions active) + +PWD = $(shell pwd) +EXEC ?= $(notdir $(PWD)) + +CSRCS = $(wildcard $(PWD)/*.cc) +DSRCS = $(foreach dir, $(DEPDIR), $(filter-out $(MROOT)/$(dir)/Main.cc, $(wildcard $(MROOT)/$(dir)/*.cc))) +CHDRS = $(wildcard $(PWD)/*.h) +COBJS = $(CSRCS:.cc=.o) $(DSRCS:.cc=.o) + +PCOBJS = $(addsuffix p, $(COBJS)) +DCOBJS = $(addsuffix d, $(COBJS)) +RCOBJS = $(addsuffix r, $(COBJS)) + + +CXX ?= g++ +CFLAGS ?= -Wall -Wno-parentheses +LFLAGS ?= -Wall + +COPTIMIZE ?= -O3 + +CFLAGS += -I$(MROOT) -D __STDC_LIMIT_MACROS -D __STDC_FORMAT_MACROS +LFLAGS += -lz + +.PHONY : s p d r rs clean + +s: $(EXEC) +p: $(EXEC)_profile +d: $(EXEC)_debug +r: $(EXEC)_release +rs: $(EXEC)_static + +libs: lib$(LIB)_standard.a +libp: lib$(LIB)_profile.a +libd: lib$(LIB)_debug.a +libr: lib$(LIB)_release.a + +## Compile options +%.o: CFLAGS +=$(COPTIMIZE) -g -D DEBUG +%.op: CFLAGS +=$(COPTIMIZE) -pg -g -D NDEBUG +%.od: CFLAGS +=-O0 -g -D DEBUG +%.or: CFLAGS +=$(COPTIMIZE) -g -D NDEBUG + +## Link options +$(EXEC): LFLAGS += -g +$(EXEC)_profile: LFLAGS += -g -pg +$(EXEC)_debug: LFLAGS += -g +#$(EXEC)_release: LFLAGS += ... +$(EXEC)_static: LFLAGS += --static + +## Dependencies +$(EXEC): $(COBJS) +$(EXEC)_profile: $(PCOBJS) +$(EXEC)_debug: $(DCOBJS) +$(EXEC)_release: $(RCOBJS) +$(EXEC)_static: $(RCOBJS) + +lib$(LIB)_standard.a: $(filter-out */Main.o, $(COBJS)) +lib$(LIB)_profile.a: $(filter-out */Main.op, $(PCOBJS)) +lib$(LIB)_debug.a: $(filter-out */Main.od, $(DCOBJS)) +lib$(LIB)_release.a: $(filter-out */Main.or, $(RCOBJS)) + + +## Build rule +%.o %.op %.od %.or: %.cc + @echo Compiling: $(subst $(MROOT)/,,$@) + @$(CXX) $(CFLAGS) -c -o $@ $< + +## Linking rules (standard/profile/debug/release) +$(EXEC) $(EXEC)_profile $(EXEC)_debug $(EXEC)_release $(EXEC)_static: + @echo Linking: "$@ ( $(foreach f,$^,$(subst $(MROOT)/,,$f)) )" + @$(CXX) $^ $(LFLAGS) -o $@ + +## Library rules (standard/profile/debug/release) +lib$(LIB)_standard.a lib$(LIB)_profile.a lib$(LIB)_release.a lib$(LIB)_debug.a: + @echo Making library: "$@ ( $(foreach f,$^,$(subst $(MROOT)/,,$f)) )" + @$(AR) -rcsv $@ $^ + +## Library Soft Link rule: +libs libp libd libr: + @echo "Making Soft Link: $^ -> lib$(LIB).a" + @ln -sf $^ lib$(LIB).a + +## Clean rule +clean: + @rm -f $(EXEC) $(EXEC)_profile $(EXEC)_debug $(EXEC)_release $(EXEC)_static \ + $(COBJS) $(PCOBJS) $(DCOBJS) $(RCOBJS) *.core depend.mk + +## Make dependencies +depend.mk: $(CSRCS) $(CHDRS) + @echo Making dependencies + @$(CXX) $(CFLAGS) -I$(MROOT) \ + $(CSRCS) -MM | sed 's|\(.*\):|$(PWD)/\1 $(PWD)/\1r $(PWD)/\1d $(PWD)/\1p:|' > depend.mk + @for dir in $(DEPDIR); do \ + if [ -r $(MROOT)/$${dir}/depend.mk ]; then \ + echo Depends on: $${dir}; \ + cat $(MROOT)/$${dir}/depend.mk >> depend.mk; \ + fi; \ + done + +-include $(MROOT)/mtl/config.mk +-include depend.mk diff --git a/src/prop/bvminisat/simp/Main.cc b/src/prop/bvminisat/simp/Main.cc new file mode 100644 index 000000000..bfb655782 --- /dev/null +++ b/src/prop/bvminisat/simp/Main.cc @@ -0,0 +1,211 @@ +/*****************************************************************************************[Main.cc] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include <errno.h> + +#include <signal.h> +#include <zlib.h> +#include <sys/resource.h> + +#include "utils/System.h" +#include "utils/ParseUtils.h" +#include "utils/Options.h" +#include "core/Dimacs.h" +#include "simp/SimpSolver.h" + +using namespace BVMinisat; + +//================================================================================================= + + +void printStats(Solver& solver) +{ + double cpu_time = cpuTime(); + double mem_used = memUsedPeak(); + printf("restarts : %"PRIu64"\n", solver.starts); + printf("conflicts : %-12"PRIu64" (%.0f /sec)\n", solver.conflicts , solver.conflicts /cpu_time); + printf("decisions : %-12"PRIu64" (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions /cpu_time); + printf("propagations : %-12"PRIu64" (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time); + printf("conflict literals : %-12"PRIu64" (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals); + if (mem_used != 0) printf("Memory used : %.2f MB\n", mem_used); + printf("CPU time : %g s\n", cpu_time); +} + + +static Solver* solver; +// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case +// for this feature of the Solver as it may take longer than an immediate call to '_exit()'. +static void SIGINT_interrupt(int signum) { solver->interrupt(); } + +// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls +// destructors and may cause deadlocks if a malloc/free function happens to be running (these +// functions are guarded by locks for multithreaded use). +static void SIGINT_exit(int signum) { + printf("\n"); printf("*** INTERRUPTED ***\n"); + if (solver->verbosity > 0){ + printStats(*solver); + printf("\n"); printf("*** INTERRUPTED ***\n"); } + _exit(1); } + + +//================================================================================================= +// Main: + +int main(int argc, char** argv) +{ + try { + setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n where input may be either in plain or gzipped DIMACS.\n"); + // printf("This is MiniSat 2.0 beta\n"); + +#if defined(__linux__) + fpu_control_t oldcw, newcw; + _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw); + printf("WARNING: for repeatability, setting FPU to use double precision\n"); +#endif + // Extra options: + // + IntOption verb ("MAIN", "verb", "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2)); + BoolOption pre ("MAIN", "pre", "Completely turn on/off any preprocessing.", true); + StringOption dimacs ("MAIN", "dimacs", "If given, stop after preprocessing and write the result to this file."); + IntOption cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX)); + IntOption mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX)); + + parseOptions(argc, argv, true); + + SimpSolver S; + double initial_time = cpuTime(); + + if (!pre) S.eliminate(true); + + S.verbosity = verb; + + solver = &S; + // Use signal handlers that forcibly quit until the solver will be able to respond to + // interrupts: + signal(SIGINT, SIGINT_exit); + signal(SIGXCPU,SIGINT_exit); + + // Set limit on CPU-time: + if (cpu_lim != INT32_MAX){ + rlimit rl; + getrlimit(RLIMIT_CPU, &rl); + if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){ + rl.rlim_cur = cpu_lim; + if (setrlimit(RLIMIT_CPU, &rl) == -1) + printf("WARNING! Could not set resource limit: CPU-time.\n"); + } } + + // Set limit on virtual memory: + if (mem_lim != INT32_MAX){ + rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024; + rlimit rl; + getrlimit(RLIMIT_AS, &rl); + if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){ + rl.rlim_cur = new_mem_lim; + if (setrlimit(RLIMIT_AS, &rl) == -1) + printf("WARNING! Could not set resource limit: Virtual memory.\n"); + } } + + if (argc == 1) + printf("Reading from standard input... Use '--help' for help.\n"); + + gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb"); + if (in == NULL) + printf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1); + + if (S.verbosity > 0){ + printf("============================[ Problem Statistics ]=============================\n"); + printf("| |\n"); } + + parse_DIMACS(in, S); + gzclose(in); + FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL; + + if (S.verbosity > 0){ + printf("| Number of variables: %12d |\n", S.nVars()); + printf("| Number of clauses: %12d |\n", S.nClauses()); } + + double parsed_time = cpuTime(); + if (S.verbosity > 0) + printf("| Parse time: %12.2f s |\n", parsed_time - initial_time); + + // Change to signal-handlers that will only notify the solver and allow it to terminate + // voluntarily: + signal(SIGINT, SIGINT_interrupt); + signal(SIGXCPU,SIGINT_interrupt); + + S.eliminate(true); + double simplified_time = cpuTime(); + if (S.verbosity > 0){ + printf("| Simplification time: %12.2f s |\n", simplified_time - parsed_time); + printf("| |\n"); } + + if (!S.okay()){ + if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res); + if (S.verbosity > 0){ + printf("===============================================================================\n"); + printf("Solved by simplification\n"); + printStats(S); + printf("\n"); } + printf("UNSATISFIABLE\n"); + exit(20); + } + + if (dimacs){ + if (S.verbosity > 0) + printf("==============================[ Writing DIMACS ]===============================\n"); + S.toDimacs((const char*)dimacs); + if (S.verbosity > 0) + printStats(S); + exit(0); + } + + vec<Lit> dummy; + lbool ret = S.solveLimited(dummy); + + if (S.verbosity > 0){ + printStats(S); + printf("\n"); } + printf(ret == l_True ? "SATISFIABLE\n" : ret == l_False ? "UNSATISFIABLE\n" : "INDETERMINATE\n"); + if (res != NULL){ + if (ret == l_True){ + fprintf(res, "SAT\n"); + for (int i = 0; i < S.nVars(); i++) + if (S.model[i] != l_Undef) + fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1); + fprintf(res, " 0\n"); + }else if (ret == l_False) + fprintf(res, "UNSAT\n"); + else + fprintf(res, "INDET\n"); + fclose(res); + } + +#ifdef NDEBUG + exit(ret == l_True ? 10 : ret == l_False ? 20 : 0); // (faster than "return", which will invoke the destructor for 'Solver') +#else + return (ret == l_True ? 10 : ret == l_False ? 20 : 0); +#endif + } catch (OutOfMemoryException&){ + printf("===============================================================================\n"); + printf("INDETERMINATE\n"); + exit(0); + } +} diff --git a/src/prop/bvminisat/simp/Makefile b/src/prop/bvminisat/simp/Makefile new file mode 100644 index 000000000..27b45f493 --- /dev/null +++ b/src/prop/bvminisat/simp/Makefile @@ -0,0 +1,4 @@ +EXEC = minisat +DEPDIR = mtl utils core + +include $(MROOT)/mtl/template.mk diff --git a/src/prop/bvminisat/simp/SimpSolver.cc b/src/prop/bvminisat/simp/SimpSolver.cc new file mode 100644 index 000000000..4af756456 --- /dev/null +++ b/src/prop/bvminisat/simp/SimpSolver.cc @@ -0,0 +1,733 @@ +/***********************************************************************************[SimpSolver.cc] +Copyright (c) 2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include "mtl/Sort.h" +#include "simp/SimpSolver.h" +#include "utils/System.h" + +using namespace BVMinisat; + +//================================================================================================= +// Options: + + +static const char* _cat = "SIMP"; + +static BoolOption opt_use_asymm (_cat, "asymm", "Shrink clauses by asymmetric branching.", false); +static BoolOption opt_use_rcheck (_cat, "rcheck", "Check if a clause is already implied. (costly)", false); +static BoolOption opt_use_elim (_cat, "elim", "Perform variable elimination.", true); +static IntOption opt_grow (_cat, "grow", "Allow a variable elimination step to grow by a number of clauses.", 0); +static IntOption opt_clause_lim (_cat, "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX)); +static IntOption opt_subsumption_lim (_cat, "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX)); +static DoubleOption opt_simp_garbage_frac(_cat, "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false)); + + +//================================================================================================= +// Constructor/Destructor: + + +SimpSolver::SimpSolver() : + grow (opt_grow) + , clause_lim (opt_clause_lim) + , subsumption_lim (opt_subsumption_lim) + , simp_garbage_frac (opt_simp_garbage_frac) + , use_asymm (opt_use_asymm) + , use_rcheck (opt_use_rcheck) + , use_elim (opt_use_elim) + , merges (0) + , asymm_lits (0) + , eliminated_vars (0) + , total_eliminate_time("theory::bv::bvminisat::TotalVariableEliminationTime") + , elimorder (1) + , use_simplification (true) + , occurs (ClauseDeleted(ca)) + , elim_heap (ElimLt(n_occ)) + , bwdsub_assigns (0) + , n_touched (0) +{ + CVC4::StatisticsRegistry::registerStat(&total_eliminate_time); + vec<Lit> dummy(1,lit_Undef); + ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below. + bwdsub_tmpunit = ca.alloc(dummy); + remove_satisfied = false; +} + + +SimpSolver::~SimpSolver() +{ + CVC4::StatisticsRegistry::unregisterStat(&total_eliminate_time); +} + + +Var SimpSolver::newVar(bool sign, bool dvar, bool freeze) { + Var v = Solver::newVar(sign, dvar); + + frozen .push((char)false); + eliminated.push((char)false); + + if (use_simplification){ + n_occ .push(0); + n_occ .push(0); + occurs .init(v); + touched .push(0); + elim_heap .insert(v); + if (freeze) { + setFrozen(v, true); + } + } + return v; +} + + + +lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp) +{ + + + vec<Var> extra_frozen; + lbool result = l_True; + + do_simp &= use_simplification; + + if (do_simp){ + // Assumptions must be temporarily frozen to run variable elimination: + for (int i = 0; i < assumptions.size(); i++){ + Var v = var(assumptions[i]); + + // If an assumption has been eliminated, remember it. + assert(!isEliminated(v)); + + if (!frozen[v]){ + // Freeze and store. + setFrozen(v, true); + extra_frozen.push(v); + } } + + result = lbool(eliminate(turn_off_simp)); + } + + if (result == l_True) + result = Solver::solve_(); + else if (verbosity >= 1) + printf("===============================================================================\n"); + + if (result == l_True) + extendModel(); + + if (do_simp) + // Unfreeze the assumptions that were frozen: + for (int i = 0; i < extra_frozen.size(); i++) + setFrozen(extra_frozen[i], false); + + return result; +} + + + +bool SimpSolver::addClause_(vec<Lit>& ps) +{ +#ifndef NDEBUG + for (int i = 0; i < ps.size(); i++) + assert(!isEliminated(var(ps[i]))); +#endif + + int nclauses = clauses.size(); + + if (use_rcheck && implied(ps)) + return true; + + if (!Solver::addClause_(ps)) + return false; + + if (use_simplification && clauses.size() == nclauses + 1){ + CRef cr = clauses.last(); + const Clause& c = ca[cr]; + + // NOTE: the clause is added to the queue immediately and then + // again during 'gatherTouchedClauses()'. If nothing happens + // in between, it will only be checked once. Otherwise, it may + // be checked twice unnecessarily. This is an unfortunate + // consequence of how backward subsumption is used to mimic + // forward subsumption. + subsumption_queue.insert(cr); + for (int i = 0; i < c.size(); i++){ + occurs[var(c[i])].push(cr); + n_occ[toInt(c[i])]++; + touched[var(c[i])] = 1; + n_touched++; + if (elim_heap.inHeap(var(c[i]))) + elim_heap.increase(var(c[i])); + } + } + + return true; +} + + +void SimpSolver::removeClause(CRef cr) +{ + const Clause& c = ca[cr]; + + if (use_simplification) + for (int i = 0; i < c.size(); i++){ + n_occ[toInt(c[i])]--; + updateElimHeap(var(c[i])); + occurs.smudge(var(c[i])); + } + + Solver::removeClause(cr); +} + + +bool SimpSolver::strengthenClause(CRef cr, Lit l) +{ + Clause& c = ca[cr]; + assert(decisionLevel() == 0); + assert(use_simplification); + + // FIX: this is too inefficient but would be nice to have (properly implemented) + // if (!find(subsumption_queue, &c)) + subsumption_queue.insert(cr); + + if (c.size() == 2){ + removeClause(cr); + c.strengthen(l); + }else{ + detachClause(cr, true); + c.strengthen(l); + attachClause(cr); + remove(occurs[var(l)], cr); + n_occ[toInt(l)]--; + updateElimHeap(var(l)); + } + + return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true; +} + + +// Returns FALSE if clause is always satisfied ('out_clause' should not be used). +bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause) +{ + merges++; + out_clause.clear(); + + bool ps_smallest = _ps.size() < _qs.size(); + const Clause& ps = ps_smallest ? _qs : _ps; + const Clause& qs = ps_smallest ? _ps : _qs; + + for (int i = 0; i < qs.size(); i++){ + if (var(qs[i]) != v){ + for (int j = 0; j < ps.size(); j++) + if (var(ps[j]) == var(qs[i])) + if (ps[j] == ~qs[i]) + return false; + else + goto next; + out_clause.push(qs[i]); + } + next:; + } + + for (int i = 0; i < ps.size(); i++) + if (var(ps[i]) != v) + out_clause.push(ps[i]); + + return true; +} + + +// Returns FALSE if clause is always satisfied. +bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size) +{ + merges++; + + bool ps_smallest = _ps.size() < _qs.size(); + const Clause& ps = ps_smallest ? _qs : _ps; + const Clause& qs = ps_smallest ? _ps : _qs; + const Lit* __ps = (const Lit*)ps; + const Lit* __qs = (const Lit*)qs; + + size = ps.size()-1; + + for (int i = 0; i < qs.size(); i++){ + if (var(__qs[i]) != v){ + for (int j = 0; j < ps.size(); j++) + if (var(__ps[j]) == var(__qs[i])) + if (__ps[j] == ~__qs[i]) + return false; + else + goto next; + size++; + } + next:; + } + + return true; +} + + +void SimpSolver::gatherTouchedClauses() +{ + if (n_touched == 0) return; + + int i,j; + for (i = j = 0; i < subsumption_queue.size(); i++) + if (ca[subsumption_queue[i]].mark() == 0) + ca[subsumption_queue[i]].mark(2); + + for (i = 0; i < touched.size(); i++) + if (touched[i]){ + const vec<CRef>& cs = occurs.lookup(i); + for (j = 0; j < cs.size(); j++) + if (ca[cs[j]].mark() == 0){ + subsumption_queue.insert(cs[j]); + ca[cs[j]].mark(2); + } + touched[i] = 0; + } + + for (i = 0; i < subsumption_queue.size(); i++) + if (ca[subsumption_queue[i]].mark() == 2) + ca[subsumption_queue[i]].mark(0); + + n_touched = 0; +} + + +bool SimpSolver::implied(const vec<Lit>& c) +{ + assert(decisionLevel() == 0); + + trail_lim.push(trail.size()); + for (int i = 0; i < c.size(); i++) + if (value(c[i]) == l_True){ + cancelUntil(0); + return false; + }else if (value(c[i]) != l_False){ + assert(value(c[i]) == l_Undef); + uncheckedEnqueue(~c[i]); + } + + bool result = propagate() != CRef_Undef; + cancelUntil(0); + return result; +} + + +// Backward subsumption + backward subsumption resolution +bool SimpSolver::backwardSubsumptionCheck(bool verbose) +{ + int cnt = 0; + int subsumed = 0; + int deleted_literals = 0; + assert(decisionLevel() == 0); + + while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){ + + // Empty subsumption queue and return immediately on user-interrupt: + if (asynch_interrupt){ + subsumption_queue.clear(); + bwdsub_assigns = trail.size(); + break; } + + // Check top-level assignments by creating a dummy clause and placing it in the queue: + if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){ + Lit l = trail[bwdsub_assigns++]; + ca[bwdsub_tmpunit][0] = l; + ca[bwdsub_tmpunit].calcAbstraction(); + subsumption_queue.insert(bwdsub_tmpunit); } + + CRef cr = subsumption_queue.peek(); subsumption_queue.pop(); + Clause& c = ca[cr]; + + if (c.mark()) continue; + + if (verbose && verbosity >= 2 && cnt++ % 1000 == 0) + printf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals); + + assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point. + + // Find best variable to scan: + Var best = var(c[0]); + for (int i = 1; i < c.size(); i++) + if (occurs[var(c[i])].size() < occurs[best].size()) + best = var(c[i]); + + // Search all candidates: + vec<CRef>& _cs = occurs.lookup(best); + CRef* cs = (CRef*)_cs; + + for (int j = 0; j < _cs.size(); j++) + if (c.mark()) + break; + else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){ + Lit l = c.subsumes(ca[cs[j]]); + + if (l == lit_Undef) + subsumed++, removeClause(cs[j]); + else if (l != lit_Error){ + deleted_literals++; + + if (!strengthenClause(cs[j], ~l)) + return false; + + // Did current candidate get deleted from cs? Then check candidate at index j again: + if (var(l) == best) + j--; + } + } + } + + return true; +} + + +bool SimpSolver::asymm(Var v, CRef cr) +{ + Clause& c = ca[cr]; + assert(decisionLevel() == 0); + + if (c.mark() || satisfied(c)) return true; + + trail_lim.push(trail.size()); + Lit l = lit_Undef; + for (int i = 0; i < c.size(); i++) + if (var(c[i]) != v && value(c[i]) != l_False) + uncheckedEnqueue(~c[i]); + else + l = c[i]; + + if (propagate() != CRef_Undef){ + cancelUntil(0); + asymm_lits++; + if (!strengthenClause(cr, l)) + return false; + }else + cancelUntil(0); + + return true; +} + + +bool SimpSolver::asymmVar(Var v) +{ + assert(use_simplification); + + const vec<CRef>& cls = occurs.lookup(v); + + if (value(v) != l_Undef || cls.size() == 0) + return true; + + for (int i = 0; i < cls.size(); i++) + if (!asymm(v, cls[i])) + return false; + + return backwardSubsumptionCheck(); +} + + +static void mkElimClause(vec<uint32_t>& elimclauses, Lit x) +{ + elimclauses.push(toInt(x)); + elimclauses.push(1); +} + + +static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c) +{ + int first = elimclauses.size(); + int v_pos = -1; + + // Copy clause to elimclauses-vector. Remember position where the + // variable 'v' occurs: + for (int i = 0; i < c.size(); i++){ + elimclauses.push(toInt(c[i])); + if (var(c[i]) == v) + v_pos = i + first; + } + assert(v_pos != -1); + + // Swap the first literal with the 'v' literal, so that the literal + // containing 'v' will occur first in the clause: + uint32_t tmp = elimclauses[v_pos]; + elimclauses[v_pos] = elimclauses[first]; + elimclauses[first] = tmp; + + // Store the length of the clause last: + elimclauses.push(c.size()); +} + + + +bool SimpSolver::eliminateVar(Var v) +{ + + assert(!frozen[v]); + assert(!isEliminated(v)); + assert(value(v) == l_Undef); + + // Split the occurrences into positive and negative: + // + const vec<CRef>& cls = occurs.lookup(v); + vec<CRef> pos, neg; + for (int i = 0; i < cls.size(); i++) + (find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]); + + // Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no + // clause must exceed the limit on the maximal clause size (if it is set): + // + int cnt = 0; + int clause_size = 0; + + for (int i = 0; i < pos.size(); i++) + for (int j = 0; j < neg.size(); j++) + if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) && + (++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim))) + return true; + + // Delete and store old clauses: + eliminated[v] = true; + setDecisionVar(v, false); + eliminated_vars++; + + if (pos.size() > neg.size()){ + for (int i = 0; i < neg.size(); i++) + mkElimClause(elimclauses, v, ca[neg[i]]); + mkElimClause(elimclauses, mkLit(v)); + }else{ + for (int i = 0; i < pos.size(); i++) + mkElimClause(elimclauses, v, ca[pos[i]]); + mkElimClause(elimclauses, ~mkLit(v)); + } + + for (int i = 0; i < cls.size(); i++) + removeClause(cls[i]); + + // Produce clauses in cross product: + vec<Lit>& resolvent = add_tmp; + for (int i = 0; i < pos.size(); i++) + for (int j = 0; j < neg.size(); j++) + if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent)) + return false; + + // Free occurs list for this variable: + occurs[v].clear(true); + + // Free watchers lists for this variable, if possible: + if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true); + if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true); + + return backwardSubsumptionCheck(); +} + + +bool SimpSolver::substitute(Var v, Lit x) +{ + assert(!frozen[v]); + assert(!isEliminated(v)); + assert(value(v) == l_Undef); + + if (!ok) return false; + + eliminated[v] = true; + setDecisionVar(v, false); + const vec<CRef>& cls = occurs.lookup(v); + + vec<Lit>& subst_clause = add_tmp; + for (int i = 0; i < cls.size(); i++){ + Clause& c = ca[cls[i]]; + + subst_clause.clear(); + for (int j = 0; j < c.size(); j++){ + Lit p = c[j]; + subst_clause.push(var(p) == v ? x ^ sign(p) : p); + } + + removeClause(cls[i]); + + if (!addClause_(subst_clause)) + return ok = false; + } + + return true; +} + + +void SimpSolver::extendModel() +{ + int i, j; + Lit x; + + for (i = elimclauses.size()-1; i > 0; i -= j){ + for (j = elimclauses[i--]; j > 1; j--, i--) + if (modelValue(toLit(elimclauses[i])) != l_False) + goto next; + + x = toLit(elimclauses[i]); + model[var(x)] = lbool(!sign(x)); + next:; + } +} + + +bool SimpSolver::eliminate(bool turn_off_elim) +{ + + CVC4::TimerStat::CodeTimer codeTimer(total_eliminate_time); + + if (!simplify()) + return false; + else if (!use_simplification) + return true; + + // Main simplification loop: + // + while (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0){ + + gatherTouchedClauses(); + // printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns); + if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) && + !backwardSubsumptionCheck(true)){ + ok = false; goto cleanup; } + + // Empty elim_heap and return immediately on user-interrupt: + if (asynch_interrupt){ + assert(bwdsub_assigns == trail.size()); + assert(subsumption_queue.size() == 0); + assert(n_touched == 0); + elim_heap.clear(); + goto cleanup; } + + // printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size()); + for (int cnt = 0; !elim_heap.empty(); cnt++){ + Var elim = elim_heap.removeMin(); + + if (asynch_interrupt) break; + + if (isEliminated(elim) || value(elim) != l_Undef) continue; + + if (verbosity >= 2 && cnt % 100 == 0) + printf("elimination left: %10d\r", elim_heap.size()); + + if (use_asymm){ + // Temporarily freeze variable. Otherwise, it would immediately end up on the queue again: + bool was_frozen = frozen[elim]; + frozen[elim] = true; + if (!asymmVar(elim)){ + ok = false; goto cleanup; } + frozen[elim] = was_frozen; } + + // At this point, the variable may have been set by assymetric branching, so check it + // again. Also, don't eliminate frozen variables: + if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){ + ok = false; goto cleanup; } + + checkGarbage(simp_garbage_frac); + } + + assert(subsumption_queue.size() == 0); + } + cleanup: + + // If no more simplification is needed, free all simplification-related data structures: + if (turn_off_elim){ + touched .clear(true); + occurs .clear(true); + n_occ .clear(true); + elim_heap.clear(true); + subsumption_queue.clear(true); + + use_simplification = false; + remove_satisfied = true; + ca.extra_clause_field = false; + + // Force full cleanup (this is safe and desirable since it only happens once): + rebuildOrderHeap(); + garbageCollect(); + }else{ + // Cheaper cleanup: + cleanUpClauses(); // TODO: can we make 'cleanUpClauses()' not be linear in the problem size somehow? + checkGarbage(); + } + + if (verbosity >= 1 && elimclauses.size() > 0) + printf("| Eliminated clauses: %10.2f Mb |\n", + double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024)); + + return ok; + + + +} + + +void SimpSolver::cleanUpClauses() +{ + occurs.cleanAll(); + int i,j; + for (i = j = 0; i < clauses.size(); i++) + if (ca[clauses[i]].mark() == 0) + clauses[j++] = clauses[i]; + clauses.shrink(i - j); +} + + +//================================================================================================= +// Garbage Collection methods: + + +void SimpSolver::relocAll(ClauseAllocator& to) +{ + if (!use_simplification) return; + + // All occurs lists: + // + for (int i = 0; i < nVars(); i++){ + vec<CRef>& cs = occurs[i]; + for (int j = 0; j < cs.size(); j++) + ca.reloc(cs[j], to); + } + + // Subsumption queue: + // + for (int i = 0; i < subsumption_queue.size(); i++) + ca.reloc(subsumption_queue[i], to); + + // Temporary clause: + // + ca.reloc(bwdsub_tmpunit, to); +} + + +void SimpSolver::garbageCollect() +{ + // Initialize the next region to a size corresponding to the estimated utilization degree. This + // is not precise but should avoid some unnecessary reallocations for the new region: + ClauseAllocator to(ca.size() - ca.wasted()); + + cleanUpClauses(); + to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields. + relocAll(to); + Solver::relocAll(to); + if (verbosity >= 2) + printf("| Garbage collection: %12d bytes => %12d bytes |\n", + ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size); + to.moveTo(ca); +} diff --git a/src/prop/bvminisat/simp/SimpSolver.h b/src/prop/bvminisat/simp/SimpSolver.h new file mode 100644 index 000000000..e21a0a9ec --- /dev/null +++ b/src/prop/bvminisat/simp/SimpSolver.h @@ -0,0 +1,197 @@ +/************************************************************************************[SimpSolver.h] +Copyright (c) 2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_SimpSolver_h +#define BVMinisat_SimpSolver_h + +#include "prop/bvminisat/mtl/Queue.h" +#include "prop/bvminisat/core/Solver.h" +#include "util/stats.h" + +namespace BVMinisat { + +//================================================================================================= + + +class SimpSolver : public Solver { + public: + // Constructor/Destructor: + // + SimpSolver(); + ~SimpSolver(); + + // Problem specification: + // + Var newVar (bool polarity = true, bool dvar = true, bool freeze = false); + bool addClause (const vec<Lit>& ps); + bool addEmptyClause(); // Add the empty clause to the solver. + bool addClause (Lit p); // Add a unit clause to the solver. + bool addClause (Lit p, Lit q); // Add a binary clause to the solver. + bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver. + bool addClause_( vec<Lit>& ps); + bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction). + + // Variable mode: + // + void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated. + bool isEliminated(Var v) const; + + // Solving: + // + bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false); + lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false); + bool solve ( bool do_simp = true, bool turn_off_simp = false); + bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false); + bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false); + bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false); + bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification. + + // Memory managment: + // + virtual void garbageCollect(); + + + // Generate a (possibly simplified) DIMACS file: + // +#if 0 + void toDimacs (const char* file, const vec<Lit>& assumps); + void toDimacs (const char* file); + void toDimacs (const char* file, Lit p); + void toDimacs (const char* file, Lit p, Lit q); + void toDimacs (const char* file, Lit p, Lit q, Lit r); +#endif + + // Mode of operation: + // + int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero). + int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit. + // -1 means no limit. + int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit. + double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac'). + + bool use_asymm; // Shrink clauses by asymmetric branching. + bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :) + bool use_elim; // Perform variable elimination. + + // Statistics: + // + int merges; + int asymm_lits; + int eliminated_vars; + CVC4::TimerStat total_eliminate_time; + protected: + + // Helper structures: + // + struct ElimLt { + const vec<int>& n_occ; + explicit ElimLt(const vec<int>& no) : n_occ(no) {} + + // TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating + // 32-bit implementation instead then, but this will have to do for now. + uint64_t cost (Var x) const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; } + bool operator()(Var x, Var y) const { return cost(x) < cost(y); } + + // TODO: investigate this order alternative more. + // bool operator()(Var x, Var y) const { + // int c_x = cost(x); + // int c_y = cost(y); + // return c_x < c_y || c_x == c_y && x < y; } + }; + + struct ClauseDeleted { + const ClauseAllocator& ca; + explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {} + bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } }; + + // Solver state: + // + int elimorder; + bool use_simplification; + vec<uint32_t> elimclauses; + vec<char> touched; + OccLists<Var, vec<CRef>, ClauseDeleted> + occurs; + vec<int> n_occ; + Heap<ElimLt> elim_heap; + Queue<CRef> subsumption_queue; + vec<char> frozen; + vec<char> eliminated; + int bwdsub_assigns; + int n_touched; + + // Temporaries: + // + CRef bwdsub_tmpunit; + + // Main internal methods: + // + lbool solve_ (bool do_simp = true, bool turn_off_simp = false); + bool asymm (Var v, CRef cr); + bool asymmVar (Var v); + void updateElimHeap (Var v); + void gatherTouchedClauses (); + bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause); + bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size); + bool backwardSubsumptionCheck (bool verbose = false); + bool eliminateVar (Var v); + void extendModel (); + + void removeClause (CRef cr); + bool strengthenClause (CRef cr, Lit l); + void cleanUpClauses (); + bool implied (const vec<Lit>& c); + void relocAll (ClauseAllocator& to); +}; + + +//================================================================================================= +// Implementation of inline methods: + + +inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; } +inline void SimpSolver::updateElimHeap(Var v) { + assert(use_simplification); + // if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef) + if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)) + elim_heap.update(v); } + + +inline bool SimpSolver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); } +inline bool SimpSolver::addEmptyClause() { add_tmp.clear(); return addClause_(add_tmp); } +inline bool SimpSolver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); } +inline bool SimpSolver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); } +inline bool SimpSolver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); } +inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } } + +inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; } +inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; } +inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; } +inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; } +inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ + budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; } + +inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ + assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); } + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/utils/Makefile b/src/prop/bvminisat/utils/Makefile new file mode 100644 index 000000000..204cea541 --- /dev/null +++ b/src/prop/bvminisat/utils/Makefile @@ -0,0 +1,4 @@ +EXEC = system_test +DEPDIR = mtl + +include $(MROOT)/mtl/template.mk diff --git a/src/prop/bvminisat/utils/Options.cc b/src/prop/bvminisat/utils/Options.cc new file mode 100644 index 000000000..a15220c4b --- /dev/null +++ b/src/prop/bvminisat/utils/Options.cc @@ -0,0 +1,91 @@ +/**************************************************************************************[Options.cc] +Copyright (c) 2008-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include "mtl/Sort.h" +#include "utils/Options.h" +#include "utils/ParseUtils.h" + +using namespace BVMinisat; + +void Minisat::parseOptions(int& argc, char** argv, bool strict) +{ + int i, j; + for (i = j = 1; i < argc; i++){ + const char* str = argv[i]; + if (match(str, "--") && match(str, Option::getHelpPrefixString()) && match(str, "help")){ + if (*str == '\0') + printUsageAndExit(argc, argv); + else if (match(str, "-verb")) + printUsageAndExit(argc, argv, true); + } else { + bool parsed_ok = false; + + for (int k = 0; !parsed_ok && k < Option::getOptionList().size(); k++){ + parsed_ok = Option::getOptionList()[k]->parse(argv[i]); + + // fprintf(stderr, "checking %d: %s against flag <%s> (%s)\n", i, argv[i], Option::getOptionList()[k]->name, parsed_ok ? "ok" : "skip"); + } + + if (!parsed_ok) + if (strict && match(argv[i], "-")) + fprintf(stderr, "ERROR! Unknown flag \"%s\". Use '--%shelp' for help.\n", argv[i], Option::getHelpPrefixString()), exit(1); + else + argv[j++] = argv[i]; + } + } + + argc -= (i - j); +} + + +void Minisat::setUsageHelp (const char* str){ Option::getUsageString() = str; } +void Minisat::setHelpPrefixStr (const char* str){ Option::getHelpPrefixString() = str; } +void Minisat::printUsageAndExit (int argc, char** argv, bool verbose) +{ + const char* usage = Option::getUsageString(); + if (usage != NULL) + fprintf(stderr, usage, argv[0]); + + sort(Option::getOptionList(), Option::OptionLt()); + + const char* prev_cat = NULL; + const char* prev_type = NULL; + + for (int i = 0; i < Option::getOptionList().size(); i++){ + const char* cat = Option::getOptionList()[i]->category; + const char* type = Option::getOptionList()[i]->type_name; + + if (cat != prev_cat) + fprintf(stderr, "\n%s OPTIONS:\n\n", cat); + else if (type != prev_type) + fprintf(stderr, "\n"); + + Option::getOptionList()[i]->help(verbose); + + prev_cat = Option::getOptionList()[i]->category; + prev_type = Option::getOptionList()[i]->type_name; + } + + fprintf(stderr, "\nHELP OPTIONS:\n\n"); + fprintf(stderr, " --%shelp Print help message.\n", Option::getHelpPrefixString()); + fprintf(stderr, " --%shelp-verb Print verbose help message.\n", Option::getHelpPrefixString()); + fprintf(stderr, "\n"); + exit(0); +} + diff --git a/src/prop/bvminisat/utils/Options.h b/src/prop/bvminisat/utils/Options.h new file mode 100644 index 000000000..1d41333ef --- /dev/null +++ b/src/prop/bvminisat/utils/Options.h @@ -0,0 +1,386 @@ +/***************************************************************************************[Options.h] +Copyright (c) 2008-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_Options_h +#define BVMinisat_Options_h + +#include <stdlib.h> +#include <stdio.h> +#include <math.h> +#include <string.h> + +#include "prop/bvminisat/mtl/IntTypes.h" +#include "prop/bvminisat/mtl/Vec.h" +#include "prop/bvminisat/utils/ParseUtils.h" + +namespace BVMinisat { + +//================================================================================================== +// Top-level option parse/help functions: + + +extern void parseOptions (int& argc, char** argv, bool strict = false); +extern void printUsageAndExit(int argc, char** argv, bool verbose = false); +extern void setUsageHelp (const char* str); +extern void setHelpPrefixStr (const char* str); + + +//================================================================================================== +// Options is an abstract class that gives the interface for all types options: + + +class Option +{ + protected: + const char* name; + const char* description; + const char* category; + const char* type_name; + + static vec<Option*>& getOptionList () { static vec<Option*> options; return options; } + static const char*& getUsageString() { static const char* usage_str; return usage_str; } + static const char*& getHelpPrefixString() { static const char* help_prefix_str = ""; return help_prefix_str; } + + struct OptionLt { + bool operator()(const Option* x, const Option* y) { + int test1 = strcmp(x->category, y->category); + return test1 < 0 || (test1 == 0 && strcmp(x->type_name, y->type_name) < 0); + } + }; + + Option(const char* name_, + const char* desc_, + const char* cate_, + const char* type_) : + name (name_) + , description(desc_) + , category (cate_) + , type_name (type_) + { + getOptionList().push(this); + } + + public: + virtual ~Option() {} + + virtual bool parse (const char* str) = 0; + virtual void help (bool verbose = false) = 0; + + friend void parseOptions (int& argc, char** argv, bool strict); + friend void printUsageAndExit (int argc, char** argv, bool verbose); + friend void setUsageHelp (const char* str); + friend void setHelpPrefixStr (const char* str); +}; + + +//================================================================================================== +// Range classes with specialization for floating types: + + +struct IntRange { + int begin; + int end; + IntRange(int b, int e) : begin(b), end(e) {} +}; + +struct Int64Range { + int64_t begin; + int64_t end; + Int64Range(int64_t b, int64_t e) : begin(b), end(e) {} +}; + +struct DoubleRange { + double begin; + double end; + bool begin_inclusive; + bool end_inclusive; + DoubleRange(double b, bool binc, double e, bool einc) : begin(b), end(e), begin_inclusive(binc), end_inclusive(einc) {} +}; + + +//================================================================================================== +// Double options: + + +class DoubleOption : public Option +{ + protected: + DoubleRange range; + double value; + + public: + DoubleOption(const char* c, const char* n, const char* d, double def = double(), DoubleRange r = DoubleRange(-HUGE_VAL, false, HUGE_VAL, false)) + : Option(n, d, c, "<double>"), range(r), value(def) { + // FIXME: set LC_NUMERIC to "C" to make sure that strtof/strtod parses decimal point correctly. + } + + operator double (void) const { return value; } + operator double& (void) { return value; } + DoubleOption& operator=(double x) { value = x; return *this; } + + virtual bool parse(const char* str){ + const char* span = str; + + if (!match(span, "-") || !match(span, name) || !match(span, "=")) + return false; + + char* end; + double tmp = strtod(span, &end); + + if (end == NULL) + return false; + else if (tmp >= range.end && (!range.end_inclusive || tmp != range.end)){ + fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); + exit(1); + }else if (tmp <= range.begin && (!range.begin_inclusive || tmp != range.begin)){ + fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); + exit(1); } + + value = tmp; + // fprintf(stderr, "READ VALUE: %g\n", value); + + return true; + } + + virtual void help (bool verbose = false){ + fprintf(stderr, " -%-12s = %-8s %c%4.2g .. %4.2g%c (default: %g)\n", + name, type_name, + range.begin_inclusive ? '[' : '(', + range.begin, + range.end, + range.end_inclusive ? ']' : ')', + value); + if (verbose){ + fprintf(stderr, "\n %s\n", description); + fprintf(stderr, "\n"); + } + } +}; + + +//================================================================================================== +// Int options: + + +class IntOption : public Option +{ + protected: + IntRange range; + int32_t value; + + public: + IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX)) + : Option(n, d, c, "<int32>"), range(r), value(def) {} + + operator int32_t (void) const { return value; } + operator int32_t& (void) { return value; } + IntOption& operator= (int32_t x) { value = x; return *this; } + + virtual bool parse(const char* str){ + const char* span = str; + + if (!match(span, "-") || !match(span, name) || !match(span, "=")) + return false; + + char* end; + int32_t tmp = strtol(span, &end, 10); + + if (end == NULL) + return false; + else if (tmp > range.end){ + fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); + exit(1); + }else if (tmp < range.begin){ + fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); + exit(1); } + + value = tmp; + + return true; + } + + virtual void help (bool verbose = false){ + fprintf(stderr, " -%-12s = %-8s [", name, type_name); + if (range.begin == INT32_MIN) + fprintf(stderr, "imin"); + else + fprintf(stderr, "%4d", range.begin); + + fprintf(stderr, " .. "); + if (range.end == INT32_MAX) + fprintf(stderr, "imax"); + else + fprintf(stderr, "%4d", range.end); + + fprintf(stderr, "] (default: %d)\n", value); + if (verbose){ + fprintf(stderr, "\n %s\n", description); + fprintf(stderr, "\n"); + } + } +}; + + +// Leave this out for visual C++ until Microsoft implements C99 and gets support for strtoll. +#ifndef _MSC_VER + +class Int64Option : public Option +{ + protected: + Int64Range range; + int64_t value; + + public: + Int64Option(const char* c, const char* n, const char* d, int64_t def = int64_t(), Int64Range r = Int64Range(INT64_MIN, INT64_MAX)) + : Option(n, d, c, "<int64>"), range(r), value(def) {} + + operator int64_t (void) const { return value; } + operator int64_t& (void) { return value; } + Int64Option& operator= (int64_t x) { value = x; return *this; } + + virtual bool parse(const char* str){ + const char* span = str; + + if (!match(span, "-") || !match(span, name) || !match(span, "=")) + return false; + + char* end; + int64_t tmp = strtoll(span, &end, 10); + + if (end == NULL) + return false; + else if (tmp > range.end){ + fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name); + exit(1); + }else if (tmp < range.begin){ + fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name); + exit(1); } + + value = tmp; + + return true; + } + + virtual void help (bool verbose = false){ + fprintf(stderr, " -%-12s = %-8s [", name, type_name); + if (range.begin == INT64_MIN) + fprintf(stderr, "imin"); + else + fprintf(stderr, "%4"PRIi64, range.begin); + + fprintf(stderr, " .. "); + if (range.end == INT64_MAX) + fprintf(stderr, "imax"); + else + fprintf(stderr, "%4"PRIi64, range.end); + + fprintf(stderr, "] (default: %"PRIi64")\n", value); + if (verbose){ + fprintf(stderr, "\n %s\n", description); + fprintf(stderr, "\n"); + } + } +}; +#endif + +//================================================================================================== +// String option: + + +class StringOption : public Option +{ + const char* value; + public: + StringOption(const char* c, const char* n, const char* d, const char* def = NULL) + : Option(n, d, c, "<string>"), value(def) {} + + operator const char* (void) const { return value; } + operator const char*& (void) { return value; } + StringOption& operator= (const char* x) { value = x; return *this; } + + virtual bool parse(const char* str){ + const char* span = str; + + if (!match(span, "-") || !match(span, name) || !match(span, "=")) + return false; + + value = span; + return true; + } + + virtual void help (bool verbose = false){ + fprintf(stderr, " -%-10s = %8s\n", name, type_name); + if (verbose){ + fprintf(stderr, "\n %s\n", description); + fprintf(stderr, "\n"); + } + } +}; + + +//================================================================================================== +// Bool option: + + +class BoolOption : public Option +{ + bool value; + + public: + BoolOption(const char* c, const char* n, const char* d, bool v) + : Option(n, d, c, "<bool>"), value(v) {} + + operator bool (void) const { return value; } + operator bool& (void) { return value; } + BoolOption& operator=(bool b) { value = b; return *this; } + + virtual bool parse(const char* str){ + const char* span = str; + + if (match(span, "-")){ + bool b = !match(span, "no-"); + + if (strcmp(span, name) == 0){ + value = b; + return true; } + } + + return false; + } + + virtual void help (bool verbose = false){ + + fprintf(stderr, " -%s, -no-%s", name, name); + + for (uint32_t i = 0; i < 32 - strlen(name)*2; i++) + fprintf(stderr, " "); + + fprintf(stderr, " "); + fprintf(stderr, "(default: %s)\n", value ? "on" : "off"); + if (verbose){ + fprintf(stderr, "\n %s\n", description); + fprintf(stderr, "\n"); + } + } +}; + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/utils/ParseUtils.h b/src/prop/bvminisat/utils/ParseUtils.h new file mode 100644 index 000000000..920298abb --- /dev/null +++ b/src/prop/bvminisat/utils/ParseUtils.h @@ -0,0 +1,122 @@ +/************************************************************************************[ParseUtils.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_ParseUtils_h +#define BVMinisat_ParseUtils_h + +#include <stdlib.h> +#include <stdio.h> + +#include <zlib.h> + +namespace BVMinisat { + +//------------------------------------------------------------------------------------------------- +// A simple buffered character stream class: + +static const int buffer_size = 1048576; + + +class StreamBuffer { + gzFile in; + unsigned char buf[buffer_size]; + int pos; + int size; + + void assureLookahead() { + if (pos >= size) { + pos = 0; + size = gzread(in, buf, sizeof(buf)); } } + +public: + explicit StreamBuffer(gzFile i) : in(i), pos(0), size(0) { assureLookahead(); } + + int operator * () const { return (pos >= size) ? EOF : buf[pos]; } + void operator ++ () { pos++; assureLookahead(); } + int position () const { return pos; } +}; + + +//------------------------------------------------------------------------------------------------- +// End-of-file detection functions for StreamBuffer and char*: + + +static inline bool isEof(StreamBuffer& in) { return *in == EOF; } +static inline bool isEof(const char* in) { return *in == '\0'; } + +//------------------------------------------------------------------------------------------------- +// Generic parse functions parametrized over the input-stream type. + + +template<class B> +static void skipWhitespace(B& in) { + while ((*in >= 9 && *in <= 13) || *in == 32) + ++in; } + + +template<class B> +static void skipLine(B& in) { + for (;;){ + if (isEof(in)) return; + if (*in == '\n') { ++in; return; } + ++in; } } + + +template<class B> +static int parseInt(B& in) { + int val = 0; + bool neg = false; + skipWhitespace(in); + if (*in == '-') neg = true, ++in; + else if (*in == '+') ++in; + if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3); + while (*in >= '0' && *in <= '9') + val = val*10 + (*in - '0'), + ++in; + return neg ? -val : val; } + + +// String matching: in case of a match the input iterator will be advanced the corresponding +// number of characters. +template<class B> +static bool match(B& in, const char* str) { + int i; + for (i = 0; str[i] != '\0'; i++) + if (in[i] != str[i]) + return false; + + in += i; + + return true; +} + +// String matching: consumes characters eagerly, but does not require random access iterator. +template<class B> +static bool eagerMatch(B& in, const char* str) { + for (; *str != '\0'; ++str, ++in) + if (*str != *in) + return false; + return true; } + + +//================================================================================================= +} + +#endif diff --git a/src/prop/bvminisat/utils/System.cc b/src/prop/bvminisat/utils/System.cc new file mode 100644 index 000000000..9c2fcb083 --- /dev/null +++ b/src/prop/bvminisat/utils/System.cc @@ -0,0 +1,95 @@ +/***************************************************************************************[System.cc] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#include "utils/System.h" + +#if defined(__linux__) + +#include <stdio.h> +#include <stdlib.h> + +using namespace BVMinisat; + +// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and +// one for reading the current virtual memory size. + +static inline int memReadStat(int field) +{ + char name[256]; + pid_t pid = getpid(); + int value; + + sprintf(name, "/proc/%d/statm", pid); + FILE* in = fopen(name, "rb"); + if (in == NULL) return 0; + + for (; field >= 0; field--) + if (fscanf(in, "%d", &value) != 1) + printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1); + fclose(in); + return value; +} + + +static inline int memReadPeak(void) +{ + char name[256]; + pid_t pid = getpid(); + + sprintf(name, "/proc/%d/status", pid); + FILE* in = fopen(name, "rb"); + if (in == NULL) return 0; + + // Find the correct line, beginning with "VmPeak:": + int peak_kb = 0; + while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1) + while (!feof(in) && fgetc(in) != '\n') + ; + fclose(in); + + return peak_kb; +} + +double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); } +double Minisat::memUsedPeak() { + double peak = memReadPeak() / 1024; + return peak == 0 ? memUsed() : peak; } + +#elif defined(__FreeBSD__) + +double Minisat::memUsed(void) { + struct rusage ru; + getrusage(RUSAGE_SELF, &ru); + return (double)ru.ru_maxrss / 1024; } +double MiniSat::memUsedPeak(void) { return memUsed(); } + + +#elif defined(__APPLE__) +#include <malloc/malloc.h> + +double Minisat::memUsed(void) { + malloc_statistics_t t; + malloc_zone_statistics(NULL, &t); + return (double)t.max_size_in_use / (1024*1024); } + +#else +double Minisat::memUsed() { + return 0; } +#endif diff --git a/src/prop/bvminisat/utils/System.h b/src/prop/bvminisat/utils/System.h new file mode 100644 index 000000000..f9fe708bb --- /dev/null +++ b/src/prop/bvminisat/utils/System.h @@ -0,0 +1,60 @@ +/****************************************************************************************[System.h] +Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson +Copyright (c) 2007-2010, Niklas Sorensson + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or +substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT +OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +**************************************************************************************************/ + +#ifndef BVMinisat_System_h +#define BVMinisat_System_h + +#if defined(__linux__) +#include <fpu_control.h> +#endif + +#include "mtl/IntTypes.h" + +//------------------------------------------------------------------------------------------------- + +namespace BVMinisat { + +static inline double cpuTime(void); // CPU-time in seconds. +extern double memUsed(); // Memory in mega bytes (returns 0 for unsupported architectures). +extern double memUsedPeak(); // Peak-memory in mega bytes (returns 0 for unsupported architectures). + +} + +//------------------------------------------------------------------------------------------------- +// Implementation of inline functions: + +#if defined(_MSC_VER) || defined(__MINGW32__) +#include <time.h> + +static inline double Minisat::cpuTime(void) { return (double)clock() / CLOCKS_PER_SEC; } + +#else +#include <sys/time.h> +#include <sys/resource.h> +#include <unistd.h> + +static inline double BVMinisat::cpuTime(void) { + struct rusage ru; + getrusage(RUSAGE_SELF, &ru); + return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; } + +#endif + +#endif diff --git a/src/prop/bvpicosat/LICENSE b/src/prop/bvpicosat/LICENSE new file mode 100644 index 000000000..b2483af20 --- /dev/null +++ b/src/prop/bvpicosat/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2006 - 2010, Armin Biere, Johannes Kepler University. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. + diff --git a/src/prop/bvpicosat/Makefile.am b/src/prop/bvpicosat/Makefile.am new file mode 100644 index 000000000..c31a3824c --- /dev/null +++ b/src/prop/bvpicosat/Makefile.am @@ -0,0 +1,24 @@ +AM_CPPFLAGS = \ + -D__BUILDING_CVC4LIB \ + -D __STDC_LIMIT_MACROS \ + -D __STDC_FORMAT_MACROS \ + -I@srcdir@/ -I@srcdir@/../.. -I@srcdir@/../../.. -I@builddir@/../../.. -I@srcdir@/../../../include +AM_CXXFLAGS = -Wall -Wno-parentheses -Wno-unknown-pragmas $(FLAG_VISIBILITY_HIDDEN) + +noinst_LTLIBRARIES = libpicosat.la +libpicosat_la_SOURCES = \ + app.c \ + picosat.h \ + picosat.c \ + picomus.c \ + version.c + +EXTRA_DIST = \ + main.c \ + README \ + LICENSE \ + NEWS \ + VERSION \ + configure \ + mkconfig \ + makefile.in diff --git a/src/prop/bvpicosat/Makefile.in b/src/prop/bvpicosat/Makefile.in new file mode 100644 index 000000000..a1c392bac --- /dev/null +++ b/src/prop/bvpicosat/Makefile.in @@ -0,0 +1,633 @@ +# Makefile.in generated by automake 1.11.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, +# Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +target_triplet = @target@ +subdir = src/prop/bvpicosat +DIST_COMMON = README $(srcdir)/Makefile.am $(srcdir)/Makefile.in NEWS +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/config/antlr.m4 \ + $(top_srcdir)/config/ax_prog_doxygen.m4 \ + $(top_srcdir)/config/ax_tls.m4 \ + $(top_srcdir)/config/bindings.m4 $(top_srcdir)/config/boost.m4 \ + $(top_srcdir)/config/cudd.m4 $(top_srcdir)/config/cvc4.m4 \ + $(top_srcdir)/config/gcc_version.m4 \ + $(top_srcdir)/config/libtool.m4 \ + $(top_srcdir)/config/ltoptions.m4 \ + $(top_srcdir)/config/ltsugar.m4 \ + $(top_srcdir)/config/ltversion.m4 \ + $(top_srcdir)/config/lt~obsolete.m4 \ + $(top_srcdir)/config/pkg.m4 $(top_srcdir)/config/readline.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/cvc4autoconfig.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +LTLIBRARIES = $(noinst_LTLIBRARIES) +libpicosat_la_LIBADD = +am_libpicosat_la_OBJECTS = app.lo picosat.lo picomus.lo version.lo +libpicosat_la_OBJECTS = $(am_libpicosat_la_OBJECTS) +AM_V_lt = $(am__v_lt_$(V)) +am__v_lt_ = $(am__v_lt_$(AM_DEFAULT_VERBOSITY)) +am__v_lt_0 = --silent +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/config/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ + $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ + $(AM_CFLAGS) $(CFLAGS) +AM_V_CC = $(am__v_CC_$(V)) +am__v_CC_ = $(am__v_CC_$(AM_DEFAULT_VERBOSITY)) +am__v_CC_0 = @echo " CC " $@; +AM_V_at = $(am__v_at_$(V)) +am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY)) +am__v_at_0 = @ +CCLD = $(CC) +LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(AM_LDFLAGS) $(LDFLAGS) -o $@ +AM_V_CCLD = $(am__v_CCLD_$(V)) +am__v_CCLD_ = $(am__v_CCLD_$(AM_DEFAULT_VERBOSITY)) +am__v_CCLD_0 = @echo " CCLD " $@; +AM_V_GEN = $(am__v_GEN_$(V)) +am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY)) +am__v_GEN_0 = @echo " GEN " $@; +SOURCES = $(libpicosat_la_SOURCES) +DIST_SOURCES = $(libpicosat_la_SOURCES) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +ANTLR = @ANTLR@ +ANTLR_HOME = @ANTLR_HOME@ +ANTLR_INCLUDES = @ANTLR_INCLUDES@ +ANTLR_LDFLAGS = @ANTLR_LDFLAGS@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BOOST_CPPFLAGS = @BOOST_CPPFLAGS@ +BOOST_LDPATH = @BOOST_LDPATH@ +BOOST_ROOT = @BOOST_ROOT@ +BOOST_THREAD_LDFLAGS = @BOOST_THREAD_LDFLAGS@ +BOOST_THREAD_LDPATH = @BOOST_THREAD_LDPATH@ +BOOST_THREAD_LIBS = @BOOST_THREAD_LIBS@ +BUILDING_SHARED = @BUILDING_SHARED@ +BUILDING_STATIC = @BUILDING_STATIC@ +CAMLP4O = @CAMLP4O@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CLN_CFLAGS = @CLN_CFLAGS@ +CLN_LIBS = @CLN_LIBS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CSHARP_CPPFLAGS = @CSHARP_CPPFLAGS@ +CUDD_CPPFLAGS = @CUDD_CPPFLAGS@ +CUDD_LDFLAGS = @CUDD_LDFLAGS@ +CUDD_LIBS = @CUDD_LIBS@ +CVC4_BINDINGS_LIBRARY_VERSION = @CVC4_BINDINGS_LIBRARY_VERSION@ +CVC4_BUILD_LIBCOMPAT = @CVC4_BUILD_LIBCOMPAT@ +CVC4_COMPAT_LIBRARY_VERSION = @CVC4_COMPAT_LIBRARY_VERSION@ +CVC4_HAS_THREADS = @CVC4_HAS_THREADS@ +CVC4_LANGUAGE_BINDINGS = @CVC4_LANGUAGE_BINDINGS@ +CVC4_LIBRARY_VERSION = @CVC4_LIBRARY_VERSION@ +CVC4_PARSER_LIBRARY_VERSION = @CVC4_PARSER_LIBRARY_VERSION@ +CVC4_TLS = @CVC4_TLS@ +CVC4_TLS_SUPPORTED = @CVC4_TLS_SUPPORTED@ +CVC4_USE_CLN_IMP = @CVC4_USE_CLN_IMP@ +CVC4_USE_GMP_IMP = @CVC4_USE_GMP_IMP@ +CXX = @CXX@ +CXXCPP = @CXXCPP@ +CXXDEPMODE = @CXXDEPMODE@ +CXXFLAGS = @CXXFLAGS@ +CXXTEST = @CXXTEST@ +CXXTESTGEN = @CXXTESTGEN@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DISTCHECK_CONFIGURE_FLAGS = @DISTCHECK_CONFIGURE_FLAGS@ +DLLTOOL = @DLLTOOL@ +DOXYGEN_EXTRACT_PRIVATE = @DOXYGEN_EXTRACT_PRIVATE@ +DOXYGEN_EXTRACT_STATIC = @DOXYGEN_EXTRACT_STATIC@ +DOXYGEN_PAPER_SIZE = @DOXYGEN_PAPER_SIZE@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +DX_CONFIG = @DX_CONFIG@ +DX_DOCDIR = @DX_DOCDIR@ +DX_DOT = @DX_DOT@ +DX_DOXYGEN = @DX_DOXYGEN@ +DX_DVIPS = @DX_DVIPS@ +DX_EGREP = @DX_EGREP@ +DX_ENV = @DX_ENV@ +DX_FLAG_DX_CURRENT_FEATURE = @DX_FLAG_DX_CURRENT_FEATURE@ +DX_FLAG_chi = @DX_FLAG_chi@ +DX_FLAG_chm = @DX_FLAG_chm@ +DX_FLAG_doc = @DX_FLAG_doc@ +DX_FLAG_dot = @DX_FLAG_dot@ +DX_FLAG_html = @DX_FLAG_html@ +DX_FLAG_man = @DX_FLAG_man@ +DX_FLAG_pdf = @DX_FLAG_pdf@ +DX_FLAG_ps = @DX_FLAG_ps@ +DX_FLAG_rtf = @DX_FLAG_rtf@ +DX_FLAG_xml = @DX_FLAG_xml@ +DX_HHC = @DX_HHC@ +DX_LATEX = @DX_LATEX@ +DX_MAKEINDEX = @DX_MAKEINDEX@ +DX_PDFLATEX = @DX_PDFLATEX@ +DX_PERL = @DX_PERL@ +DX_PROJECT = @DX_PROJECT@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +FLAG_VISIBILITY_HIDDEN = @FLAG_VISIBILITY_HIDDEN@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +JAR = @JAR@ +JAVA = @JAVA@ +JAVAC = @JAVAC@ +JAVAH = @JAVAH@ +JAVA_CPPFLAGS = @JAVA_CPPFLAGS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LFSC = @LFSC@ +LFSCARGS = @LFSCARGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MAN_DATE = @MAN_DATE@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OCAMLC = @OCAMLC@ +OCAMLFIND = @OCAMLFIND@ +OCAMLMKTOP = @OCAMLMKTOP@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PERL_CPPFLAGS = @PERL_CPPFLAGS@ +PHP_CPPFLAGS = @PHP_CPPFLAGS@ +PKG_CONFIG = @PKG_CONFIG@ +PYTHON = @PYTHON@ +PYTHON_CONFIG = @PYTHON_CONFIG@ +PYTHON_CXXFLAGS = @PYTHON_CXXFLAGS@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_INCLUDE = @PYTHON_INCLUDE@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +RANLIB = @RANLIB@ +READLINE_LIBS = @READLINE_LIBS@ +RUBY_CPPFLAGS = @RUBY_CPPFLAGS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STATIC_BINARY = @STATIC_BINARY@ +STRIP = @STRIP@ +SWIG = @SWIG@ +TCL_CPPFLAGS = @TCL_CPPFLAGS@ +TEST_CPPFLAGS = @TEST_CPPFLAGS@ +TEST_CXXFLAGS = @TEST_CXXFLAGS@ +TEST_LDFLAGS = @TEST_LDFLAGS@ +VERSION = @VERSION@ +WNO_CONVERSION_NULL = @WNO_CONVERSION_NULL@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_CXX = @ac_ct_CXX@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mk_include = @mk_include@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target = @target@ +target_alias = @target_alias@ +target_cpu = @target_cpu@ +target_os = @target_os@ +target_vendor = @target_vendor@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +AM_CPPFLAGS = \ + -D__BUILDING_CVC4LIB \ + -D __STDC_LIMIT_MACROS \ + -D __STDC_FORMAT_MACROS \ + -I@srcdir@/ -I@srcdir@/../.. -I@srcdir@/../../.. -I@builddir@/../../.. -I@srcdir@/../../../include + +AM_CXXFLAGS = -Wall -Wno-parentheses -Wno-unknown-pragmas $(FLAG_VISIBILITY_HIDDEN) +noinst_LTLIBRARIES = libpicosat.la +libpicosat_la_SOURCES = \ + app.c \ + picosat.h \ + picosat.c \ + picomus.c \ + version.c + +EXTRA_DIST = \ + main.c \ + README \ + LICENSE \ + NEWS \ + VERSION \ + configure \ + mkconfig \ + makefile.in + +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/prop/bvpicosat/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu src/prop/bvpicosat/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +clean-noinstLTLIBRARIES: + -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + @list='$(noinst_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libpicosat.la: $(libpicosat_la_OBJECTS) $(libpicosat_la_DEPENDENCIES) + $(AM_V_CCLD)$(LINK) $(libpicosat_la_OBJECTS) $(libpicosat_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/app.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/picomus.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/picosat.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/version.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@am__fastdepCC_FALSE@ $(AM_V_CC) @AM_BACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + `test -z '$(STRIP)' || \ + echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-noinstLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/src/prop/bvpicosat/NEWS b/src/prop/bvpicosat/NEWS new file mode 100644 index 000000000..ea3e1ce26 --- /dev/null +++ b/src/prop/bvpicosat/NEWS @@ -0,0 +1,93 @@ +news for release 936 since 935 +------------------------------ + +* simple minimal unsatisfiable core (MUS) extractor 'picomus' + (example for using 'picosat_mus_assumptions' and 'picosat_coreclause') + +* added 'picosat_mus_assumptions' + +* added 'picosat_{set_}propagations' + +* new 'int' return value for 'picosat_enable_trace_generation' to + check for trace code being compiled + +news for release 935 since 926 +------------------------------ + +* added 'picosat_failed_assumptions' (plural) + +* new '-A <failedlits>' command line option + +* fixed failed assumption issues + +* added 'picosat_remove_learned' + +* added 'picosat_reset_{phases,scores}' + +* added 'picosat_set_less_important_lit' + +* added 'picosat_res' + +news for release 926 since 846 +------------------------------ + +* random initial phase (API of 'picosat_set_default_phase' changed) + +* fixed accumulative failed assumption (multiple times) + +* fixed missing original clause in core generation with assumptions + +* fixed debugging code for memory allocation + +* shared library in addition to static library + +* removed potential UNKNOWN result without decision limit + +* added picosat_set_more_important_lit + +* added picosat_coreclause + +* propagation of binary clauses until completion + +* fixed API usage 'assume;sat;sat' + +* literals move to front (LMTF) during traversal of visited clauses + +* switched from inner/outer to Luby style restart scheduling + +* less agressive reduce schedule + +* replaced watched literals with head and tail pointers + +* add 'picosat_failed_assumption', which allows to avoid tracing and core + generation, if one is only interested in assumptions in the core + +* fixed a BUG in the generic iterator code of clauses + (should rarely happen unless you use a very sophisticated malloc lib) + +news for release 846 since 632 +------------------------------ + +* cleaned up assumption handling (actually removed buggy optimization) + +* incremental core generation + +* experimental 'all different constraint' handling as in our FMCAD'08 paper + +* new API calls: + + - picosat_add_ado_lit (add all different object literal) + - picosat_deref_top_level (deref top level assignment) + - picosat_changed (check whether extension was possible) + - picosat_measure_all_calls (per default do not measure adding time) + - picosat_set_prefix (set prefix for messages) + +* 64 bit port (and compilation options) + +* optional NVSIDS visualization code + +* resource controlled failed literal implementation + +* disconnect long clauses satisfied at lower decision level + +* controlling restarts diff --git a/src/prop/bvpicosat/README b/src/prop/bvpicosat/README new file mode 100644 index 000000000..89d6ea5f6 --- /dev/null +++ b/src/prop/bvpicosat/README @@ -0,0 +1,5 @@ +These are the sources of the PicoSAT solver. +The preprocessor is not included. +To compile run './configure && make'. +The API is document in 'picosat.h'. +See also 'NEWS' and 'LICENSE'. diff --git a/src/prop/bvpicosat/VERSION b/src/prop/bvpicosat/VERSION new file mode 100644 index 000000000..10c7f0b94 --- /dev/null +++ b/src/prop/bvpicosat/VERSION @@ -0,0 +1 @@ +936 diff --git a/src/prop/bvpicosat/app.c b/src/prop/bvpicosat/app.c new file mode 100644 index 000000000..667a2ac8c --- /dev/null +++ b/src/prop/bvpicosat/app.c @@ -0,0 +1,923 @@ +#include "picosat.h" + +#include <assert.h> +#include <string.h> +#include <ctype.h> +#include <stdio.h> + +#define GUNZIP "gunzip -c %s" +#define GZIP "gzip -c -f > %s" + +FILE * popen (const char *, const char*); +int pclose (FILE *); + +static int lineno; +static FILE *input; +static int inputid; +static FILE *output; +static int verbose; +static int sargc; +static char ** sargv; +static char buffer[100]; +static char *bhead = buffer; +static const char *eob = buffer + 80; +static FILE * incremental_rup_file; + +extern void picosat_enter (void); +extern void picosat_leave (void); + +static char page[4096]; +static char * top; +static char * end; + +static int +next (void) +{ + size_t bytes; + int res; + + if (top == end) + { + if (end < page + sizeof page) + return EOF; + + bytes = fread (page, 1, sizeof page, input); + if (bytes == 0) + return EOF; + + top = page; + end = page + bytes; + } + + res = *top++; + + if (res == '\n') + lineno++; + + return res; +} + +static const char * +parse (int force) +{ + int ch, sign, lit, vars, clauses; + + lineno = 1; + inputid = fileno (input); + +SKIP_COMMENTS: + ch = next (); + if (ch == 'c') + { + while ((ch = next ()) != EOF && ch != '\n') + ; + goto SKIP_COMMENTS; + } + + if (isspace (ch)) + goto SKIP_COMMENTS; + + if (ch != 'p') +INVALID_HEADER: + return "missing or invalid 'p cnf <variables> <clauses>' header"; + + if (!isspace (next ())) + goto INVALID_HEADER; + + while (isspace (ch = next ())) + ; + + if (ch != 'c' || next () != 'n' || next () != 'f' || !isspace (next ())) + goto INVALID_HEADER; + + while (isspace (ch = next ())) + ; + + if (!isdigit (ch)) + goto INVALID_HEADER; + + vars = ch - '0'; + while (isdigit (ch = next ())) + vars = 10 * vars + (ch - '0'); + + if (!isspace (ch)) + goto INVALID_HEADER; + + while (isspace (ch = next ())) + ; + + if (!isdigit (ch)) + goto INVALID_HEADER; + + clauses = ch - '0'; + while (isdigit (ch = next ())) + clauses = 10 * clauses + (ch - '0'); + + if (!isspace (ch) && ch != '\n' ) + goto INVALID_HEADER; + + if (verbose) + { + fprintf (output, "c parsed header 'p cnf %d %d'\n", vars, clauses); + fflush (output); + } + + picosat_adjust (vars); + + if (incremental_rup_file) + picosat_set_incremental_rup_file (incremental_rup_file, vars, clauses); + + lit = 0; +READ_LITERAL: + ch = next (); + + if (ch == 'c') + { + while ((ch = next ()) != EOF && ch != '\n') + ; + goto READ_LITERAL; + } + + if (ch == EOF) + { + if (lit) + return "trailing 0 missing"; + + if (clauses && !force) + return "clause missing"; + + return 0; + } + + if (isspace (ch)) + goto READ_LITERAL; + + sign = 1; + if (ch == '-') + { + sign = -1; + ch = next (); + } + + if (!isdigit (ch)) + return "expected number"; + + lit = ch - '0'; + while (isdigit (ch = next ())) + lit = 10 * lit + (ch - '0'); + + if (!clauses && !force) + return "too many clauses"; + + if (lit) + { + if (lit > vars && !force) + return "maximal variable index exceeded"; + + lit *= sign; + } + else + clauses--; + + picosat_add (lit); + + goto READ_LITERAL; +} + +static void +bflush (void) +{ + *bhead = 0; + fputs (buffer, output); + fputc ('\n', output); + bhead = buffer; +} + +static void +printi (int i) +{ + char *next; + int l; + +REENTER: + if (bhead == buffer) + *bhead++ = 'v'; + + l = sprintf (bhead, " %d", i); + next = bhead + l; + + if (next >= eob) + { + bflush (); + goto REENTER; + } + else + bhead = next; +} + +static void +printa (void) +{ + int max_idx = picosat_variables (), i, lit; + + assert (bhead == buffer); + + for (i = 1; i <= max_idx; i++) + { + lit = (picosat_deref (i) > 0) ? i : -i; + printi (lit); + } + + printi (0); + if (bhead > buffer) + bflush (); +} + +static int +has_suffix (const char *str, const char *suffix) +{ + const char *tmp = strstr (str, suffix); + if (!tmp) + return 0; + + return str + strlen (str) - strlen (suffix) == tmp; +} + +static void +write_core_variables (FILE * file) +{ + int i, max_idx = picosat_variables (), count = 0; + for (i = 1; i <= max_idx; i++) + if (picosat_corelit (i)) + { + fprintf (file, "%d\n", i); + count++; + } + + if (verbose) + fprintf (output, "c found and wrote %d core variables\n", count); +} + +static int +next_assumption (int start) +{ + char * arg, c; + int res; + res = start + 1; + while (res < sargc) + { + arg = sargv[res++]; + if (!strcmp (arg, "-a")) + { + assert (res < sargc); + break; + } + + if (arg[0] == '-') { + c = arg[1]; + if (c == 'l' || c == 'i' || c == 's' || c == 'o' || c == 't' || + c == 'T' || c == 'r' || c == 'R' || c == 'c' || c == 'V' || + c == 'U' || c == 'A') res++; + } + } + if (res >= sargc) res = 0; + return res; +} + +static void +write_failed_assumptions (FILE * file) +{ + int i, lit, count = 0; +#ifndef NDEBUG + int max_idx = picosat_variables (); +#endif + i = 0; + while ((i = next_assumption (i))) { + lit = atoi (sargv[i]); + if (!picosat_failed_assumption (lit)) continue; + fprintf (file, "%d\n", lit); + count++; + } + if (verbose) + fprintf (output, "c found and wrote %d failed assumptions\n", count); +#ifndef NDEBUG + for (i = 1; i <= max_idx; i++) + if (picosat_failed_assumption (i)) + count--; +#endif + assert (!count); +} + +static void +write_to_file (const char *name, const char *type, void (*writer) (FILE *)) +{ + int pclose_file, zipped = has_suffix (name, ".gz"); + FILE *file; + char *cmd; + + if (zipped) + { + cmd = malloc (strlen (GZIP) + strlen (name)); + sprintf (cmd, GZIP, name); + file = popen (cmd, "w"); + free (cmd); + pclose_file = 1; + } + else + { + file = fopen (name, "w"); + pclose_file = 0; + } + + if (file) + { + if (verbose) + fprintf (output, + "c\nc writing %s%s to '%s'\n", + zipped ? "gzipped " : "", type, name); + + writer (file); + + if (pclose_file) + pclose (file); + else + fclose (file); + } + else + fprintf (output, "*** picosat: can not write to '%s'\n", name); +} + +#define USAGE \ +"usage: picosat [ <option> ... ] [ <input> ]\n" \ +"\n" \ +"where <option> is one of the following\n" \ +"\n" \ +" -h print this command line option summary and exit\n" \ +" --version print version and exit\n" \ +" --config print build configuration and exit\n" \ +"\n" \ +" -v enable verbose output\n" \ +" -f ignore invalid header\n" \ +" -n do not print satisfying assignment\n" \ +" -p print formula in DIMACS format and exit\n" \ +" -a <lit> start with an assumption\n" \ +" -l <limit> set decision limit (no limit per default)\n" \ +" -P <limit> set propagation limit (no limit per default)\n" \ +" -i [0-3] [0-3]=[FALSE,TRUE,JWH,RAND] initial phase (default 2=JWH)\n" \ +" -s <seed> set random number generator seed (default 0)\n" \ +" -o <output> set output file (<stdout> per default)\n" \ +" -t <trace> generate compact proof trace file\n" \ +" -T <trace> generate extended proof trace file\n" \ +" -r <trace> generate reverse unit propagation proof file\n" \ +" -R <trace> generate reverse unit propagation proof file incrementally\n" \ +" -c <core> generate clausal core file in DIMACS format\n" \ +" -V <core> generate file listing core variables\n" \ +" -U <core> generate file listing used variables\n" \ +" -A <core> generate file listing failed assumptions\n" \ +"\n" \ +"and <input> is an optional input file in DIMACS format.\n" + +int +picosat_main (int argc, char **argv) +{ + int res, done, err, print_satisfying_assignment, force, print_formula; + const char *compact_trace_name, *extended_trace_name, * rup_trace_name; + const char * clausal_core_name, * variable_core_name; + int assumption, assumptions, defaultphase; + const char *input_name, *output_name; + const char * failed_assumptions_name; + int close_input, pclose_input; + long long propagation_limit; + int i, decision_limit; + double start_time; + unsigned seed; + FILE *file; + int trace; + + start_time = picosat_time_stamp (); + + sargc = argc; + sargv = argv; + + clausal_core_name = 0; + variable_core_name = 0; + failed_assumptions_name = 0; + output_name = 0; + compact_trace_name = 0; + extended_trace_name = 0; + rup_trace_name = 0; + incremental_rup_file = 0; + close_input = 0; + pclose_input = 0; + input_name = "<stdin>"; + input = stdin; + output = stdout; + verbose = 0; + done = err = 0; + decision_limit = -1; + propagation_limit = -1; + defaultphase = 2; + assumptions = 0; + force = 0; + trace = 0; + seed = 0; + + top = end = page + sizeof page; + + print_satisfying_assignment = 1; + print_formula = 0; + + for (i = 1; !done && !err && i < argc; i++) + { + if (!strcmp (argv[i], "-h")) + { + fputs (USAGE, output); + done = 1; + } + else if (!strcmp (argv[i], "--version")) + { + fprintf (output, "%s\n", picosat_version ()); + done = 1; + } + else if (!strcmp (argv[i], "--config")) + { + fprintf (output, "%s\n", picosat_config ()); + done = 1; + } + else if (!strcmp (argv[i], "-v")) + { + verbose++; + } + else if (!strcmp (argv[i], "-f")) + { + force = 1; + } + else if (!strcmp (argv[i], "-n")) + { + print_satisfying_assignment = 0; + } + else if (!strcmp (argv[i], "-p")) + { + print_formula = 1; + } + else if (!strcmp (argv[i], "-l")) + { + if (++i == argc) + { + fprintf (output, "*** picosat: argument to '-l' missing\n"); + err = 1; + } + else + decision_limit = atoi (argv[i]); + } + else if (!strcmp (argv[i], "-P")) + { + if (++i == argc) + { + fprintf (output, "*** picosat: argument to '-P' missing\n"); + err = 1; + } + else + propagation_limit = atoll (argv[i]); + } + else if (!strcmp (argv[i], "-i")) + { + if (++i == argc) + { + fprintf (output, "*** picosat: argument to '-i' missing\n"); + err = 1; + } + else if (!argv[i][1] && ('0' <= argv[i][0] && argv[i][0] <= '3')) + { + defaultphase = argv[i][0] - '0'; + } + else + { + fprintf (output, "*** picosat: invalid argument to '-i'\n"); + err = 1; + } + } + else if (!strcmp (argv[i], "-a")) + { + if (++i == argc) + { + fprintf (output, "*** picosat: argument to '-a' missing\n"); + err = 1; + } + else if (!atoi (argv[i])) + { + fprintf (output, "*** picosat: argument to '-a' zero\n"); + err = 1; + } + else + { + /* Handle assumptions further down + */ + assumptions++; + } + } + else if (!strcmp (argv[i], "-s")) + { + if (++i == argc) + { + fprintf (output, "*** picosat: argument to '-s' missing\n"); + err = 1; + } + else + seed = atoi (argv[i]); + } + else if (!strcmp (argv[i], "-o")) + { + if (output_name) + { + fprintf (output, + "*** picosat: " + "multiple output files '%s' and '%s'\n", + output_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-o' missing\n"); + err = 1; + } + else if (!(file = fopen (argv[i], "w"))) + { + fprintf (output, + "*** picosat: " + "can not write output file '%s'\n", argv[i]); + err = 1; + } + else + { + output_name = argv[i]; + output = file; + } + } + else if (!strcmp (argv[i], "-t")) + { + if (compact_trace_name) + { + fprintf (output, + "*** picosat: " + "multiple compact trace files '%s' and '%s'\n", + compact_trace_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-t' missing\n"); + err = 1; + } + else + { + compact_trace_name = argv[i]; + trace = 1; + } + } + else if (!strcmp (argv[i], "-T")) + { + if (extended_trace_name) + { + fprintf (output, + "*** picosat: " + "multiple extended trace files '%s' and '%s'\n", + extended_trace_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-T' missing\n"); + err = 1; + } + else + { + extended_trace_name = argv[i]; + trace = 1; + } + } + else if (!strcmp (argv[i], "-r")) + { + if (rup_trace_name) + { + fprintf (output, + "*** picosat: " + "multiple RUP trace files '%s' and '%s'\n", + rup_trace_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-r' missing\n"); + err = 1; + } + else + { + rup_trace_name = argv[i]; + trace = 1; + } + } + else if (!strcmp (argv[i], "-R")) + { + if (rup_trace_name) + { + fprintf (output, + "*** picosat: " + "multiple RUP trace files '%s' and '%s'\n", + rup_trace_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-R' missing\n"); + err = 1; + } + else if (!(file = fopen (argv[i], "w"))) + { + fprintf (output, + "*** picosat: can not write to '%s'\n", argv[i]); + err = 1; + } + else + { + rup_trace_name = argv[i]; + incremental_rup_file = file; + } + } + else if (!strcmp (argv[i], "-c")) + { + if (clausal_core_name) + { + fprintf (output, + "*** picosat: " + "multiple clausal core files '%s' and '%s'\n", + clausal_core_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-c' missing\n"); + err = 1; + } + else + { + clausal_core_name = argv[i]; + trace = 1; + } + } + else if (!strcmp (argv[i], "-V")) + { + if (variable_core_name) + { + fprintf (output, + "*** picosat: " + "multiple variable core files '%s' and '%s'\n", + variable_core_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-V' missing\n"); + err = 1; + } + else + { + variable_core_name = argv[i]; + trace = 1; + } + } + else if (!strcmp (argv[i], "-A")) + { + if (failed_assumptions_name) + { + fprintf (output, + "*** picosat: " + "multiple failed assumptions files '%s' and '%s'\n", + failed_assumptions_name, argv[i]); + err = 1; + } + else if (++i == argc) + { + fprintf (output, "*** picosat: argument ot '-A' missing\n"); + err = 1; + } + else + failed_assumptions_name = argv[i]; + } + else if (argv[i][0] == '-') + { + fprintf (output, + "*** picosat: " + "unknown command line option '%s' (try '-h')\n", argv[i]); + err = 1; + } + else if (close_input || pclose_input) + { + fprintf (output, + "*** picosat: " + "multiple input files '%s' and '%s'\n", + input_name, argv[i]); + err = 1; + } + else if (has_suffix (argv[i], ".gz")) + { + char *cmd = malloc (strlen (GUNZIP) + strlen (argv[i])); + sprintf (cmd, GUNZIP, argv[i]); + if ((file = popen (cmd, "r"))) + { + input_name = argv[i]; + pclose_input = 1; + input = file; + } + else + { + fprintf (output, + "*** picosat: " + "can not read compressed input file '%s'\n", argv[i]); + err = 1; + } + free (cmd); + } + else if (!(file = fopen (argv[i], "r"))) /* TODO .gz ? */ + { + fprintf (output, + "*** picosat: can not read input file '%s'\n", argv[i]); + err = 1; + } + else + { + input_name = argv[i]; + close_input = 1; + input = file; + } + } + + res = PICOSAT_UNKNOWN; + + if (!done && !err) + { + const char *err_msg; + + if (verbose) + { + fprintf (output, + "c PicoSAT SAT Solver Version %s\n", + picosat_version ()); + + fprintf (output, "c %s\n", picosat_copyright ()); + fprintf (output, "c %s\n", picosat_config ()); + } + + picosat_init (); + picosat_enter (); + + if (output_name) + picosat_set_output (output); + + picosat_set_verbosity (verbose); + + if (verbose) fputs ("c\n", output); + + if (trace) + { + if (verbose) + fprintf (output, "c tracing proof\n"); + picosat_enable_trace_generation (); + } + + if (defaultphase) + { + if (verbose) + fprintf (output, "c using %d as default phase\n", defaultphase); + + picosat_set_global_default_phase (defaultphase); + } + + if (propagation_limit >= 0) + { + if (verbose) + fprintf (output, "c propagation limit of %lld propagations\n", + propagation_limit); + picosat_set_propagation_limit ( + (unsigned long long) propagation_limit); + } + + if (verbose) + fprintf (output, "c\nc parsing %s\n", input_name); + + if ((err_msg = parse (force))) + { + fprintf (output, "%s:%d: %s\n", input_name, lineno, err_msg); + err = 1; + } + else + { + if (assumptions) + { + i = 0; + while ((i = next_assumption (i))) + { + assert (i < argc); + assumption = atoi (argv[i]); + assert (assumption); + + picosat_assume (assumption); + + if (verbose) + fprintf (output, "c assumption %d\n", assumption); + } + } + + if (print_formula) + { + picosat_print (output); + } + else + { + if (verbose) + fprintf (output, + "c initialized %u variables\n" + "c found %u non trivial clauses\n", + picosat_variables (), + picosat_added_original_clauses ()); + + picosat_set_seed (seed); + if (verbose) + fprintf (output, + "c\nc random number generator seed %u\n", + seed); + + res = picosat_sat (decision_limit); + + if (res == PICOSAT_UNSATISFIABLE) + { + fputs ("s UNSATISFIABLE\n", output); + + if (compact_trace_name) + write_to_file (compact_trace_name, + "compact trace", + picosat_write_compact_trace); + + if (extended_trace_name) + write_to_file (extended_trace_name, + "extended trace", + picosat_write_extended_trace); + + if (!incremental_rup_file && rup_trace_name) + write_to_file (rup_trace_name, + "rup trace", + picosat_write_rup_trace); + + if (clausal_core_name) + write_to_file (clausal_core_name, + "clausal core", + picosat_write_clausal_core); + + if (variable_core_name) + write_to_file (variable_core_name, + "variable core", write_core_variables); + + if (failed_assumptions_name) + write_to_file (failed_assumptions_name, + "failed assumptions", + write_failed_assumptions); + } + else if (res == PICOSAT_SATISFIABLE) + { + fputs ("s SATISFIABLE\n", output); + + if (print_satisfying_assignment) + printa (); + } + else + fputs ("s UNKNOWN\n", output); + } + } + + if (!err && verbose) + { + fputs ("c\n", output); + picosat_stats (); + fprintf (output, + "c %.1f seconds total run time\n", + picosat_time_stamp () - start_time); + } + + picosat_leave (); + picosat_reset (); + } + + if (incremental_rup_file) + fclose (incremental_rup_file); + + if (close_input) + fclose (input); + + if (pclose_input) + pclose (input); + + if (output_name) + fclose (output); + + return res; +} diff --git a/src/prop/bvpicosat/config.h b/src/prop/bvpicosat/config.h new file mode 100644 index 000000000..aa6888822 --- /dev/null +++ b/src/prop/bvpicosat/config.h @@ -0,0 +1,3 @@ +#define PICOSAT_CC "gcc" +#define PICOSAT_CFLAGS "-DSTATS -DTRACE -Wall -Wextra -DNDEBUG -O2" +#define PICOSAT_VERSION "936" diff --git a/src/prop/bvpicosat/configure b/src/prop/bvpicosat/configure new file mode 100755 index 000000000..23cf0efb4 --- /dev/null +++ b/src/prop/bvpicosat/configure @@ -0,0 +1,151 @@ +#!/bin/sh + +satcompetition=no + +log=no +debug=no +optimize=no +stats=undefined +trace=undefined +static=yes +shared=no +thirtytwobit=no +static=no + +while [ $# -gt 0 ] +do + case $1 in + -l|--log) debug=yes; log=yes;; + -g|--debug) debug=yes; optimize=no;; + -s|--stats) stats=yes;; + -t|--trace) trace=yes;; + --no-stats) stats=no;; + --no-trace) trace=no;; + -32|--32|-m32) thirtytwobit=yes;; + -static|--static) static=yes;; + -O) debug=no; optimize=yes;; + *) cat <<EOF +usage: ./configure [<option> ...] + +where <option> is one of the following: + + -g|--debug includ debugging code and symbols + -l|--log add low level logging code + -s|--stats include and enable more expensive stats counters + -t|--trace compile with trace generation support (more memory) + --no-stats disable expensive stats + --no-trace enable trace generation (less memory) + -32|--32|-m32 compile for 32 bit machine even on 64 bit host + -static|--static only produce static library + -shared|--shared produce shared library as well + -O optimize a lot and disable trace generation +EOF +exit 1 +;; + esac +shift +done + +echo "version ... `cat VERSION`" + +if [ $satcompetition = yes ] +then + debug=no + optimize=yes + stats=no + trace=no + thirtytwobit=yes + static=yes + shared=no +fi + +echo "debug ... $debug" +echo "optimize ... $optimize" +echo "log ... $log" + +if [ $stats = undefined ] +then + if [ $optimize = yes ] + then + stats=no + else + stats=yes + fi +fi +echo "stats ... $stats" + +if [ $trace = undefined ] +then + if [ $optimize = yes ] + then + trace=no + else + trace=yes + fi +fi +echo "trace ... $trace" + +echo "static ... $static" + +echo "shared ... $shared" + +[ "X$CC" = X ] && CC=gcc + +if [ X"$CFLAGS" = X ] +then + case X"$CC" in + *wine*|*mingw*) CFLAGS="-DNGETRUSAGE -DNALLSIGNALS";; + *);; + esac + [ $log = yes ] && CFLAGS="$CFLAGS -DLOGGING" + [ $stats = yes ] && CFLAGS="$CFLAGS -DSTATS" + [ $trace = yes ] && CFLAGS="$CFLAGS -DTRACE" + [ $static = yes ] && CFLAGS="$CFLAGS -static" + case X"$CC" in + X*gcc*) + CFLAGS="$CFLAGS -Wall -Wextra" + [ $thirtytwobit = yes ] && CFLAGS="$CFLAGS -m32" + if [ $debug = yes ] + then + CFLAGS="$CFLAGS -g3 -ggdb" + else + CFLAGS="$CFLAGS -DNDEBUG" + if [ $optimize = yes ] + then + CFLAGS="$CFLAGS -O3 -fomit-frame-pointer -finline-limit=1000000" + else + CFLAGS="$CFLAGS -O2" + fi + fi + ;; + *) + if [ $debug = yes ] + then + CFLAGS="$CFLAGS -g" + else + CFLAGS="$CFLAGS -O" + fi + ;; + esac +fi + +TARGETS="picosat picomus libpicosat.a" +if [ $shared = yes ] +then + TARGETS="$TARGETS libpicosat.so" + CFLAGS="$CFLAGS -fPIC" +fi +echo "targets ... $TARGETS" + +echo "cc ... $CC" + +echo "cflags ... $CFLAGS" + +echo -n "makefile ..." +rm -f makefile +sed \ + -e "s,@CC@,$CC," \ + -e "s,@CFLAGS@,$CFLAGS," \ + -e "s,@TARGETS@,$TARGETS," \ +makefile.in > makefile +echo " done" diff --git a/src/prop/bvpicosat/main.c b/src/prop/bvpicosat/main.c new file mode 100644 index 000000000..cb82580fa --- /dev/null +++ b/src/prop/bvpicosat/main.c @@ -0,0 +1,90 @@ +#include <signal.h> +#include <stdlib.h> +#include <string.h> + +#include "picosat.h" + +int picosat_main (int, char **); + +static int catched; + +static void (*sig_int_handler); +static void (*sig_segv_handler); +static void (*sig_abrt_handler); +static void (*sig_term_handler); +#ifndef NALLSIGNALS +static void (*sig_kill_handler); +static void (*sig_xcpu_handler); +static void (*sig_xfsz_handler); +#endif + +static void +resetsighandlers (void) +{ + (void) signal (SIGINT, sig_int_handler); + (void) signal (SIGSEGV, sig_segv_handler); + (void) signal (SIGABRT, sig_abrt_handler); + (void) signal (SIGTERM, sig_term_handler); +#ifndef NALLSIGNALS + (void) signal (SIGKILL, sig_kill_handler); + (void) signal (SIGXCPU, sig_xcpu_handler); + (void) signal (SIGXFSZ, sig_xfsz_handler); +#endif +} + +static void +message (int sig) +{ + picosat_message (1, ""); + picosat_message (1, "*** CAUGHT SIGNAL %d ***", sig); + picosat_message (1, ""); +} + +static void +catch (int sig) +{ + if (!catched) + { + message (sig); + catched = 1; + picosat_stats (); + message (sig); + } + + resetsighandlers (); + raise (sig); +} + +static void +setsighandlers (void) +{ + sig_int_handler = signal (SIGINT, catch); + sig_segv_handler = signal (SIGSEGV, catch); + sig_abrt_handler = signal (SIGABRT, catch); + sig_term_handler = signal (SIGTERM, catch); +#ifndef NALLSIGNALS + sig_kill_handler = signal (SIGKILL, catch); + sig_xcpu_handler = signal (SIGXCPU, catch); + sig_xfsz_handler = signal (SIGXFSZ, catch); +#endif +} + +int +main (int argc, char **argv) +{ + int res, verbose; + + for (verbose = argc - 1; verbose; verbose--) + if (!strcmp (argv[verbose], "-v")) + break; + + if (verbose) + setsighandlers (); + + res = picosat_main (argc, argv); + + if (verbose) + resetsighandlers (); + + return res; +} diff --git a/src/prop/bvpicosat/makefile b/src/prop/bvpicosat/makefile new file mode 100644 index 000000000..f6fd2f099 --- /dev/null +++ b/src/prop/bvpicosat/makefile @@ -0,0 +1,43 @@ +CC=gcc +CFLAGS= -DSTATS -DTRACE -Wall -Wextra -DNDEBUG -O2 + +all: picosat picomus libpicosat.a + +clean: + rm -f picosat *.exe *.s *.o *.a *.so + rm -f makefile config.h + rm -f gmon.out *~ + +picosat: libpicosat.a app.o main.o + $(CC) $(CFLAGS) -o $@ main.o app.o -L. -lpicosat + +picomus: libpicosat.a picomus.o + $(CC) $(CFLAGS) -o $@ picomus.o -L. -lpicosat + +app.o: app.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +picomus.o: picomus.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +main.o: main.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +picosat.o: picosat.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +version.o: version.c config.h makefile + $(CC) $(CFLAGS) -c $< + +config.h: makefile VERSION mkconfig # and actually picosat.c + rm -f $@; ./mkconfig > $@ + +libpicosat.a: picosat.o version.o + ar rc $@ picosat.o version.o + ranlib $@ + +SONAME=-Xlinker -soname -Xlinker libpicosat.so +libpicosat.so: picosat.o version.o + $(CC) $(CFLAGS) -shared -o $@ picosat.o version.o $(SONAME) + +.PHONY: all clean diff --git a/src/prop/bvpicosat/makefile.in b/src/prop/bvpicosat/makefile.in new file mode 100644 index 000000000..8c8f22299 --- /dev/null +++ b/src/prop/bvpicosat/makefile.in @@ -0,0 +1,43 @@ +CC=@CC@ +CFLAGS=@CFLAGS@ + +all: @TARGETS@ + +clean: + rm -f picosat *.exe *.s *.o *.a *.so + rm -f makefile config.h + rm -f gmon.out *~ + +picosat: libpicosat.a app.o main.o + $(CC) $(CFLAGS) -o $@ main.o app.o -L. -lpicosat + +picomus: libpicosat.a picomus.o + $(CC) $(CFLAGS) -o $@ picomus.o -L. -lpicosat + +app.o: app.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +picomus.o: picomus.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +main.o: main.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +picosat.o: picosat.c picosat.h makefile + $(CC) $(CFLAGS) -c $< + +version.o: version.c config.h makefile + $(CC) $(CFLAGS) -c $< + +config.h: makefile VERSION mkconfig # and actually picosat.c + rm -f $@; ./mkconfig > $@ + +libpicosat.a: picosat.o version.o + ar rc $@ picosat.o version.o + ranlib $@ + +SONAME=-Xlinker -soname -Xlinker libpicosat.so +libpicosat.so: picosat.o version.o + $(CC) $(CFLAGS) -shared -o $@ picosat.o version.o $(SONAME) + +.PHONY: all clean diff --git a/src/prop/bvpicosat/mkconfig b/src/prop/bvpicosat/mkconfig new file mode 100755 index 000000000..d0c8fa835 --- /dev/null +++ b/src/prop/bvpicosat/mkconfig @@ -0,0 +1,35 @@ +#!/bin/sh + +die () { + echo "*** mkconfig: $*" 1>&2 + exit 1 +} + +[ -f makefile ] || die "can not find 'makefile'" + +sed \ + -e '/^C[A-Z]*=/!d' \ + -e 's,^,#define PICOSAT_,' \ + -e 's,= *, ",' \ + -e 's,$,",' \ + makefile + +id="" +if [ -d .git -a -f .git/HEAD ] +then + head="`awk 'NF == 1' .git/HEAD`" + if [ x"$head" = x ] + then + head="`awk '{print $2}' .git/HEAD`" + if [ ! x"$head" = x -a -f ".git/$head" ] + then + id=" `cat .git/$head`" + fi + else + id=" $head" + fi +fi + +echo "#define PICOSAT_VERSION \"`cat VERSION`$id\"" + +exit 0 diff --git a/src/prop/bvpicosat/picomus.c b/src/prop/bvpicosat/picomus.c new file mode 100644 index 000000000..bf98dc644 --- /dev/null +++ b/src/prop/bvpicosat/picomus.c @@ -0,0 +1,340 @@ +/**************************************************************************** +Copyright (c) 2010, Armin Biere, Johannes Kepler University. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +****************************************************************************/ + +#include "picosat.h" + +#include <stdio.h> +#include <assert.h> +#include <string.h> +#include <stdarg.h> +#include <ctype.h> + +#define MAXNONREDROUNDS 3 +#define MINCOREROUNDS 5 +#define MAXCOREROUNDS 100 + +typedef struct Cls { int lit, red, * lits; } Cls; + +static int verbose; +static int fclose_input, pclose_input, close_output; +static FILE * input_file, * output_file; +static const char * input_name, * output_name; +static int lineno = 1; +static int nvars, nclauses; +static Cls * clauses; +static int * lits, nlits, szlits; +static double start; +static int reductions; + +static int next (void) { + int res = fgetc (input_file); + if (res == '\n') lineno++; + return res; +} + +static void msg (const char * fmt, ...) { + va_list ap; + if (!verbose) return; + fputs ("c [picomus] ", stderr); + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + fputc ('\n', stderr); + fflush (stderr); +} + +static const char * parse (void) { + int ch, n, lit, sign, i; + Cls * c; +HEADER: + ch = next (); + if (ch == 'c') { + while ((ch = next ()) != '\n') + if (ch == EOF) return "EOF after 'c'"; + goto HEADER; + } + if (ch == '\r') goto HEADER; + if (ch != 'p') return "expected 'c' or 'p'"; + if (fscanf (input_file, " cnf %d %d", &nvars, &nclauses) != 2) + return "invalid header"; + msg ("p cnf %d %d", nvars, nclauses); + clauses = calloc (nclauses, sizeof *clauses); + lit = n = 0; +LIT: + ch = next (); + if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r') goto LIT; + if (ch == 'c') { + while ((ch = next ()) != '\n') + if (ch == EOF) return "EOF after 'c'"; + goto LIT; + } + if (ch == EOF) { + if (lit) return "zero missing"; + if (n < nclauses) return "clauses missing"; + return 0; + } + if (n == nclauses) return "too many clauses"; + if (ch == '-') { + sign = -1; + ch = next (); + if (!isdigit (ch)) return "expected digit after '-'"; + } else sign = 1; + if (!isdigit (ch)) return "expected digit"; + lit = ch - '0'; + while (isdigit (ch = next ())) + lit = 10 * lit + (ch - '0'); + if (lit > nvars) return "maximum variable index exceeded"; + if (lit) { + lit *= sign; + if (nlits == szlits) { + szlits = szlits ? 2 * szlits : 1; + lits = realloc (lits, szlits * sizeof *lits); + } + lits[nlits++] = lit; + } else { + c = clauses + n++; + c->lits = malloc ((nlits + 1) * sizeof *c->lits); + for (i = 0; i < nlits; i++) + c->lits[i] = lits[i]; + c->lits[i] = 0; + nlits = 0; + } + goto LIT; +} + +static void die (const char * fmt, ...) { + va_list ap; + fputs ("*** picomus: ", stderr); + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + fputc ('\n', stderr); + fflush (stderr); + exit (1); +} + +static double percent (double a, double b) { return b?100.0*a/b:0.0; } + +static void callback (void * dummy, const int * mus) { + int remaining; + const int * p; + (void) dummy; + if (!verbose) return; + remaining = 0; + for (p = mus; *p; p++) remaining++; + assert (remaining <= nclauses); + reductions++; + msg ("reduction %d to %d out of %d (%.0f%%) after %.1f sec", + reductions, + remaining, nclauses, percent (remaining, nclauses), + picosat_time_stamp () - start); +} + +int main (int argc, char ** argv) { + int i, * p, n, oldn, red, nonred, tmp, res, round, printed, len; + const char * err; + const int * q; + char * cmd; + Cls * c; + start = picosat_time_stamp (); + for (i = 1; i < argc; i++) { + if (!strcmp (argv[i], "-h")) { + printf ( + "picomus [-v][-h][<input>[<output>]]\n" + "\n" + "This tool is a SAT solver that uses the PicoSAT library to\n" + "generate a 'minimal unsatisfiable core' also known as 'minimal\n" + "unsatisfiable set' (MUS) of a CNF in DIMACS format.\n" + "\n" + "Both file argumetns can be \"-\" and then denote <stdin> resp.\n" + "<stdout>. If no input file is given <stdin> is used. If no\n" + "output file is specified the MUS is only computed, but not\n" + "printed.\n" + "\n" + "Otherwise the output conforms to the standard SAT solver\n" + "format used at SAT competitions.\n" + "\n" +#ifndef TRACE + "WARNING: PicosSAT is compiled without trace support.\n" + "\n" + "This typically slows down this MUS extractor, since\n" + "it only relies on clause selector variables and\n" + "can not make use of core extraction. To enable\n" + "trace generation use './configure --trace' or\n" + "'./configure -O --trace' when building PicoSAT.\n" +#else + "Since trace generation code is included, this binary\n" + "uses both core extraction and clause selector variables.\n" +#endif + ); + exit (0); + } else if (!strcmp (argv[i], "-v")) verbose++; + else if (output_name) die ("too many arguments"); + else if (!input_name) input_name = argv[i]; + else output_name = argv[i]; + } + if (input_name && strcmp (input_name, "-")) { + len = strlen (input_name); + if (len >= 3 && !strcmp (input_name + len - 3, ".gz")) { + cmd = malloc (len + 20); + sprintf (cmd, "gunzip -c %s 2>/dev/null", input_name); + input_file = popen (cmd, "r"); + pclose_input = 1; + free (cmd); + } else input_file = fopen (input_name, "r"), fclose_input = 1; + if (!input_file) die ("can not read '%s'", input_name); + } else input_file = stdin, input_name = "-"; + if ((err = parse ())) { + fprintf (stderr, "%s:%d: %s\n", input_name, lineno, err); + fflush (stderr); + exit (1); + } + if (fclose_input) fclose (input_file); + if (pclose_input) pclose (input_file); + picosat_init (); + picosat_set_prefix ("c [picosat] "); + picosat_set_output (stderr); + if (verbose > 1) picosat_set_verbosity (verbose - 1); + printed = 0; + if (picosat_enable_trace_generation ()) { + n = nclauses; + nonred = 0; + for (round = 1; round <= MAXCOREROUNDS; round++) { + if (verbose > 1) + msg ("starting core extraction round %d", round); + picosat_set_seed (round); + for (i = 0; i < nclauses; i++) { + c = clauses + i; + if (c->red) { + picosat_add (1); + picosat_add (-1); + } else { + for (p = c->lits; *p; p++) + picosat_add (*p); + } + tmp = picosat_add (0); + assert (tmp == i); + } + res = picosat_sat (-1); + if (res == 10) { assert (round == 1); goto SAT; } + assert (res == 20); + if (!printed) { + assert (round == 1); + printed = 1; + printf ("s UNSATISFIABLE\n"); + fflush (stdout); + } + for (i = 0; i < nclauses; i++) { + c = clauses + i; + if (c->red) { assert (!picosat_coreclause (i)); continue; } + if (picosat_coreclause (i)) continue; + c->red = 1; + } + oldn = n; + n = 0; + for (i = 0; i < nclauses; i++) if (!clauses[i].red) n++; + msg ("extracted core %d of size %d out of %d (%.0f%%) after %.1f sec", + round, n, nclauses, percent (n, nclauses), + picosat_time_stamp () - start); + assert (oldn >= n); + picosat_reset (); + picosat_init (); + picosat_set_prefix ("c [picosat] "); + picosat_set_output (stderr); + if (round >= MINCOREROUNDS) { + red = oldn - n; + if (red < 10 && (100*red + 99)/oldn < 2) { + nonred++; + if (nonred > MAXNONREDROUNDS) break; + } + } + if (round < MAXCOREROUNDS) picosat_enable_trace_generation (); + } + } + for (i = 0; i < nclauses; i++) { + c = clauses + i; + if (c->red) { + picosat_add (1); + picosat_add (-1); + tmp = picosat_add (0); + assert (tmp == i); + continue; + } + c->lit = nvars + i + 1; + picosat_add (-c->lit); + for (p = c->lits; *p; p++) + (void) picosat_add (*p); + tmp = picosat_add (0); + assert (tmp == i); + } + for (i = 0; i < nclauses; i++) { + c = clauses + i; + if (c->red) continue; + picosat_assume (c->lit); + } + res = picosat_sat (-1); + if (res == 20) { + if (!printed) printf ("s UNSATISFIABLE\n"), fflush (stdout); + for (i = 0; i < nclauses; i++) clauses[i].red = 1; + q = picosat_mus_assumptions (0, callback, 1); + while ((i = *q++)) { + i -= nvars + 1; + assert (0 <= i && i < nclauses); + clauses[i].red = 0; + } + } else { +SAT: + assert (res == 10); + printf ("s SATISFIABLE\n"); fflush (stdout); + for (i = 1; i <= nvars; i++) + printf ("v %d\n", ((picosat_deref (i) < 0) ? -1 : 1) * i); + printf ("v 0\n"); + } + if (verbose) picosat_stats (); + picosat_reset (); + n = 0; + for (i = 0; i < nclauses; i++) if (!clauses[i].red) n++; + red = nclauses - n; + msg ("found %d redundant clauses %.0f%%", red, percent (red, nclauses)); + if (output_name && strcmp (output_name, "-")) { + output_file = fopen (output_name, "w"); + if (!output_file) die ("can not write '%s'", output_name); + close_output = 1; + } else if (output_name && !strcmp (output_name, "-")) output_file = stdout; + if (output_file) { + fprintf (output_file, "p cnf %d %d\n", nvars, n); + for (i = 0; i < nclauses; i++) + if (!clauses[i].red) { + for (p = clauses[i].lits; *p; p++) fprintf (output_file, "%d ", *p); + fprintf (output_file, "0\n"); + } + if (close_output) fclose (output_file); + } + msg ("%s %d irredundant clauses %.0f%%", + output_file ? "printed" : "computed", n, percent (n, nclauses)); + for (i = 0; i < nclauses; i++) free (clauses[i].lits); + free (clauses); + free (lits); + msg ("%d reductions in %.1f seconds", + reductions, picosat_time_stamp () - start); + return res; +} diff --git a/src/prop/bvpicosat/picosat.c b/src/prop/bvpicosat/picosat.c new file mode 100644 index 000000000..490d235cc --- /dev/null +++ b/src/prop/bvpicosat/picosat.c @@ -0,0 +1,7731 @@ +/**************************************************************************** +Copyright (c) 2006 - 2010, Armin Biere, Johannes Kepler University. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +****************************************************************************/ + +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <assert.h> +#include <limits.h> +#include <ctype.h> +#include <stdarg.h> + +#include "picosat.h" + +/* By default code for 'all different constraints' is disabled, since 'NADC' + * is defined. +#define NADC + */ + +/* By default we enable failed literals, since 'NFL' is undefined. + * + */ +#define NFL + +/* By default we 'detach satisfied (large) clauses', e.g. NDSC undefined. + * +#define NDSC + */ + +/* Do not use luby restart schedule instead of inner/outer. + * +#define NLUBY + */ + +// #define VISCORES /* keep this disabled */ + +#ifdef VISCORES +// #define WRITEGIF +#endif + +#ifdef VISCORES +#ifndef WRITEGIF +#include <unistd.h> /* for 'usleep' */ +#endif +#endif + +#define MINRESTART 100 /* minimum restart interval */ +#define MAXRESTART 1000000 /* maximum restart interval */ +#define RDECIDE 1000 /* interval of random decisions */ +#define FRESTART 110 /* restart increase factor in percent */ +#define FREDUCE 110 /* reduce increase factor in percent */ +#define FFLIPPED 10000 /* flipped reduce factor */ +#define FFLIPPEDPREC 10000000/* flipped reduce factor precision */ + +#ifndef TRACE +#define NO_BINARY_CLAUSES /* store binary clauses more compactly */ +#endif + +/* For debugging purposes you may want to define 'LOGGING', which actually + * can be enforced by using the '--log' option for the configure script. + */ +#ifdef LOGGING +#define LOG(code) do { code; } while (0) +#else +#define LOG(code) do { } while (0) +#endif +#define NOLOG(code) do { } while (0) /* log exception */ +#define ONLYLOG(code) do { code; } while (0) /* force logging */ + +#define FALSE ((Val)-1) +#define UNDEF ((Val)0) +#define TRUE ((Val)1) + +#define COMPACT_TRACECHECK_TRACE_FMT 0 +#define EXTENDED_TRACECHECK_TRACE_FMT 1 +#define RUP_TRACE_FMT 2 + +#define NEWN(p,n) do { (p) = new (sizeof (*(p)) * (n)); } while (0) +#define CLRN(p,n) do { memset ((p), 0, sizeof (*(p)) * (n)); } while (0) +#define CLR(p) CLRN(p,1) +#define DELETEN(p,n) \ + do { delete (p, sizeof (*(p)) * (n)); (p) = 0; } while (0) + +#define RESIZEN(p,old_num,new_num) \ + do { \ + size_t old_size = sizeof (*(p)) * (old_num); \ + size_t new_size = sizeof (*(p)) * (new_num); \ + (p) = resize ((p), old_size, new_size) ; \ + } while (0) + +#define ENLARGE(start,head,end) \ + do { \ + unsigned old_num = (unsigned)((end) - (start)); \ + size_t new_num = old_num ? (2 * old_num) : 1; \ + unsigned count = (head) - (start); \ + assert ((start) <= (start)); \ + RESIZEN((start),old_num,new_num); \ + (head) = (start) + count; \ + (end) = (start) + new_num; \ + } while (0) + +#define NOTLIT(l) (lits + (1 ^ ((l) - lits))) + +#define LIT2IDX(l) ((unsigned)((l) - lits) / 2) +#define LIT2IMPLS(l) (impls + (unsigned)((l) - lits)) +#define LIT2INT(l) (LIT2SGN(l) * LIT2IDX(l)) +#define LIT2SGN(l) (((unsigned)((l) - lits) & 1) ? -1 : 1) +#define LIT2VAR(l) (vars + LIT2IDX(l)) +#define LIT2HTPS(l) (htps + (unsigned)((l) - lits)) +#define LIT2JWH(l) (jwh + ((l) - lits)) + +#ifndef NDSC +#define LIT2DHTPS(l) (dhtps + (unsigned)((l) - lits)) +#endif + +#ifdef NO_BINARY_CLAUSES +typedef unsigned long Wrd; +#define ISLITREASON(cls) (1&(Wrd)cls) +#define LIT2REASON(lit) \ + (assert (lit->val==TRUE), ((Cls*)(1 + (2*(lit - lits))))) +#define REASON2LIT(cls) ((Lit*)(lits + ((Wrd)cls)/2)) +#endif + +#define ENDOFCLS(c) ((void*)((c)->lits + (c)->size)) + +#define SOC ((oclauses == ohead) ? lclauses : oclauses) +#define EOC lhead +#define NXC(p) (((p) + 1 == ohead) ? lclauses : (p) + 1) + +#define OIDX2IDX(idx) (2 * ((idx) + 1)) +#define LIDX2IDX(idx) (2 * (idx) + 1) + +#define ISLIDX(idx) ((idx)&1) + +#define IDX2OIDX(idx) (assert(!ISLIDX(idx)), (idx)/2 - 1) +#define IDX2LIDX(idx) (assert(ISLIDX(idx)), (idx)/2) + +#define EXPORTIDX(idx) \ + ((ISLIDX(idx) ? (IDX2LIDX (idx) + (ohead - oclauses)) : IDX2OIDX(idx)) + 1) + +#define IDX2CLS(i) \ + (assert(i), (ISLIDX(i) ? lclauses : oclauses)[(i)/2 - !ISLIDX(i)]) + +#define IDX2ZHN(i) (assert(i), (ISLIDX(i) ? zhains[(i)/2] : 0)) + +#define CLS2TRD(c) (((Trd*)(c)) - 1) +#define CLS2IDX(c) ((((Trd*)(c)) - 1)->idx) + +#define CLS2ACT(c) \ + ((Act*)((assert((c)->learned)),assert((c)->size>2),ENDOFCLS(c))) + +#define VAR2LIT(v) (lits + 2 * ((v) - vars)) +#define VAR2RNK(v) (rnks + ((v) - vars)) + +#define RNK2LIT(r) (lits + 2 * ((r) - rnks)) +#define RNK2VAR(r) (vars + ((r) - rnks)) + +#define BLK_FILL_BYTES 8 +#define SIZE_OF_BLK (sizeof (Blk) - BLK_FILL_BYTES) + +#define PTR2BLK(void_ptr) \ + ((void_ptr) ? (Blk*)(((char*)(void_ptr)) - SIZE_OF_BLK) : 0) + +#define AVERAGE(a,b) ((b) ? (((double)a) / (double)(b)) : 0.0) +#define PERCENT(a,b) (100.0 * AVERAGE(a,b)) + +#define ABORT(msg) \ + do { \ + fputs ("*** picosat: " msg "\n", stderr); \ + abort (); \ + } while (0) + +#define ABORTIF(cond,msg) \ + do { \ + if (!(cond)) break; \ + ABORT (msg); \ + } while (0) + +#define ZEROFLT (0x00000000u) +#define INFFLT (0xffffffffu) + +#define FLTCARRY (1u << 25) +#define FLTMSB (1u << 24) +#define FLTMAXMANTISSA (FLTMSB - 1) + +#define FLTMANTISSA(d) ((d) & FLTMAXMANTISSA) +#define FLTEXPONENT(d) ((int)((d) >> 24) - 128) + +#define FLTMINEXPONENT (-128) +#define FLTMAXEXPONENT (127) + +#define cmpswapflt(a,b) \ + do { \ + Flt tmp; \ + if (((a) < (b))) \ + { \ + tmp = (a); \ + (a) = (b); \ + (b) = tmp; \ + } \ + } while (0) + +#define unpackflt(u,m,e) \ + do { \ + (m) = FLTMANTISSA(u); \ + (e) = FLTEXPONENT(u); \ + (m) |= FLTMSB; \ + } while (0) + +#define INSERTION_SORT_LIMIT 10 + +#define internal_sorting_swap(T,p,q) \ +do { \ + T tmp = *(q); \ + *(q) = *(p); \ + *(p) = tmp; \ +} while (0) + +#define internal_sorting_cmpswap(T,cmp,p,q) \ +do { \ + if ((cmp) (*(p), *(q)) > 0) \ + internal_sorting_swap (T, p, q); \ +} while(0) + +#define internal_quicksort_partition(T,cmp,a,l,r) \ +do { \ + T pivot; \ + int j; \ + i = (l) - 1; /* result in 'i' */ \ + j = (r); \ + pivot = (a)[j]; \ + for (;;) \ + { \ + while ((cmp) ((a)[++i], pivot) < 0) \ + ; \ + while ((cmp) (pivot, (a)[--j]) < 0) \ + if (j == (l)) \ + break; \ + if (i >= j) \ + break; \ + internal_sorting_swap (T, (a) + i, (a) + j); \ + } \ + internal_sorting_swap (T, (a) + i, (a) + (r)); \ +} while(0) + +#define internal_quicksort(T,cmp,a,n) \ +do { \ + int l = 0, r = (n) - 1, m, ll, rr, i; \ + assert (ihead == indices); \ + if (r - l <= INSERTION_SORT_LIMIT) \ + break; \ + for (;;) \ + { \ + m = (l + r) / 2; \ + internal_sorting_swap (T, (a) + m, (a) + r - 1); \ + internal_sorting_cmpswap (T, cmp, (a) + l, (a) + r - 1); \ + internal_sorting_cmpswap (T, cmp, (a) + l, (a) + r); \ + internal_sorting_cmpswap (T, cmp, (a) + r - 1, (a) + r); \ + internal_quicksort_partition (T, cmp, (a), l + 1, r - 1); \ + if (i - l < r - i) \ + { \ + ll = i + 1; \ + rr = r; \ + r = i - 1; \ + } \ + else \ + { \ + ll = l; \ + rr = i - 1; \ + l = i + 1; \ + } \ + if (r - l > INSERTION_SORT_LIMIT) \ + { \ + assert (rr - ll > INSERTION_SORT_LIMIT); \ + if (ihead == eoi) \ + ENLARGE (indices, ihead, eoi); \ + *ihead++ = ll; \ + if (ihead == eoi) \ + ENLARGE (indices, ihead, eoi); \ + *ihead++ = rr; \ + } \ + else if (rr - ll > INSERTION_SORT_LIMIT) \ + { \ + l = ll; \ + r = rr; \ + } \ + else if (ihead > indices) \ + { \ + r = *--ihead; \ + l = *--ihead; \ + } \ + else \ + break; \ + } \ +} while (0) + +#define internal_insertion_sort(T,cmp,a,n) \ +do { \ + T pivot; \ + int l = 0, r = (n) - 1, i, j; \ + for (i = r; i > l; i--) \ + internal_sorting_cmpswap (T, cmp, (a) + i - 1, (a) + i); \ + for (i = l + 2; i <= r; i++) \ + { \ + j = i; \ + pivot = (a)[i]; \ + while ((cmp) (pivot, (a)[j - 1]) < 0) \ + { \ + (a)[j] = (a)[j - 1]; \ + j--; \ + } \ + (a)[j] = pivot; \ + } \ +} while (0) + +#ifdef NDEBUG +#define check_sorted(cmp,a,n) do { } while(0) +#else +#define check_sorted(cmp,a,n) \ +do { \ + int i; \ + for (i = 0; i < (n) - 1; i++) \ + assert ((cmp) ((a)[i], (a)[i + 1]) <= 0); \ +} while(0) +#endif + +#define sort(T,cmp,a,n) \ +do { \ + T * aa = (a); \ + int nn = (n); \ + internal_quicksort (T, cmp, aa, nn); \ + internal_insertion_sort (T, cmp, aa, nn); \ + assert (ihead == indices); \ + check_sorted (cmp, aa, nn); \ +} while (0) + +#define WRDSZ (sizeof (long) * 8) + +typedef unsigned Flt; /* 32 bit deterministic soft float */ +typedef Flt Act; /* clause and variable activity */ +typedef struct Blk Blk; /* allocated memory block */ +typedef struct Cls Cls; /* clause */ +typedef struct Lit Lit; /* literal */ +typedef struct Rnk Rnk; /* variable to score mapping */ +typedef signed char Val; /* TRUE, UNDEF, FALSE */ +typedef struct Var Var; /* variable */ +#ifdef TRACE +typedef struct Trd Trd; /* trace data for clauses */ +typedef struct Zhn Zhn; /* compressed chain (=zain) data */ +typedef unsigned char Znt; /* compressed antecedent data */ +#endif + +#ifdef NO_BINARY_CLAUSES +typedef struct Ltk Ltk; + +struct Ltk +{ + Lit ** start; + unsigned count : WRDSZ == 32 ? 27 : 32; + unsigned ldsize : WRDSZ == 32 ? 5 : 32; +}; +#endif + +struct Lit +{ + Val val; +}; + +struct Var +{ + unsigned mark : 1; + unsigned resolved : 1; + unsigned phase : 1; + unsigned assigned : 1; + unsigned used : 1; + unsigned failed : 1; +#ifdef TRACE + unsigned core : 1; +#endif + unsigned level : WRDSZ == 32 ? 24 : 32; + Cls *reason; +#ifndef NADC + Lit ** inado; + Lit ** ado; + Lit *** adotabpos; +#endif +}; + +struct Rnk +{ + Act score; + unsigned pos : 30; /* 0 iff not on heap */ + unsigned moreimportant : 1; + unsigned lessimportant : 1; +}; + +struct Cls +{ + unsigned size; + unsigned learned:1; + unsigned collect:1; + unsigned locked:1; + unsigned fixed:1; + unsigned used:1; +#ifndef NDEBUG + unsigned connected:1; +#endif +#ifdef TRACE + unsigned core:1; + unsigned collected:1; +#endif + Cls *next[2]; + Lit *lits[2]; +}; + +#ifdef TRACE +struct Zhn +{ + unsigned ref:31; + unsigned core:1; + Znt * liz; + Znt znt[0]; +}; + +struct Trd +{ + unsigned idx; + Cls cls[0]; +}; +#endif + +struct Blk +{ +#ifndef NDEBUG + union + { + size_t size; /* this is what we really use */ + void *as_two_ptrs[2]; /* 2 * sizeof (void*) alignment of data */ + } + header; +#endif + char data[BLK_FILL_BYTES]; +}; + +static enum State +{ + RESET = 0, + READY = 1, + SAT = 2, + UNSAT = 3, + UNKNOWN = 4, +} +state = RESET; + +static int last_sat_call_result; + +static FILE *out; +static char * prefix; +static int verbosity; +static unsigned level; +static unsigned max_var; +static unsigned size_vars; + +static Lit * __attribute__((aligned(64))) lits; +static Var *vars; +static Rnk *rnks; +static Flt *jwh; +static Cls **htps; +#ifndef NDSC +static Cls **dhtps; +#endif +#ifdef NO_BINARY_CLAUSES +static Ltk *impls; +static Cls impl, cimpl; +static int implvalid, cimplvalid; +#else +static Cls **impls; +#endif +static Lit **trail, **thead, **eot, **ttail, ** ttail2; +#ifndef NADC +static Lit **ttailado; +#endif +static unsigned adecidelevel; +static Lit **als, **alshead, **alstail, **eoals; +static int *fals, *falshead, *eofals; +static int *mass, szmass; +static Lit *failed_assumption; +static int extracted_all_failed_assumptions; +static Rnk **heap, **hhead, **eoh; +static Cls **oclauses, **ohead, **eoo; /* original clauses */ +static Cls **lclauses, **lhead, ** eol; /* learned clauses */ +#ifdef TRACE +static int trace; +static Zhn **zhains, **zhead, **eoz; +static int ocore = -1; +#endif +static FILE * rup; +static int rupstarted; +static int rupvariables; +static int rupclauses; +static Cls *mtcls; +static Cls *conflict; +static Lit **added, **ahead, **eoa; +static Var **marked, **mhead, **eom; +static Var **dfs, **dhead, **eod; +static Cls **resolved, **rhead, **eor; +static unsigned char *buffer, *bhead, *eob; +static Act vinc, lscore, ilvinc, ifvinc; +#ifdef VISCORES +static Act fvinc, nvinc; +#endif +static Act cinc, lcinc, ilcinc, fcinc; +static unsigned srng; +static size_t current_bytes; +static size_t max_bytes; +static size_t recycled; +static double seconds; +static double entered; +static unsigned nentered; +static int measurealltimeinlib; +static char *rline[2]; +static int szrline, rcount; +static double levelsum; +static unsigned iterations; +static int reports; +static int lastrheader = -2; +static unsigned calls; +static unsigned decisions; +static unsigned restarts; +static unsigned simps; +static unsigned fsimplify; +static unsigned isimplify; +static unsigned reductions; +static unsigned lreduce; +static unsigned lreduceadjustcnt; +static unsigned lreduceadjustinc; +static unsigned lastreduceconflicts; +static unsigned llocked; /* locked large learned clauses */ +static unsigned lrestart; +#ifdef NLUBY +static unsigned drestart; +static unsigned ddrestart; +#else +static unsigned lubycnt; +static unsigned lubymaxdelta; +static int waslubymaxdelta; +#endif +static unsigned long long lsimplify; +static unsigned long long propagations; +static unsigned long long lpropagations; +static unsigned fixed; /* top level assignments */ +#ifndef NFL +static unsigned failedlits; +static unsigned ifailedlits; +static unsigned efailedlits; +static unsigned flcalls; +#ifdef STATS +static unsigned flrounds; +static unsigned long long flprops; +static unsigned long long floopsed, fltried, flskipped; +#endif +static unsigned long long fllimit; +static int simplifying; +static Lit ** saved; +static unsigned saved_size; +#endif +static unsigned conflicts; +static unsigned noclauses; /* current number large original clauses */ +static unsigned nlclauses; /* current number large learned clauses */ +static unsigned olits; /* current literals in large original clauses */ +static unsigned llits; /* current literals in large learned clauses */ +static unsigned oadded; /* added original clauses */ +static unsigned ladded; /* added learned clauses */ +static unsigned loadded; /* added original large clauses */ +static unsigned lladded; /* added learned large clauses */ +static unsigned addedclauses; /* oadded + ladded */ +static unsigned vused; /* used variables */ +static unsigned llitsadded; /* added learned literals */ +#ifdef STATS +static unsigned loused; /* used large original clauses */ +static unsigned llused; /* used large learned clauses */ +static unsigned long long visits; +static unsigned long long bvisits; +static unsigned long long tvisits; +static unsigned long long lvisits; +static unsigned long long othertrue; +static unsigned long long othertrue2; +static unsigned long long othertruel; +static unsigned long long othertrue2u; +static unsigned long long othertruelu; +static unsigned long long ltraversals; +static unsigned long long traversals; +#ifdef TRACE +static unsigned long long antecedents; +#endif +static unsigned uips; +static unsigned znts; +static unsigned assumptions; +static unsigned rdecisions; +static unsigned sdecisions; +static size_t srecycled; +static size_t rrecycled; +static unsigned long long derefs; +#endif +static unsigned minimizedllits; +static unsigned nonminimizedllits; +#ifndef NADC +static Lit *** ados, *** hados, *** eados; +static Lit *** adotab; +static unsigned nadotab; +static unsigned szadotab; +static Cls * adoconflict; +static unsigned adoconflicts; +static unsigned adoconflictlimit = UINT_MAX; +static int addingtoado; +static int adodisabled; +#endif +static unsigned long long flips; +#ifdef STATS +static unsigned long long forced; +static unsigned long long assignments; +static unsigned inclreduces; +static unsigned staticphasedecisions; +static unsigned skippedrestarts; +#endif +static int * indices, * ihead, *eoi; +static unsigned sdflips; +static int defaultphase; + +static unsigned long long saved_flips; +static unsigned saved_max_var; +static unsigned min_flipped = UINT_MAX; + +static void * emgr; +static void * (*enew)(void*,size_t); +static void * (*eresize)(void*,void*,size_t,size_t); +static void (*edelete)(void*,void*,size_t); + +#ifdef VISCORES +static FILE * fviscores; +#endif + +static Flt +packflt (unsigned m, int e) +{ + Flt res; + assert (m < FLTMSB); + assert (FLTMINEXPONENT <= e); + assert (e <= FLTMAXEXPONENT); + res = m | ((e + 128) << 24); + return res; +} + +static Flt +base2flt (unsigned m, int e) +{ + if (!m) + return ZEROFLT; + + if (m < FLTMSB) + { + do + { + if (e <= FLTMINEXPONENT) + return ZEROFLT; + + e--; + m <<= 1; + + } + while (m < FLTMSB); + } + else + { + while (m >= FLTCARRY) + { + if (e >= FLTMAXEXPONENT) + return INFFLT; + + e++; + m >>= 1; + } + } + + m &= ~FLTMSB; + return packflt (m, e); +} + +static Flt +addflt (Flt a, Flt b) +{ + unsigned ma, mb, delta; + int ea, eb; + + cmpswapflt (a, b); + if (!b) + return a; + + unpackflt (a, ma, ea); + unpackflt (b, mb, eb); + + assert (ea >= eb); + delta = ea - eb; + mb >>= delta; + if (!mb) + return a; + + ma += mb; + if (ma & FLTCARRY) + { + if (ea == FLTMAXEXPONENT) + return INFFLT; + + ea++; + ma >>= 1; + } + + assert (ma < FLTCARRY); + ma &= FLTMAXMANTISSA; + + return packflt (ma, ea); +} + +static Flt +mulflt (Flt a, Flt b) +{ + unsigned ma, mb; + unsigned long long accu; + int ea, eb; + + cmpswapflt (a, b); + if (!b) + return ZEROFLT; + + unpackflt (a, ma, ea); + unpackflt (b, mb, eb); + + ea += eb; + ea += 24; + if (ea > FLTMAXEXPONENT) + return INFFLT; + + if (ea < FLTMINEXPONENT) + return ZEROFLT; + + accu = ma; + accu *= mb; + accu >>= 24; + + if (accu >= FLTCARRY) + { + if (ea == FLTMAXEXPONENT) + return INFFLT; + + ea++; + accu >>= 1; + + if (accu >= FLTCARRY) + return INFFLT; + } + + assert (accu < FLTCARRY); + assert (accu & FLTMSB); + + ma = accu; + ma &= ~FLTMSB; + + return packflt (ma, ea); +} + +static int +ISDIGIT (char c) +{ + return '0' <= c && c <= '9'; +} + +static Flt +ascii2flt (const char *str) +{ + Flt ten = base2flt (10, 0); + Flt onetenth = base2flt (26843546, -28); + Flt res = ZEROFLT, tmp, base; + const char *p = str; + char ch; + + ch = *p++; + + if (ch != '.') + { + if (!ISDIGIT (ch)) + return INFFLT; /* better abort ? */ + + res = base2flt (ch - '0', 0); + + while ((ch = *p++)) + { + if (ch == '.') + break; + + if (!ISDIGIT (ch)) + return INFFLT; /* better abort? */ + + res = mulflt (res, ten); + tmp = base2flt (ch - '0', 0); + res = addflt (res, tmp); + } + } + + if (ch == '.') + { + ch = *p++; + if (!ISDIGIT (ch)) + return INFFLT; /* better abort ? */ + + base = onetenth; + tmp = mulflt (base2flt (ch - '0', 0), base); + res = addflt (res, tmp); + + while ((ch = *p++)) + { + if (!ISDIGIT (ch)) + return INFFLT; /* better abort? */ + + base = mulflt (base, onetenth); + tmp = mulflt (base2flt (ch - '0', 0), base); + res = addflt (res, tmp); + } + } + + return res; +} + +#if defined(VISCORES) + +static double +flt2double (Flt f) +{ + double res; + unsigned m; + int e, i; + + unpackflt (f, m, e); + res = m; + + if (e < 0) + { + for (i = e; i < 0; i++) + res *= 0.5; + } + else + { + for (i = 0; i < e; i++) + res *= 2.0; + } + + return res; +} + +#endif + +static int +log2flt (Flt a) +{ + return FLTEXPONENT (a) + 24; +} + +static int +cmpflt (Flt a, Flt b) +{ + if (a < b) + return -1; + + if (a > b) + return 1; + + return 0; +} + +static void * +new (size_t size) +{ + size_t bytes; + Blk *b; + + if (!size) + return 0; + + bytes = size + SIZE_OF_BLK; + + if (enew) + b = enew (emgr, bytes); + else + b = malloc (bytes); + + ABORTIF (!b, "out of memory in 'new'"); +#ifndef NDEBUG + b->header.size = size; +#endif + current_bytes += size; + if (current_bytes > max_bytes) + max_bytes = current_bytes; + return b->data; +} + +static void +delete (void *void_ptr, size_t size) +{ + size_t bytes; + Blk *b; + + if (!void_ptr) + { + assert (!size); + return; + } + + assert (size); + b = PTR2BLK (void_ptr); + + assert (size <= current_bytes); + current_bytes -= size; + + assert (b->header.size == size); + + bytes = size + SIZE_OF_BLK; + if (edelete) + edelete (emgr, b, bytes); + else + free (b); +} + +static void * +resize (void *void_ptr, size_t old_size, size_t new_size) +{ + size_t old_bytes, new_bytes; + Blk *b; + + b = PTR2BLK (void_ptr); + + assert (old_size <= current_bytes); + current_bytes -= old_size; + + if ((old_bytes = old_size)) + { + assert (old_size && b->header.size == old_size); + old_bytes += SIZE_OF_BLK; + } + else + assert (!b); + + if ((new_bytes = new_size)) + new_bytes += SIZE_OF_BLK; + + if (eresize) + b = eresize (emgr, b, old_bytes, new_bytes); + else + b = realloc (b, new_bytes); + + if (!new_size) + { + assert (!b); + return 0; + } + + ABORTIF (!b, "out of memory in 'resize'"); +#ifndef NDEBUG + b->header.size = new_size; +#endif + + current_bytes += new_size; + if (current_bytes > max_bytes) + max_bytes = current_bytes; + + return b->data; +} + +static unsigned +int2unsigned (int l) +{ + return (l < 0) ? 1 + 2 * -l : 2 * l; +} + +static Lit * +int2lit (int l) +{ + return lits + int2unsigned (l); +} + +static Lit ** +end_of_lits (Cls * cls) +{ + return cls->lits + cls->size; +} + +static int +lit2idx (Lit * lit) +{ + return (lit - lits) / 2; +} + +static int +lit2sign (Lit * lit) +{ + return ((lit - lits) & 1) ? -1 : 1; +} + + +static int +lit2int (Lit * l) +{ + return lit2idx (l) * lit2sign (l); +} + +#if !defined(NDEBUG) || defined(LOGGING) + +static void +dumplits (Lit ** lits, Lit ** eol) +{ + int first; + Lit ** p; + + if (lits == eol) + { + /* empty clause */ + } + else if (lits + 1 == eol) + { + fprintf (out, "%d ", lit2int (lits[0])); + } + else + { + assert (lits + 2 <= eol); + first = (abs (lit2int (lits[0])) > abs (lit2int (lits[1]))); + fprintf (out, "%d ", lit2int (lits[first])); + fprintf (out, "%d ", lit2int (lits[!first])); + for (p = lits + 2; p < eol; p++) + fprintf (out, "%d ", lit2int (*p)); + } + + fputc ('0', out); +} + +static void +dumpcls (Cls * cls) +{ + Lit **eol; + + if (cls) + { + eol = end_of_lits (cls); + dumplits (cls->lits, eol); +#ifdef TRACE + if (trace) + fprintf (out, " clause(%u)", CLS2IDX (cls)); +#endif + } + else + fputs ("DECISION", out); +} + +static void +dumpclsnl (Cls * cls) +{ + dumpcls (cls); + fputc ('\n', out); +} + +void +dumpcnf (void) +{ + Cls **p, *cls; + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + + dumpclsnl (*p); + } +} + +#endif + +static void +delete_prefix (void) +{ + if (!prefix) + return; + + delete (prefix, strlen (prefix) + 1); + prefix = 0; +} + +static void +new_prefix (const char * str) +{ + delete_prefix (); + assert (str); + prefix = new (strlen (str) + 1); + strcpy (prefix, str); +} + +static void +init (void) +{ + static int count; + + ABORTIF (state != RESET, "API usage: multiple initializations"); + + count = 3 - !enew - !eresize - !edelete; + ABORTIF (count && !enew, "API usage: missing 'picosat_set_new'"); + ABORTIF (count && !eresize, "API usage: missing 'picosat_set_resize'"); + ABORTIF (count && !edelete, "API usage: missing 'picosat_set_delete'"); + + assert (!max_var); /* check for proper reset */ + assert (!size_vars); /* check for proper reset */ + + size_vars = 1; + + NEWN (lits, 2 * size_vars); + NEWN (jwh, 2 * size_vars); + NEWN (htps, 2 * size_vars); +#ifndef NDSC + NEWN (dhtps, 2 * size_vars); +#endif + NEWN (impls, 2 * size_vars); + NEWN (vars, size_vars); + NEWN (rnks, size_vars); + + ENLARGE (heap, hhead, eoh); /* because '0' pos denotes not on heap */ + hhead = heap + 1; + + vinc = base2flt (1, 0); /* initial variable activity */ + ifvinc = ascii2flt ("1.05"); /* variable score rescore factor */ +#ifdef VISCORES + fvinc = ascii2flt ("0.9523809"); /* 1/f = 1/1.1 */ + nvinc = ascii2flt ("0.0476191"); /* 1 - 1/f = 1 - 1/1.1 */ +#endif + lscore = base2flt (1, 90); /* variable activity rescore limit */ + ilvinc = base2flt (1, -90); /* inverse of 'lscore' */ + + cinc = base2flt (1, 0); /* initial clause activity */ + fcinc = ascii2flt ("1.001"); /* clause activity rescore factor */ + lcinc = base2flt (1, 90); /* clause activity rescore limit */ + ilcinc = base2flt (1, -90); /* inverse of 'ilcinc' */ + + lreduceadjustcnt = lreduceadjustinc = 100; + lpropagations = ~0ull; + + out = stdout; + new_prefix ("c "); + verbosity = 0; + +#ifdef NO_BINARY_CLAUSES + memset (&impl, 0, sizeof (impl)); + impl.size = 2; + + memset (&cimpl, 0, sizeof (impl)); + cimpl.size = 2; +#endif + +#ifdef VISCORES + fviscores = popen ( + "/usr/bin/gnuplot -background black" + " -xrm 'gnuplot*textColor:white'" + " -xrm 'gnuplot*borderColor:white'" + " -xrm 'gnuplot*axisColor:white'" + , "w"); + fprintf (fviscores, "unset key\n"); + // fprintf (fviscores, "set log y\n"); + fflush (fviscores); + system ("rm -rf /tmp/picosat-viscores"); + system ("mkdir /tmp/picosat-viscores"); + system ("mkdir /tmp/picosat-viscores/data"); +#ifdef WRITEGIF + system ("mkdir /tmp/picosat-viscores/gif"); + fprintf (fviscores, + "set terminal gif giant animate opt size 1024,768 x000000 xffffff" + "\n"); + + fprintf (fviscores, + "set output \"/tmp/picosat-viscores/gif/animated.gif\"\n"); +#endif +#endif + defaultphase = 2; + state = READY; + last_sat_call_result = 0; +} + +static size_t +bytes_clause (unsigned size, unsigned learned) +{ + size_t res; + + res = sizeof (Cls); + res += size * sizeof (Lit *); + res -= 2 * sizeof (Lit *); + + if (learned && size > 2) + res += sizeof (Act); /* add activity */ + +#ifdef TRACE + if (trace) + res += sizeof (Trd); /* add trace data */ +#endif + + return res; +} + +static Cls * +new_clause (unsigned size, unsigned learned) +{ + size_t bytes; + void * tmp; +#ifdef TRACE + Trd *trd; +#endif + Cls *res; + + bytes = bytes_clause (size, learned); + tmp = new (bytes); + +#ifdef TRACE + if (trace) + { + trd = tmp; + + if (learned) + trd->idx = LIDX2IDX (lhead - lclauses); + else + trd->idx = OIDX2IDX (ohead - oclauses); + + res = trd->cls; + } + else +#endif + res = tmp; + + res->size = size; + res->learned = learned; + + res->collect = 0; +#ifndef NDEBUG + res->connected = 0; +#endif + res->locked = 0; + res->fixed = 0; + res->used = 0; +#ifdef TRACE + res->core = 0; +#ifndef NDEBUG + res->collected = 0; +#endif +#endif + + if (learned && size > 2) + *CLS2ACT (res) = cinc; + + return res; +} + +static void +delete_clause (Cls * cls) +{ + size_t bytes; +#ifdef TRACE + Trd *trd; +#endif + + bytes = bytes_clause (cls->size, cls->learned); + +#ifdef TRACE + if (trace) + { + trd = CLS2TRD (cls); + delete (trd, bytes); + } + else +#endif + delete (cls, bytes); +} + +static void +delete_clauses (void) +{ + Cls **p; + for (p = SOC; p != EOC; p = NXC (p)) + if (*p) + delete_clause (*p); + + DELETEN (oclauses, eoo - oclauses); + DELETEN (lclauses, eol - lclauses); + + ohead = eoo = lhead = eol = 0; +} + +#ifdef TRACE + +static void +delete_zhain (Zhn * zhain) +{ + const Znt *p, *znt; + + assert (zhain); + + znt = zhain->znt; + for (p = znt; *p; p++) + ; + + delete (zhain, sizeof (Zhn) + (p - znt) + 1); +} + +static void +delete_zhains (void) +{ + Zhn **p, *z; + for (p = zhains; p < zhead; p++) + if ((z = *p)) + delete_zhain (z); + + DELETEN (zhains, eoz - zhains); + eoz = zhead = 0; +} + +#endif + +#ifdef NO_BINARY_CLAUSES +static void +lrelease (Ltk * stk) +{ + if (stk->start) + DELETEN (stk->start, (1 << (stk->ldsize))); + memset (stk, 0, sizeof (*stk)); +} +#endif + +#ifndef NADC + +static unsigned +llength (Lit ** a) +{ + Lit ** p; + for (p = a; *p; p++) + ; + return p - a; +} + +static void +resetadoconflict (void) +{ + assert (adoconflict); + delete_clause (adoconflict); + adoconflict = 0; +} + +static void +reset_ados (void) +{ + Lit *** p; + + for (p = ados; p < hados; p++) + DELETEN (*p, llength (*p) + 1); + + DELETEN (ados, eados - ados); + hados = eados = 0; + + DELETEN (adotab, szadotab); + szadotab = nadotab = 0; + + if (adoconflict) + resetadoconflict (); + + adoconflicts = 0; + adoconflictlimit = UINT_MAX; + adodisabled = 0; +} + +#endif + +static void +reset (void) +{ + ABORTIF (state == RESET, "API usage: reset without initialization"); + + delete_clauses (); +#ifdef TRACE + delete_zhains (); +#endif +#ifdef NO_BINARY_CLAUSES + implvalid = 0; + cimplvalid = 0; + { + unsigned i; + for (i = 2; i <= 2 * max_var + 1; i++) + lrelease (impls + i); + } +#endif +#ifndef NADC + reset_ados (); +#endif +#ifndef NFL + DELETEN (saved, saved_size); + saved_size = 0; +#endif + DELETEN (htps, 2 * size_vars); +#ifndef NDSC + DELETEN (dhtps, 2 * size_vars); +#endif + DELETEN (impls, 2 * size_vars); + DELETEN (lits, 2 * size_vars); + DELETEN (jwh, 2 * size_vars); + DELETEN (vars, size_vars); + DELETEN (rnks, size_vars); + + DELETEN (trail, eot - trail); + trail = ttail = ttail2 = thead = eot = 0; +#ifndef NADC + ttailado = 0; +#endif + + DELETEN (heap, eoh - heap); + heap = hhead = eoh = 0; + + DELETEN (als, eoals - als); + als = eoals = alshead = alstail = 0; + extracted_all_failed_assumptions = 0; + failed_assumption = 0; + adecidelevel = 0; + DELETEN (fals, eofals - fals); + fals = eofals = falshead = 0; + DELETEN (mass, szmass); + szmass = 0; + mass = 0; + + size_vars = 0; + max_var = 0; + + mtcls = 0; +#ifdef TRACE + ocore = -1; +#endif + conflict = 0; + + DELETEN (added, eoa - added); + eoa = ahead = 0; + + DELETEN (marked, eom - marked); + eom = mhead = 0; + + DELETEN (dfs, eod - dfs); + eod = dhead = 0; + + DELETEN (resolved, eor - resolved); + eor = rhead = 0; + + DELETEN (buffer, eob - buffer); + eob = bhead = 0; + + DELETEN (indices, eoi - indices); + eoi = ihead = 0; + + delete_prefix (); + + delete (rline[0], szrline); + delete (rline[1], szrline); + rline[0] = rline[1] = 0; + szrline = rcount = 0; + assert (getenv ("LEAK") || !current_bytes); /* found leak if failing */ + max_bytes = 0; + recycled = 0; + current_bytes = 0; + + lrestart = 0; + lreduce = 0; + lastreduceconflicts = 0; + llocked = 0; + lsimplify = 0; + fsimplify = 0; + + seconds = 0; + entered = 0; + nentered = 0; + measurealltimeinlib = 0; + + levelsum = 0.0; + calls = 0; + decisions = 0; + restarts = 0; + simps = 0; + iterations = 0; + reports = 0; + lastrheader = -2; + fixed = 0; +#ifndef NFL + failedlits = 0; + simplifying = 0; + fllimit = 0; +#ifdef STATS + efailedlits = ifailedlits = 0; + fltried = flskipped = floopsed = 0; + flcalls = flrounds = 0; + flprops = 0; +#endif +#endif + propagations = 0; + conflicts = 0; + noclauses = 0; + oadded = 0; + lladded = 0; + loadded = 0; + olits = 0; + nlclauses = 0; + ladded = 0; + addedclauses = 0; + llits = 0; + out = 0; +#ifdef TRACE + trace = 0; +#endif + rup = 0; + rupstarted = 0; + rupclauses = 0; + rupvariables = 0; + level = 0; + + reductions = 0; + + vused = 0; + llitsadded = 0; +#ifdef STATS + loused = 0; + llused = 0; + visits = 0; + bvisits = 0; + tvisits = 0; + lvisits = 0; + othertrue = 0; + othertrue2 = 0; + othertruel = 0; + othertrue2u = 0; + othertruelu = 0; + ltraversals = 0; + traversals = 0; +#ifndef NO_BINARY_CLAUSES + antecedents = 0; +#endif + znts = 0; + uips = 0; + assumptions = 0; + rdecisions = 0; + sdecisions = 0; + srecycled = 0; + rrecycled = 0; +#endif + minimizedllits = 0; + nonminimizedllits = 0; + state = RESET; + srng = 0; + + saved_flips = 0; + saved_max_var = 0; + min_flipped = UINT_MAX; + + flips = 0; +#ifdef STATS + forced = 0; + assignments = 0; +#endif + + sdflips = 0; + defaultphase = 2; + +#ifdef STATS + staticphasedecisions = 0; + inclreduces = 0; + skippedrestarts = 0; +#endif + + emgr = 0; + enew = 0; + eresize = 0; + edelete = 0; +#ifdef VISCORES + pclose (fviscores); + fviscores = 0; +#endif +} + +inline static void +tpush (Lit * lit) +{ + assert (lits < lit && lit <= lits + 2* max_var + 1); + if (thead == eot) + { + unsigned ttail2count = ttail2 - trail; + unsigned ttailcount = ttail - trail; +#ifndef NADC + unsigned ttailadocount = ttailado - trail; +#endif + ENLARGE (trail, thead, eot); + ttail = trail + ttailcount; + ttail2 = trail + ttail2count; +#ifndef NADC + ttailado = trail + ttailadocount; +#endif + } + + *thead++ = lit; +} + +static void +assign_reason (Var * v, Cls * reason) +{ +#ifdef NO_BINARY_CLAUSES + assert (reason != &impl); +#endif + v->reason = reason; +} + +static void +assign_phase (Lit * lit) +{ + unsigned new_phase, idx; + Var * v = LIT2VAR (lit); + +#ifndef NFL + /* In 'simplifying' mode we only need to keep 'min_flipped' up to date if + * we force assignments on the top level. The other assignments will be + * undone and thus we can keep the old saved value of the phase. + */ + if (!level || !simplifying) +#endif + { + new_phase = (LIT2SGN (lit) > 0); + + if (v->assigned) + { + sdflips -= sdflips/FFLIPPED; + + if (new_phase != v->phase) + { + assert (FFLIPPEDPREC >= FFLIPPED); + sdflips += FFLIPPEDPREC / FFLIPPED; + flips++; + + idx = lit2idx (lit); + if (idx < min_flipped) + min_flipped = idx; + + NOLOG (fprintf (out, "%sflipped %d\n", prefix, lit2int (lit))); + } + } + + v->phase = new_phase; + v->assigned = 1; + } + + lit->val = TRUE; + NOTLIT (lit)->val = FALSE; +} + +inline static void +assign (Lit * lit, Cls * reason) +{ + Var * v = LIT2VAR (lit); + assert (lit->val == UNDEF); +#ifdef STATS + assignments++; +#endif + v->level = level; + assign_phase (lit); + assign_reason (v, reason); + tpush (lit); +} + +inline static int +cmp_added (Lit * k, Lit * l) +{ + Val a = k->val, b = l->val; + Var *u, *v; + int res; + + if (a == UNDEF && b != UNDEF) + return -1; + + if (a != UNDEF && b == UNDEF) + return 1; + + u = LIT2VAR (k); + v = LIT2VAR (l); + + if (a != UNDEF) + { + assert (b != UNDEF); + res = v->level - u->level; + if (res) + return res; /* larger level first */ + } + + res = cmpflt (VAR2RNK (v)->score, VAR2RNK (u)->score); + if (res) + return res; /* larger activity first */ + + return u - v; /* smaller index first */ +} + +static void +sorttwolits (Lit ** v) +{ + Lit * a = v[0], * b = v[1]; + + assert (a != b); + + if (a < b) + return; + + v[0] = b; + v[1] = a; +} + +inline static void +sortlits (Lit ** v, unsigned size) +{ + if (size == 2) + sorttwolits (v); /* same order with and with out 'NO_BINARY_CLAUSES' */ + else + sort (Lit *, cmp_added, v, size); +} + +#ifdef NO_BINARY_CLAUSES +static Cls * +setimpl (Lit * a, Lit * b) +{ + assert (!implvalid); + assert (impl.size == 2); + + impl.lits[0] = a; + impl.lits[1] = b; + + sorttwolits (impl.lits); + implvalid = 1; + + return &impl; +} + +static void +resetimpl (void) +{ + assert (implvalid); + implvalid = 0; +} + +static Cls * +setcimpl (Lit * a, Lit * b) +{ + assert (!cimplvalid); + assert (cimpl.size == 2); + + cimpl.lits[0] = a; + cimpl.lits[1] = b; + + sorttwolits (cimpl.lits); + cimplvalid = 1; + + return &cimpl; +} + +static void +resetcimpl (void) +{ + assert (cimplvalid); + cimplvalid = 0; +} + +#endif + +static int +cmp_ptr (void *l, void *k) +{ + return ((char*)l) - (char*)k; /* arbitrarily already reverse */ +} + +static int +cmp_rnk (Rnk * r, Rnk * s) +{ + if (!r->moreimportant && s->moreimportant) + return -1; + + if (r->moreimportant && !s->moreimportant) + return 1; + + if (!r->lessimportant && s->lessimportant) + return 1; + + if (r->lessimportant && !s->lessimportant) + return -1; + + if (r->score < s->score) + return -1; + + if (r->score > s->score) + return 1; + + return -cmp_ptr (r, s); +} + +static void +hup (Rnk * v) +{ + int upos, vpos; + Rnk *u; + +#ifndef NFL + assert (!simplifying); +#endif + + vpos = v->pos; + + assert (0 < vpos); + assert (vpos < hhead - heap); + assert (heap[vpos] == v); + + while (vpos > 1) + { + upos = vpos / 2; + + u = heap[upos]; + + if (cmp_rnk (u, v) > 0) + break; + + heap[vpos] = u; + u->pos = vpos; + + vpos = upos; + } + + heap[vpos] = v; + v->pos = vpos; +} + +static Cls *add_simplified_clause (int learned); + +inline static void +add_antecedent (Cls * c) +{ + assert (c); + +#ifdef NO_BINARY_CLAUSES + if (ISLITREASON (c)) + return; + + if (c == &impl) + return; +#else +#ifdef STATS + antecedents++; +#endif +#endif + if (rhead == eor) + ENLARGE (resolved, rhead, eor); + + assert (rhead < eor); + *rhead++ = c; +} + +#ifdef TRACE + +#ifdef NO_BINARY_CLAUSES +#error "can not combine TRACE and NO_BINARY_CLAUSES" +#endif + +#endif /* TRACE */ + +static void +add_lit (Lit * lit) +{ + assert (lit); + + if (ahead == eoa) + ENLARGE (added, ahead, eoa); + + *ahead++ = lit; +} + +static void +push_var_as_marked (Var * v) +{ + if (mhead == eom) + ENLARGE (marked, mhead, eom); + + *mhead++ = v; +} + +static void +mark_var (Var * v) +{ + assert (!v->mark); + v->mark = 1; + push_var_as_marked (v); +} + +/* Whenever we have a top level derived unit we really should derive a unit + * clause otherwise the resolutions in 'add_simplified_clause' become + * incorrect. + */ +static Cls * +resolve_top_level_unit (Lit * lit, Cls * reason) +{ + unsigned count_resolved; + Lit **p, **eol, *other; + Var *u, *v; + + assert (rhead == resolved); + assert (ahead == added); + + add_lit (lit); + add_antecedent (reason); + count_resolved = 1; + v = LIT2VAR (lit); + + eol = end_of_lits (reason); + for (p = reason->lits; p < eol; p++) + { + other = *p; + u = LIT2VAR (other); + if (u == v) + continue; + + add_antecedent (u->reason); + count_resolved++; + } + + /* Some of the literals could be assumptions. If at least one + * variable is not an assumption, we should resolve. + */ + if (count_resolved >= 2) + { +#ifdef NO_BINARY_CLAUSES + if (reason == &impl) + resetimpl (); +#endif + reason = add_simplified_clause (1); +#ifdef NO_BINARY_CLAUSES + if (reason->size == 2) + { + assert (reason == &impl); + other = reason->lits[0]; + if (lit == other) + other = reason->lits[1]; + assert (other->val == FALSE); + reason = LIT2REASON (NOTLIT (other)); + resetimpl (); + } +#endif + assign_reason (v, reason); + } + else + { + ahead = added; + rhead = resolved; + } + + return reason; +} + +static void +fixvar (Var * v) +{ + Rnk * r; + + assert (VAR2LIT (v) != UNDEF); + assert (!v->level); + + fixed++; + + r = VAR2RNK (v); + r->score = INFFLT; + +#ifndef NFL + if (simplifying) + return; +#endif + + if (!r->pos) + return; + + hup (r); +} + +static void +use_var (Var * v) +{ + if (v->used) + return; + + v->used = 1; + vused++; +} + +static void +assign_forced (Lit * lit, Cls * reason) +{ + Var *v; + + assert (reason); + assert (lit->val == UNDEF); + +#ifdef STATS + forced++; +#endif + assign (lit, reason); + +#ifdef NO_BINARY_CLAUSES + assert (reason != &impl); + if (ISLITREASON (reason)) + reason = setimpl (lit, NOTLIT (REASON2LIT (reason))); +#endif + LOG (fprintf (out, + "%sassign %d at level %d by ", + prefix, lit2int (lit), level); + dumpclsnl (reason)); + + v = LIT2VAR (lit); + if (!level) + use_var (v); + + if (reason && !level && reason->size > 1) + reason = resolve_top_level_unit (lit, reason); + +#ifdef NO_BINARY_CLAUSES + if (ISLITREASON (reason) || reason == &impl) + { + /* DO NOTHING */ + } + else +#endif + if (reason) + { + assert (!reason->locked); + reason->locked = 1; + if (reason->learned && reason->size > 2) + llocked++; + } + +#ifdef NO_BINARY_CLAUSES + if (reason == &impl) + resetimpl (); +#endif + + if (!level) + fixvar (v); +} + +#ifdef NO_BINARY_CLAUSES + +static void +lpush (Lit * lit, Cls * cls) +{ + int pos = (cls->lits[0] == lit); + Ltk * s = LIT2IMPLS (lit); + unsigned oldsize, newsize; + + assert (cls->size == 2); + + if (!s->start) + { + assert (!s->count); + assert (!s->ldsize); + NEWN (s->start, 1); + } + else + { + oldsize = (1 << (s->ldsize)); + assert (s->count <= oldsize); + if (s->count == oldsize) + { + newsize = 2 * oldsize; + RESIZEN (s->start, oldsize, newsize); + s->ldsize++; + } + } + + s->start[s->count++] = cls->lits[pos]; +} + +#endif + +static void +connect_head_tail (Lit * lit, Cls * cls) +{ + Cls ** s; + assert (cls->size >= 1); + if (cls->size == 2) + { +#ifdef NO_BINARY_CLAUSES + lpush (lit, cls); + return; +#else + s = LIT2IMPLS (lit); +#endif + } + else + s = LIT2HTPS (lit); + + if (cls->lits[0] != lit) + { + assert (cls->size >= 2); + assert (cls->lits[1] == lit); + cls->next[1] = *s; + } + else + cls->next[0] = *s; + + *s = cls; +} + +#ifdef TRACE +static void +zpush (Zhn * zhain) +{ + assert (trace); + + if (zhead == eoz) + ENLARGE (zhains, zhead, eoz); + + *zhead++ = zhain; +} + +static int +cmp_resolved (Cls * c, Cls * d) +{ + assert (trace); + + return CLS2IDX (c) - CLS2IDX (d); +} + +static void +bpushc (unsigned char ch) +{ + if (bhead == eob) + ENLARGE (buffer, bhead, eob); + + *bhead++ = ch; +} + +static void +bpushu (unsigned u) +{ + while (u & ~0x7f) + { + bpushc (u | 0x80); + u >>= 7; + } + + bpushc (u); +} + +static void +bpushd (unsigned prev, unsigned this) +{ + unsigned delta; + assert (prev < this); + delta = this - prev; + bpushu (delta); +} + +static void +add_zhain (void) +{ + unsigned prev, this, count, rcount; + Cls **p, *c; + Zhn *res; + + assert (trace); + assert (bhead == buffer); + assert (rhead > resolved); + + rcount = rhead - resolved; + sort (Cls *, cmp_resolved, resolved, rcount); + + prev = 0; + for (p = resolved; p < rhead; p++) + { + c = *p; + this = CLS2TRD (c)->idx; + bpushd (prev, this); + prev = this; + } + bpushc (0); + + count = bhead - buffer; + + res = new (sizeof (Zhn) + count); + res->core = 0; + res->ref = 0; + memcpy (res->znt, buffer, count); + + bhead = buffer; +#ifdef STATS + znts += count - 1; +#endif + zpush (res); +} + +#endif + +static void +add_resolved (int learned) +{ +#if defined(STATS) || defined(TRACE) + Cls **p, *c; + + for (p = resolved; p < rhead; p++) + { + c = *p; + if (c->used) + continue; + + c->used = 1; + + if (c->size <= 2) + continue; + +#ifdef STATS + if (c->learned) + llused++; + else + loused++; +#endif + } +#endif + +#ifdef TRACE + if (learned && trace) + add_zhain (); +#else + (void) learned; +#endif + rhead = resolved; +} + +static void +incjwh (Cls * cls) +{ + Lit **p, *lit, ** eol; + Flt * f, inc, sum; + unsigned size = 0; + Var * v; + Val val; + + eol = end_of_lits (cls); + + for (p = cls->lits; p < eol; p++) + { + lit = *p; + val = lit->val; + + if (val && level > 0) + { + v = LIT2VAR (lit); + if (v->level > 0) + val = UNDEF; + } + + if (val == TRUE) + return; + + if (val != FALSE) + size++; + } + + inc = base2flt (1, -size); + + for (p = cls->lits; p < eol; p++) + { + lit = *p; + f = LIT2JWH (lit); + sum = addflt (*f, inc); + *f = sum; + } +} + +static void +write_rup_header (FILE * file) +{ + char line[80]; + int i; + + sprintf (line, "%%RUPD32 %u %u", rupvariables, rupclauses); + + fputs (line, file); + for (i = 255 - strlen (line); i >= 0; i--) + fputc (' ', file); + + fputc ('\n', file); + fflush (file); +} + +static void +write_int (int d, FILE * file) +{ + static char write_int_buffer[16]; + unsigned tmp; + char * res; + int sign; + + assert (sizeof d <= 4); + + res = write_int_buffer + sizeof write_int_buffer; + *--res = 0; + + sign = (d < 0); + + if (sign) + tmp = (unsigned) -d; + else + tmp = d; + + do { + assert (res > write_int_buffer); + *--res = '0' + (tmp % 10); + tmp /= 10; + } while (tmp); + + if (sign) + { + assert (res > write_int_buffer); + *--res = '-'; + } + + fputs (res, file); +} + +static Cls * +add_simplified_clause (int learned) +{ + unsigned num_true, num_undef, num_false, idx, size, count_resolved; + Lit **p, **q, *lit, ** end; + Cls *res, * reason; + Val val; + Var *v; + +REENTER: + + size = ahead - added; + + add_resolved (learned); + + if (learned) + { + ladded++; + llitsadded += size; + if (size > 2) + { + lladded++; + nlclauses++; + llits += size; + } + } + else + { + oadded++; + if (size > 2) + { + loadded++; + noclauses++; + olits += size; + } + } + + addedclauses++; + assert (addedclauses == ladded + oadded); + +#ifdef NO_BINARY_CLAUSES + if (size == 2) + res = setimpl (added[0], added[1]); + else +#endif + { + sortlits (added, size); + + if (learned) + { + if (lhead == eol) + { + ENLARGE (lclauses, lhead, eol); + + /* A very difficult to find bug, which only occurs if the + * learned clauses stack is immediately allocated before the + * original clauses stack without padding. In this case, we + * have 'SOC == EOC', which terminates all loops using the + * idiom 'for (p = SOC; p != EOC; p = NXC(p))' immediately. + * Unfortunately this occurred in 'fix_clause_lits' after + * using a recent version of the memory allocator of 'Google' + * perftools in the context of one large benchmark for + * 'boolector'. + */ + if (eol == oclauses) + ENLARGE (lclauses, lhead, eol); + } + + idx = LIDX2IDX (lhead - lclauses); + } + else + { + if (ohead == eoo) + { + ENLARGE (oclauses, ohead, eoo); + if (eol == oclauses) + ENLARGE (oclauses, ohead, eoo); /* dito */ + } + + idx = OIDX2IDX (ohead - oclauses); + } + + assert (eol != oclauses); /* dito */ + + res = new_clause (size, learned); + +#if !defined(NDEBUG) && defined(TRACE) + if (trace) + assert (CLS2IDX (res) == idx); +#endif + if (learned) + *lhead++ = res; + else + *ohead++ = res; + +#if !defined(NDEBUG) && defined(TRACE) + if (trace && learned) + assert (zhead - zhains == lhead - lclauses); +#endif + assert (lhead != oclauses); /* dito */ + } + + if (learned && rup) + { + if (!rupstarted) + { + write_rup_header (rup); + rupstarted = 1; + } + } + + num_true = num_undef = num_false = 0; + + q = res->lits; + for (p = added; p < ahead; p++) + { + lit = *p; + *q++ = lit; + + if (learned && rup) + { + write_int (lit2int (lit), rup); + fputc (' ', rup); + } + + val = lit->val; + + num_true += (val == TRUE); + num_undef += (val == UNDEF); + num_false += (val == FALSE); + + v = LIT2VAR (lit); + } + assert (num_false + num_true + num_undef == size); + + if (learned && rup) + fputs ("0\n", rup); + + ahead = added; /* reset */ + + if (size > 0) + { + connect_head_tail (res->lits[0], res); + if (size > 1) + connect_head_tail (res->lits[1], res); + } + + if (size == 0) + { + if (!mtcls) + mtcls = res; + } + +#ifdef NO_BINARY_CLAUSES + if (size != 2) +#endif +#ifndef NDEBUG + res->connected = 1; +#endif + + LOG (fprintf (out, "%s%s ", prefix, learned ? "learned" : "original"); + dumpclsnl (res)); + + /* Shrink clause by resolving it against top level assignments. + */ + if (!level && num_false > 0) + { + assert (ahead == added); + assert (rhead == resolved); + + count_resolved = 1; + add_antecedent (res); + + end = end_of_lits (res); + for (p = res->lits; p < end; p++) + { + lit = *p; + v = LIT2VAR (lit); + use_var (v); + + if (lit->val == FALSE) + { + add_antecedent (v->reason); + count_resolved++; + } + else + add_lit (lit); + } + + assert (count_resolved >= 2); + + learned = 1; +#ifdef NO_BINARY_CLAUSES + if (res == &impl) + resetimpl (); +#endif + goto REENTER; /* and return simplified clause */ + } + + if (!num_true && num_undef == 1) /* unit clause */ + { + lit = 0; + for (p = res->lits; p < res->lits + size; p++) + { + if ((*p)->val == UNDEF) + lit = *p; + + v = LIT2VAR (*p); + use_var (v); + } + assert (lit); + + reason = res; +#ifdef NO_BINARY_CLAUSES + if (size == 2) + { + Lit * other = res->lits[0]; + if (other == lit) + other = res->lits[1]; + + assert (other->val == FALSE); + reason = LIT2REASON (NOTLIT (other)); + } +#endif + assign_forced (lit, reason); + num_true++; + } + + if (num_false == size && !conflict) + { +#ifdef NO_BINARY_CLAUSES + if (res == &impl) + conflict = setcimpl (res->lits[0], res->lits[1]); + else +#endif + conflict = res; + } + + if (!learned && !num_true && num_undef) + incjwh (res); + //FIXME: perhaps sketchy unsound hack +/* #ifdef NO_BINARY_CLAUSES */ +/* if (res == &impl) */ +/* resetimpl (); */ +/* #endif */ + return res; +} + +static int +trivial_clause (void) +{ + Lit **p, **q, *prev; + Var *v; + + sort (Lit *, cmp_ptr, added, ahead - added); + + prev = 0; + q = added; + for (p = q; p < ahead; p++) + { + Lit *this = *p; + + v = LIT2VAR (this); + + if (prev == this) /* skip repeated literals */ + continue; + + /* Top level satisfied ? + */ + if (this->val == TRUE && !v->level) + return 1; + + if (prev == NOTLIT (this))/* found pair of dual literals */ + return 1; + + *q++ = prev = this; + } + + ahead = q; /* shrink */ + + return 0; +} + +static void +simplify_and_add_original_clause (void) +{ + Cls * cls; + + if (trivial_clause ()) + { + ahead = added; + + if (ohead == eoo) + ENLARGE (oclauses, ohead, eoo); + + *ohead++ = 0; + + addedclauses++; + oadded++; + } + else + { + cls = add_simplified_clause (0); +#ifdef NO_BINARY_CLAUSES + if (cls == &impl) + resetimpl (); +#endif + } +} + +#ifndef NADC + +static void +add_ado (void) +{ + unsigned len = ahead - added; + Lit ** ado, ** p, ** q, *lit; + Var * v, * u; + +#ifdef TRACE + assert (!trace); +#endif + + ABORTIF (ados < hados && llength (ados[0]) != len, + "internal: non matching all different constraint object lengths"); + + if (hados == eados) + ENLARGE (ados, hados, eados); + + NEWN (ado, len + 1); + *hados++ = ado; + + p = added; + q = ado; + u = 0; + while (p < ahead) + { + lit = *p++; + v = LIT2VAR (lit); + ABORTIF (v->inado, + "internal: variable in multiple all different objects"); + v->inado = ado; + if (!u && !lit->val) + u = v; + *q++ = lit; + } + + assert (q == ado + len); + *q++ = 0; + + /* TODO simply do a conflict test as in propado */ + + ABORTIF (!u, + "internal: " + "adding fully instantiated all different object not implemented yet"); + + assert (u); + assert (u->inado == ado); + assert (!u->ado); + u->ado = ado; + + ahead = added; +} + +#endif + +static void +hdown (Rnk * r) +{ + unsigned end, rpos, cpos, opos; + Rnk *child, *other; + + assert (r->pos > 0); + assert (heap[r->pos] == r); + + end = hhead - heap; + rpos = r->pos; + + for (;;) + { + cpos = 2 * rpos; + if (cpos >= end) + break; + + opos = cpos + 1; + child = heap[cpos]; + + if (cmp_rnk (r, child) < 0) + { + if (opos < end) + { + other = heap[opos]; + + if (cmp_rnk (child, other) < 0) + { + child = other; + cpos = opos; + } + } + } + else if (opos < end) + { + child = heap[opos]; + + if (cmp_rnk (r, child) >= 0) + break; + + cpos = opos; + } + else + break; + + heap[rpos] = child; + child->pos = rpos; + rpos = cpos; + } + + r->pos = rpos; + heap[rpos] = r; +} + +static Rnk * +htop (void) +{ + assert (hhead > heap); + return heap[1]; +} + +static Rnk * +hpop (void) +{ + Rnk *res, *last; + unsigned end; + + assert (hhead > heap); + + res = heap[1]; + res->pos = 0; + + end = --hhead - heap; + if (end == 1) + return res; + + last = heap[end]; + + heap[last->pos = 1] = last; + hdown (last); + + return res; +} + +inline static void +hpush (Rnk * r) +{ + assert (!r->pos); + + if (hhead == eoh) + ENLARGE (heap, hhead, eoh); + + r->pos = hhead++ - heap; + heap[r->pos] = r; + hup (r); +} + +static void +fix_trail_lits (long delta) +{ + Lit **p; + for (p = trail; p < thead; p++) + *p += delta; +} + +#ifdef NO_BINARY_CLAUSES +static void +fix_impl_lits (long delta) +{ + Ltk * s; + Lit ** p; + + for (s = impls + 2; s < impls + 2 * max_var; s++) + for (p = s->start; p < s->start + s->count; p++) + *p += delta; +} +#endif + +static void +fix_clause_lits (long delta) +{ + Cls **p, *clause; + Lit **q, *lit, **eol; + + for (p = SOC; p != EOC; p = NXC (p)) + { + clause = *p; + if (!clause) + continue; + + q = clause->lits; + eol = end_of_lits (clause); + while (q < eol) + { + assert (q - clause->lits <= (int) clause->size); + lit = *q; + lit += delta; + *q++ = lit; + } + } +} + +static void +fix_added_lits (long delta) +{ + Lit **p; + for (p = added; p < ahead; p++) + *p += delta; +} + +static void +fix_assumed_lits (long delta) +{ + Lit **p; + for (p = als; p < alshead; p++) + *p += delta; +} + +static void +fix_heap_rnks (long delta) +{ + Rnk **p; + + for (p = heap + 1; p < hhead; p++) + *p += delta; +} + +#ifndef NADC + +static void +fix_ado (long delta, Lit ** ado) +{ + Lit ** p; + for (p = ado; *p; p++) + *p += delta; +} + +static void +fix_ados (long delta) +{ + Lit *** p; + + for (p = ados; p < hados; p++) + fix_ado (delta, *p); +} + +#endif + +static void +enlarge (unsigned new_size_vars) +{ + long rnks_delta, lits_delta, vars_delta; + Lit *old_lits = lits; + Rnk *old_rnks = rnks; + Var *old_vars = vars; + + RESIZEN (lits, 2 * size_vars, 2 * new_size_vars); + RESIZEN (jwh, 2 * size_vars, 2 * new_size_vars); + RESIZEN (htps, 2 * size_vars, 2 * new_size_vars); +#ifndef NDSC + RESIZEN (dhtps, 2 * size_vars, 2 * new_size_vars); +#endif + RESIZEN (impls, 2 * size_vars, 2 * new_size_vars); + RESIZEN (vars, size_vars, new_size_vars); + RESIZEN (rnks, size_vars, new_size_vars); + + lits_delta = lits - old_lits; + rnks_delta = rnks - old_rnks; + vars_delta = vars - old_vars; + + fix_trail_lits (lits_delta); + fix_clause_lits (lits_delta); + fix_added_lits (lits_delta); + fix_assumed_lits (lits_delta); +#ifdef NO_BINARY_CLAUSES + fix_impl_lits (lits_delta); +#endif +#ifndef NADC + fix_ados (lits_delta); +#endif + fix_heap_rnks (rnks_delta); + assert (mhead == marked); + + size_vars = new_size_vars; +} + +static void +unassign (Lit * lit) +{ + Cls *reason; + Var *v; + Rnk *r; + + assert (lit->val == TRUE); + + LOG (fprintf (out, "%sunassign %d\n", prefix, lit2int (lit))); + + v = LIT2VAR (lit); + reason = v->reason; + +#ifdef NO_BINARY_CLAUSES + assert (reason != &impl); + if (ISLITREASON (reason)) + { + /* DO NOTHING */ + } + else +#endif + if (reason) + { + assert (reason->locked); + reason->locked = 0; + if (reason->learned && reason->size > 2) + { + assert (llocked > 0); + llocked--; + } + } + + lit->val = UNDEF; + NOTLIT (lit)->val = UNDEF; + + r = VAR2RNK (v); + if (!r->pos) + hpush (r); + +#ifndef NDSC + { + Cls * p, * next, ** q; + + q = LIT2DHTPS (lit); + p = *q; + *q = 0; + + while (p) + { + Lit * other = p->lits[0]; + + if (other == lit) + { + other = p->lits[1]; + q = p->next + 1; + } + else + { + assert (p->lits[1] == lit); + q = p->next; + } + + next = *q; + *q = *LIT2HTPS (other); + *LIT2HTPS (other) = p; + p = next; + } + } +#endif + +#ifndef NADC + if (v->adotabpos) + { + assert (nadotab); + assert (*v->adotabpos == v->ado); + + *v->adotabpos = 0; + v->adotabpos = 0; + + nadotab--; + } +#endif +} + +static Cls * +var2reason (Var * var) +{ + Cls * res = var->reason; +#ifdef NO_BINARY_CLAUSES + Lit * this, * other; + if (ISLITREASON (res)) + { + this = VAR2LIT (var); + if (this->val == FALSE) + this = NOTLIT (this); + + other = REASON2LIT (res); + assert (other->val == TRUE); + assert (this->val == TRUE); + res = setimpl (NOTLIT (other), this); + } +#endif + return res; +} + +static void +mark_clause_to_be_collected (Cls * cls) +{ + assert (!cls->collect); + cls->collect = 1; +} + +static void +undo (unsigned new_level) +{ + Lit *lit; + Var *v; + + while (thead > trail) + { + lit = *--thead; + v = LIT2VAR (lit); + if (v->level == new_level) + { + thead++; /* fix pre decrement */ + break; + } + + unassign (lit); + } + + level = new_level; + ttail = thead; + ttail2 = thead; +#ifndef NADC + ttailado = thead; +#endif + +#ifdef NO_BINARY_CLAUSES + if (conflict == &cimpl) + resetcimpl (); +#endif +#ifndef NADC + if (conflict && conflict == adoconflict) + resetadoconflict (); +#endif + conflict = mtcls; + if (level < adecidelevel) + { + assert (als < alshead); + adecidelevel = 0; + alstail = als; + } + LOG (fprintf (out, "%sback to level %u\n", prefix, level)); +} + +#ifndef NDEBUG + +static int +clause_satisfied (Cls * cls) +{ + Lit **p, **eol, *lit; + + eol = end_of_lits (cls); + for (p = cls->lits; p < eol; p++) + { + lit = *p; + if (lit->val == TRUE) + return 1; + } + + return 0; +} + +static void +original_clauses_satisfied (void) +{ + Cls **p, *cls; + + for (p = oclauses; p < ohead; p++) + { + cls = *p; + + if (!cls) + continue; + + if (cls->learned) + continue; + + assert (clause_satisfied (cls)); + } +} + +static void +assumptions_satisfied (void) +{ + Lit *lit, ** p; + + for (p = als; p < alshead; p++) + { + lit = *p; + assert (lit->val == TRUE); + } +} + +#endif + +static void +sflush (void) +{ + double now = picosat_time_stamp (); + double delta = now - entered; + delta = (delta < 0) ? 0 : delta; + seconds += delta; + entered = now; +} + +static double +mb (void) +{ + return current_bytes / (double) (1 << 20); +} + +static double +avglevel (void) +{ + return decisions ? levelsum / decisions : 0.0; +} + +static void +rheader (void) +{ + assert (lastrheader <= reports); + + if (lastrheader == reports) + return; + + lastrheader = reports; + + fprintf (out, "%s\n", prefix); + fprintf (out, "%s %s\n", prefix, rline[0]); + fprintf (out, "%s %s\n", prefix, rline[1]); + fprintf (out, "%s\n", prefix); +} + +static unsigned +dynamic_flips_per_assignment_per_mille (void) +{ + assert (FFLIPPEDPREC >= 1000); + return sdflips / (FFLIPPEDPREC / 1000); +} + +#ifdef NLUBY + +static int +high_agility (void) +{ + return dynamic_flips_per_assignment_per_mille () >= 200; +} + +static int +very_high_agility (void) +{ + return dynamic_flips_per_assignment_per_mille () >= 250; +} + +#else + +static int +medium_agility (void) +{ + return dynamic_flips_per_assignment_per_mille () >= 230; +} + +#endif + +static void +relemdata (void) +{ + char *p; + int x; + + if (reports < 0) + { + /* strip trailing white space + */ + for (x = 0; x <= 1; x++) + { + p = rline[x] + strlen (rline[x]); + while (p-- > rline[x]) + { + if (*p != ' ') + break; + + *p = 0; + } + } + + rheader (); + } + else + fputc ('\n', out); + + rcount = 0; +} + +static void +relemhead (const char * name, int fp, double val) +{ + int x, y, len, size; + const char *fmt; + unsigned tmp, e; + + if (reports < 0) + { + x = rcount & 1; + y = (rcount / 2) * 12 + x * 6; + + if (rcount == 1) + sprintf (rline[1], "%6s", ""); + + len = strlen (name); + while (szrline <= len + y + 1) + { + size = szrline ? 2 * szrline : 128; + rline[0] = resize (rline[0], szrline, size); + rline[1] = resize (rline[1], szrline, size); + szrline = size; + } + + fmt = (len <= 6) ? "%6s%10s" : "%-10s%4s"; + sprintf (rline[x] + y, fmt, name, ""); + } + else if (val < 0) + { + assert (fp); + + if (val > -100 && (tmp = val * 10.0 - 0.5) > -1000.0) + { + fprintf (out, "-%4.1f ", -tmp / 10.0); + } + else + { + tmp = -val / 10.0 + 0.5; + e = 1; + while (tmp >= 100) + { + tmp /= 10; + e++; + } + + fprintf (out, "-%2ue%u ", tmp, e); + } + } + else + { + if (fp && val < 1000 && (tmp = val * 10.0 + 0.5) < 10000) + { + fprintf (out, "%5.1f ", tmp / 10.0); + } + else if (!fp && (tmp = val) < 100000) + { + fprintf (out, "%5u ", tmp); + } + else + { + tmp = val / 10.0 + 0.5; + e = 1; + + while (tmp >= 1000) + { + tmp /= 10; + e++; + } + + fprintf (out, "%3ue%u ", tmp, e); + } + } + + rcount++; +} + +inline static void +relem (const char *name, int fp, double val) +{ + if (name) + relemhead (name, fp, val); + else + relemdata (); +} + +static unsigned +reduce_limit_on_lclauses (void) +{ + unsigned res = lreduce; + res += llocked; + return res; +} + +static void +report (int level, char type) +{ + int rounds; + + if (verbosity < level) + return; + + sflush (); + + if (!reports) + reports = -1; + + for (rounds = (reports < 0) ? 2 : 1; rounds; rounds--) + { + if (reports >= 0) + fprintf (out, "%s%c ", prefix, type); + + relem ("seconds", 1, seconds); + relem ("level", 1, avglevel ()); + assert (fixed <= max_var); + relem ("variables", 0, max_var - fixed); + relem ("used", 1, PERCENT (vused, max_var)); + relem ("original", 0, noclauses); + relem ("conflicts", 0, conflicts); + //relem ("decisions", 0, decisions); + // relem ("conf/dec", 1, PERCENT(conflicts,decisions)); + // relem ("limit", 0, reduce_limit_on_lclauses ()); + relem ("learned", 0, nlclauses); + // relem ("limit", 1, PERCENT (nlclauses, reduce_limit_on_lclauses ())); + relem ("limit", 0, lreduce); +#ifdef STATS + relem ("learning", 1, PERCENT (llused, lladded)); +#endif + relem ("agility", 1, dynamic_flips_per_assignment_per_mille () / 10.0); + // relem ("original", 0, noclauses); + relem ("MB", 1, mb ()); + // relem ("lladded", 0, lladded); + // relem ("llused", 0, llused); + + relem (0, 0, 0); + + reports++; + } + + /* Adapt this to the number of rows in your terminal. + */ + #define ROWS 25 + + if (reports % (ROWS - 3) == (ROWS - 4)) + rheader (); + + fflush (out); +} + +static int +bcp_queue_is_empty (void) +{ + if (ttail != thead) + return 0; + + if (ttail2 != thead) + return 0; + +#ifndef NADC + if (ttailado != thead) + return 0; +#endif + + return 1; +} + +static int +satisfied (void) +{ + assert (!mtcls); + assert (!failed_assumption); + if (alstail < alshead) + return 0; + assert (!conflict); + assert (bcp_queue_is_empty ()); + return thead == trail + max_var; /* all assigned */ +} + +static void +vrescore (void) +{ + Rnk *p, *eor = rnks + max_var; + for (p = rnks + 1; p <= eor; p++) + if (p->score != INFFLT) + p->score = mulflt (p->score, ilvinc); + vinc = mulflt (vinc, ilvinc);; +#ifdef VISCORES + nvinc = mulflt (nvinc, lscore);; +#endif +} + +static void +inc_score (Var * v) +{ + Flt score; + Rnk *r; + +#ifndef NFL + if (simplifying) + return; +#endif + + if (!v->level) + return; + + r = VAR2RNK (v); + score = r->score; + + assert (score != INFFLT); + + score = addflt (score, vinc); + assert (score < INFFLT); + r->score = score; + if (r->pos > 0) + hup (r); + + if (score > lscore) + vrescore (); +} + +static void +inc_activity (Cls * cls) +{ + Act *p; + + if (!cls->learned) + return; + + if (cls->size <= 2) + return; + + p = CLS2ACT (cls); + *p = addflt (*p, cinc); +} + +static unsigned +hashlevel (unsigned l) +{ + return 1u << (l & 31); +} + +static void +push (Var * v) +{ + if (dhead == eod) + ENLARGE (dfs, dhead, eod); + + *dhead++ = v; +} + +static Var * +pop (void) +{ + assert (dfs < dhead); + return *--dhead; +} + +static void +analyze (void) +{ + unsigned open, minlevel, siglevels, l, old, i, orig; + Lit *this, *other, **p, **q, **eol; + Var *v, *u, **m, *start, *uip; + Cls *c; + + assert (conflict); + + assert (ahead == added); + assert (mhead == marked); + assert (rhead == resolved); + + /* 2. Search for First UIP variable and mark all resolved variables. At + * the same time determine the minimum decision level involved. Increase + * activities of resolved variables. + */ + q = thead; + open = 0; + minlevel = level; + siglevels = 0; + uip = 0; + + c = conflict; + + for (;;) + { + add_antecedent (c); + inc_activity (c); + eol = end_of_lits (c); + for (p = c->lits; p < eol; p++) + { + other = *p; + + if (other->val == TRUE) + continue; + + assert (other->val == FALSE); + + u = LIT2VAR (other); + if (u->mark) + continue; + + u->mark = 1; + inc_score (u); + use_var (u); + + if (u->level == level) + { + open++; + } + else + { + push_var_as_marked (u); + + if (u->level) + { + /* The statistics counter 'nonminimizedllits' sums up the + * number of literals that would be added if only the + * 'first UIP' scheme for learned clauses would be used + * and no clause minimization. + */ + nonminimizedllits++; + + if (u->level < minlevel) + minlevel = u->level; + + siglevels |= hashlevel (u->level); + } + else + { + assert (!u->level); + assert (u->reason); + } + } + } + + do + { + if (q == trail) + { + uip = 0; + goto DONE_FIRST_UIP; + } + + this = *--q; + uip = LIT2VAR (this); + } + while (!uip->mark); + + uip->mark = 0; + + c = var2reason (uip); +#ifdef NO_BINARY_CLAUSES + if (c == &impl) + resetimpl (); +#endif + open--; + if ((!open && level) || !c) + break; + + assert (c); + } + +DONE_FIRST_UIP: + + if (uip) + { + assert (level); + this = VAR2LIT (uip); + this += (this->val == TRUE); + nonminimizedllits++; + minimizedllits++; + add_lit (this); +#ifdef STATS + if (uip->reason) + uips++; +#endif + } + else + assert (!level); + + /* 3. Try to mark more intermediate variables, with the goal to minimize + * the conflict clause. This is a DFS from already marked variables + * backward through the implication graph. It tries to reach other marked + * variables. If the search reaches an unmarked decision variable or a + * variable assigned below the minimum level of variables in the first uip + * learned clause or a level on which no variable has been marked, then + * the variable from which the DFS is started is not redundant. Otherwise + * the start variable is redundant and will eventually be removed from the + * learned clause in step 4. We initially implemented BFS, but then + * profiling revelead that this step is a bottle neck for certain + * incremental applications. After switching to DFS this hot spot went + * away. + */ + orig = mhead - marked; + for (i = 0; i < orig; i++) + { + start = marked[i]; + + assert (start->mark); + assert (start != uip); + assert (start->level < level); + + if (!start->reason) + continue; + + old = mhead - marked; + assert (dhead == dfs); + push (start); + + while (dhead > dfs) + { + u = pop (); + assert (u->mark); + + c = var2reason (u); +#ifdef NO_BINARY_CLAUSES + if (c == &impl) + resetimpl (); +#endif + if (!c || + ((l = u->level) && + (l < minlevel || ((hashlevel (l) & ~siglevels))))) + { + while (mhead > marked + old) /* reset all marked */ + (*--mhead)->mark = 0; + + dhead = dfs; /* and DFS stack */ + break; + } + + eol = end_of_lits (c); + for (p = c->lits; p < eol; p++) + { + v = LIT2VAR (*p); + if (v->mark) + continue; + + mark_var (v); + push (v); + } + } + } + + for (m = marked; m < mhead; m++) + { + v = *m; + + assert (v->mark); + assert (!v->resolved); + + use_var (v); + + c = var2reason (v); + if (!c) + continue; + +#ifdef NO_BINARY_CLAUSES + if (c == &impl) + resetimpl (); +#endif + eol = end_of_lits (c); + for (p = c->lits; p < eol; p++) + { + other = *p; + + u = LIT2VAR (other); + if (!u->level) + continue; + + if (!u->mark) /* 'MARKTEST' */ + break; + } + + if (p != eol) + continue; + + add_antecedent (c); + v->resolved = 1; + } + + for (m = marked; m < mhead; m++) + { + v = *m; + + assert (v->mark); + v->mark = 0; + + if (v->resolved) + { + v->resolved = 0; + continue; + } + + this = VAR2LIT (v); + if (this->val == TRUE) + this++; /* actually NOTLIT */ + + add_lit (this); + minimizedllits++; + } + + assert (ahead <= eoa); + assert (rhead <= eor); + + mhead = marked; +} + +static void +fanalyze (void) +{ + Lit ** eol, ** p, * lit; + Cls * cls, * reason; + Var * v, * u; + int next; + + double start = picosat_time_stamp (); + + assert (failed_assumption); + assert (failed_assumption->val == FALSE); + + v = LIT2VAR (failed_assumption); + reason = var2reason (v); + if (!reason) return; +#ifdef NO_BINARY_CLAUSES + if (reason == &impl) + resetimpl (); +#endif + + eol = end_of_lits (reason); + for (p = reason->lits; p != eol; p++) + { + lit = *p; + u = LIT2VAR (lit); + if (u == v) continue; + if (u->reason) break; + } + if (p == eol) return; + + assert (ahead == added); + assert (mhead == marked); + assert (rhead == resolved); + + next = 0; + mark_var (v); + add_lit (NOTLIT (failed_assumption)); + + do + { + v = marked[next++]; + use_var (v); + if (v->reason) + { + reason = var2reason (v); +#ifdef NO_BINARY_CLAUSES + if (reason == &impl) + resetimpl (); +#endif + add_antecedent (reason); + eol = end_of_lits (reason); + for (p = reason->lits; p != eol; p++) + { + lit = *p; + u = LIT2VAR (lit); + if (u == v) continue; + if (u->mark) continue; + mark_var (u); + } + } + else + { + lit = VAR2LIT (v); + if (lit->val == TRUE) lit = NOTLIT (lit); + add_lit (lit); + } + } + while (marked + next < mhead); + + cls = add_simplified_clause (1); + v = LIT2VAR (failed_assumption); + reason = var2reason (v); +#ifdef NO_BINARY_CLAUSES + if (reason == &impl) + resetimpl (); + else +#endif + { + assert (reason->locked); + reason->locked = 0; + } + if (reason->learned && reason->size > 2) + { + assert (llocked > 0); + llocked--; + } + v->reason = cls; + assert (cls->learned); + assert (!cls->locked); + cls->locked = 1; + if (cls->size > 2) + { + llocked++; + assert (llocked > 0); + } + + while (mhead > marked) + (*--mhead)->mark = 0; + + if (verbosity) + fprintf (out, "%sfanalyze took %.1f seconds\n", + prefix, picosat_time_stamp () - start); +} + +/* Propagate assignment of 'this' to 'FALSE' by visiting all binary clauses in + * which 'this' occurs. + */ +inline static void +prop2 (Lit * this) +{ +#ifdef NO_BINARY_CLAUSES + Lit ** l, ** start; + Ltk * lstk; +#else + Cls * cls, ** p; + Cls * next; +#endif + Lit * other; + Val tmp; + + assert (this->val == FALSE); + +#ifdef NO_BINARY_CLAUSES + lstk = LIT2IMPLS (this); + start = lstk->start; + l = start + lstk->count; + while (l != start) + { +#ifdef STATS + /* The counter 'visits' is the number of clauses that are + * visited during propagations of assignments. + */ + visits++; + bvisits++; +#endif + other = *--l; + tmp = other->val; + + if (tmp == TRUE) + { +#ifdef STATS + othertrue++; + othertrue2++; + if (LIT2VAR (other)->level < level) + othertrue2u++; +#endif + continue; + } + + if (tmp != FALSE) + { + assign_forced (other, LIT2REASON (NOTLIT(this))); + continue; + } + + if (conflict == &cimpl) + resetcimpl (); + conflict = setcimpl (this, other); + } +#else + /* Traverse all binary clauses with 'this'. Head/Tail pointers for binary + * clauses do not have to be modified here. + */ + p = LIT2IMPLS (this); + for (cls = *p; cls; cls = next) + { +#ifdef STATS + visits++; + bvisits++; +#endif + assert (!cls->collect); +#ifdef TRACE + assert (!cls->collected); +#endif + assert (cls->size == 2); + + other = cls->lits[0]; + if (other == this) + { + next = cls->next[0]; + other = cls->lits[1]; +#ifdef STATS +#endif + } + else + next = cls->next[1]; + + tmp = other->val; + + if (tmp == TRUE) + { +#ifdef STATS + othertrue++; + othertrue2++; + if (LIT2VAR (other)->level < level) + othertrue2u++; +#endif + continue; + } + + if (tmp == FALSE) + conflict = cls; + else + assign_forced (other, cls); /* unit clause */ + } +#endif /* !defined(NO_BINARY_CLAUSES) */ +} + +#ifndef NDSC +static int +should_disconnect_head_tail (Lit * lit) +{ + unsigned lit_level; + Var * v; + + assert (lit->val == TRUE); + + v = LIT2VAR (lit); + lit_level = v->level; + + if (!lit_level) + return 1; + +#ifndef NFL + if (simplifying) + return 0; +#endif + + return lit_level < level; +} +#endif + +inline static void +propl (Lit * this) +{ + Lit **l, *other, *prev, *new_lit, **eol; + Cls *next, **htp_ptr, **new_htp_ptr; + Cls *cls; +#ifdef STATS + unsigned size; +#endif + + htp_ptr = LIT2HTPS (this); + assert (this->val == FALSE); + + /* Traverse all non binary clauses with 'this'. Head/Tail pointers are + * updated as well. + */ + for (cls = *htp_ptr; cls; cls = next) + { +#ifdef STATS + visits++; + size = cls->size; + if (size == 2) + bvisits++; + else if (size >= 3) + { + traversals++; /* other is dereferenced at least */ + + if (size == 3) + tvisits++; + else if (size >= 4) + { + lvisits++; + ltraversals++; + } + } +#endif +#ifdef TRACE + assert (!cls->collected); +#endif + assert (cls->size > 0); + + /* With assumptions we need to traverse unit clauses as well. + */ + if (cls->size == 1) + { + assert (!conflict); + conflict = cls; + break; + } + + other = cls->lits[0]; + if (other != this) + { + cls->lits[0] = this; + cls->lits[1] = other; + next = cls->next[1]; + cls->next[1] = cls->next[0]; + cls->next[0] = next; + } + else + { + other = cls->lits[1]; + next = cls->next[0]; + } + assert (other == cls->lits[1]); + assert (this == cls->lits[0]); + assert (next == cls->next[0]); + assert (!cls->collect); + + if (other->val == TRUE) + { +#ifdef STATS + othertrue++; + othertruel++; +#endif +#ifndef NDSC + if (should_disconnect_head_tail (other)) + { + new_htp_ptr = LIT2DHTPS (other); + cls->next[0] = *new_htp_ptr; + *new_htp_ptr = cls; +#ifdef STATS + othertruelu++; +#endif + *htp_ptr = next; + continue; + } +#endif + htp_ptr = cls->next; + continue; + } + + l = cls->lits + 1; + eol = cls->lits + cls->size; + prev = this; + + while (++l != eol) + { +#ifdef STATS + if (size >= 3) + { + traversals++; + if (size > 3) + ltraversals++; + } +#endif + new_lit = *l; + *l = prev; + prev = new_lit; + if (new_lit->val != FALSE) break; + } + + if (l == eol) + { + while (l > cls->lits + 2) + { + new_lit = *--l; + *l = prev; + prev = new_lit; + } + assert (cls->lits[0] == this); + + assert (other == cls->lits[1]); + if (other->val == FALSE) /* found conflict */ + { + assert (!conflict); + conflict = cls; + return; + } + + assign_forced (other, cls); /* unit clause */ + htp_ptr = cls->next; + } + else + { + assert (new_lit->val == TRUE || new_lit->val == UNDEF); + cls->lits[0] = new_lit; + // *l = this; + new_htp_ptr = LIT2HTPS (new_lit); + cls->next[0] = *new_htp_ptr; + *new_htp_ptr = cls; + *htp_ptr = next; + } + } +} + +#ifndef NADC + +static unsigned primes[] = { 996293, 330643, 753947, 500873 }; + +#define PRIMES ((sizeof primes)/sizeof *primes) + +static unsigned +hash_ado (Lit ** ado, unsigned salt) +{ + unsigned i, res, tmp; + Lit ** p, * lit; + + assert (salt < PRIMES); + + i = salt; + res = 0; + + for (p = ado; (lit = *p); p++) + { + assert (lit->val); + + tmp = res >> 31; + res <<= 1; + + if (lit->val > 0) + res |= 1; + + assert (i < PRIMES); + res *= primes[i++]; + if (i == PRIMES) + i = 0; + + res += tmp; + } + + return res & (szadotab - 1); +} + +static unsigned +cmp_ado (Lit ** a, Lit ** b) +{ + Lit ** p, ** q, * l, * k; + int res; + + for (p = a, q = b; (l = *p); p++, q++) + { + k = *q; + assert (k); + if ((res = (l->val - k->val))) + return res; + } + + assert (!*q); + + return 0; +} + +static Lit *** +find_ado (Lit ** ado) +{ + Lit *** res, ** other; + unsigned pos, delta; + + pos = hash_ado (ado, 0); + assert (pos < szadotab); + res = adotab + pos; + + other = *res; + if (!other || !cmp_ado (other, ado)) + return res; + + delta = hash_ado (ado, 1); + if (!(delta & 1)) + delta++; + + assert (delta & 1); + assert (delta < szadotab); + + for (;;) + { + pos += delta; + if (pos >= szadotab) + pos -= szadotab; + + assert (pos < szadotab); + res = adotab + pos; + other = *res; + if (!other || !cmp_ado (other, ado)) + return res; + } +} + +static void +enlarge_adotab (void) +{ + /* TODO make this generic */ + + ABORTIF (szadotab, + "internal: all different objects table needs larger initial size"); + assert (!nadotab); + szadotab = 10000; + NEWN (adotab, szadotab); + CLRN (adotab, szadotab); +} + +static int +propado (Var * v) +{ + Lit ** p, ** q, *** adotabpos, **ado, * lit; + Var * u; + + if (level && adodisabled) + return 1; + + assert (!conflict); + assert (!adoconflict); + assert (VAR2LIT (v)->val != UNDEF); + assert (!v->adotabpos); + + if (!v->ado) + return 1; + + assert (v->inado); + + for (p = v->ado; (lit = *p); p++) + if (lit->val == UNDEF) + { + u = LIT2VAR (lit); + assert (!u->ado); + u->ado = v->ado; + v->ado = 0; + + return 1; + } + + if (4 * nadotab >= 3 * szadotab) /* at least 75% filled */ + enlarge_adotab (); + + adotabpos = find_ado (v->ado); + ado = *adotabpos; + + if (!ado) + { + nadotab++; + v->adotabpos = adotabpos; + *adotabpos = v->ado; + return 1; + } + + assert (ado != v->ado); + + adoconflict = new_clause (2 * llength (ado), 1); + q = adoconflict->lits; + + for (p = ado; (lit = *p); p++) + *q++ = lit->val == FALSE ? lit : NOTLIT (lit); + + for (p = v->ado; (lit = *p); p++) + *q++ = lit->val == FALSE ? lit : NOTLIT (lit); + + assert (q == ENDOFCLS (adoconflict)); + conflict = adoconflict; + adoconflicts++; + return 0; +} + +#endif + +static void +bcp (void) +{ + int props = 0; + assert (!conflict); + + if (mtcls || conflict) + return; + + for (;;) + { + if (ttail2 < thead) /* prioritize implications */ + { + props++; + prop2 (NOTLIT (*ttail2++)); + } + else if (ttail < thead) /* unit clauses or clauses with length > 2 */ + { + if (conflict) break; + propl (NOTLIT (*ttail++)); + if (conflict) break; + } +#ifndef NADC + else if (ttailado < thead) + { + if (conflict) break; + propado (LIT2VAR (*ttailado++)); + if (conflict) break; + } +#endif + else + break; /* all assignments propagated, so break */ + } + + propagations += props; +} + +/* This version of 'drive' is independent of the global variable 'level' and + * thus even works if we resolve ala 'relsat' without driving an assignment. + */ +static unsigned +drive (void) +{ + Var *v, *first, *second; + Lit **p; + + first = 0; + for (p = added; p < ahead; p++) + { + v = LIT2VAR (*p); + if (!first || v->level > first->level) + first = v; + } + + if (!first) + return 0; + + second = 0; + for (p = added; p < ahead; p++) + { + v = LIT2VAR (*p); + + if (v->level == first->level) + continue; + + if (!second || v->level > second->level) + second = v; + } + + if (!second) + return 0; + + return second->level; +} + +#ifdef VISCORES + +static void +viscores (void) +{ + Rnk *p, *eor = rnks + max_var; + char name[100], cmd[200]; + FILE * data; + Flt s; + int i; + + for (p = rnks + 1; p <= eor; p++) + { + s = p->score; + if (s == INFFLT) + continue; + s = mulflt (s, nvinc); + assert (flt2double (s) <= 1.0); + } + + sprintf (name, "/tmp/picosat-viscores/data/%08u", conflicts); + sprintf (cmd, "sort -n|nl>%s", name); + + data = popen (cmd, "w"); + for (p = rnks + 1; p <= eor; p++) + { + s = p->score; + if (s == INFFLT) + continue; + s = mulflt (s, nvinc); + fprintf (data, "%lf %d\n", 100.0 * flt2double (s), (int)(p - rnks)); + } + fflush (data); + pclose (data); + + for (i = 0; i < 8; i++) + { + sprintf (cmd, "awk '$3%%8==%d' %s>%s.%d", i, name, name, i); + system (cmd); + } + + fprintf (fviscores, "set title \"%u\"\n", conflicts); + fprintf (fviscores, "plot [0:%u] 0, 100 * (1 - 1/1.1), 100", max_var); + + for (i = 0; i < 8; i++) + fprintf (fviscores, + ", \"%s.%d\" using 1:2:3 with labels tc lt %d", + name, i, i + 1); + + fputc ('\n', fviscores); + fflush (fviscores); +#ifndef WRITEGIF + usleep (50000); /* refresh rate of 20 Hz */ +#endif +} + +#endif + +static void +crescore (void) +{ + Cls **p, *cls; + Act *a; + Flt factor; + int l = log2flt (cinc); + assert (l > 0); + factor = base2flt (1, -l); + + for (p = lclauses; p != lhead; p++) + { + cls = *p; + + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + assert (cls->learned); + + if (cls->size <= 2) + continue; + + a = CLS2ACT (cls); + *a = mulflt (*a, factor); + } + + cinc = mulflt (cinc, factor); +} + +static void +inc_vinc (void) +{ +#ifdef VISCORES + nvinc = mulflt (nvinc, fvinc); +#endif + vinc = mulflt (vinc, ifvinc); +} + +inline static void +inc_max_var (void) +{ + Lit *lit; + Rnk *r; + Var *v; + + assert (max_var < size_vars); + + max_var++; /* new index of variable */ + assert (max_var); /* no unsigned overflow */ + + if (max_var == size_vars) + enlarge (size_vars + (size_vars + 3) / 4); /* increase by 25% */ + + assert (max_var < size_vars); + + lit = lits + 2 * max_var; + lit[0].val = lit[1].val = UNDEF; + + memset (htps + 2 * max_var, 0, 2 * sizeof *htps); +#ifndef NDSC + memset (dhtps + 2 * max_var, 0, 2 * sizeof *dhtps); +#endif + memset (impls + 2 * max_var, 0, 2 * sizeof *impls); + memset (jwh + 2 * max_var, 0, 2 * sizeof *jwh); + + v = vars + max_var; /* initialize variable components */ + CLR (v); + + r = rnks + max_var; /* initialize rank */ + CLR (r); + + hpush (r); +} + +static void +force (Cls * cls) +{ + Lit ** p, ** eol, * lit, * forced; + Cls * reason; + Var *v; + + forced = 0; + reason = cls; + + eol = end_of_lits (cls); + for (p = cls->lits; p < eol; p++) + { + lit = *p; + if (lit->val == UNDEF) + { + assert (!forced); + forced = lit; +#ifdef NO_BINARY_CLAUSES + if (cls == &impl) + reason = LIT2REASON (NOTLIT (p[p == cls->lits ? 1 : -1])); +#endif + } + else + assert (lit->val == FALSE); + } + +#ifdef NO_BINARY_CLAUSES + if (cls == &impl) + resetimpl (); +#endif + if (!forced) + return; + + assign_forced (forced, reason); + v = LIT2VAR (forced); +} + +static void +inc_lreduce (void) +{ +#ifdef STATS + inclreduces++; +#endif + lreduce *= FREDUCE; + lreduce /= 100; + report (1, '+'); +} + +static void +backtrack (void) +{ + unsigned new_level; + Cls * cls; + + conflicts++; + LOG (fprintf (out, "%sconflict ", prefix); dumpclsnl (conflict)); + + analyze (); + new_level = drive (); + // TODO: why not? assert (new_level != 1 || (ahead - added) == 2); + cls = add_simplified_clause (1); + undo (new_level); + force (cls); + + if ( +#ifndef NFL + !simplifying && +#endif + !--lreduceadjustcnt) + { + lreduceadjustinc *= 15; + lreduceadjustinc /= 10; + lreduceadjustcnt = lreduceadjustinc; + inc_lreduce (); + } + + if (verbosity >= 4 && !(conflicts % 1000)) + report (4, 'C'); +} + +static void +inc_cinc (void) +{ + cinc = mulflt (cinc, fcinc); + if (lcinc < cinc) + crescore (); +} + +static void +incincs (void) +{ + inc_vinc (); + inc_cinc (); +#ifdef VISCORES + viscores (); +#endif +} + +static void +disconnect_clause (Cls * cls) +{ + assert (cls->connected); + + if (cls->size > 2) + { + if (cls->learned) + { + assert (nlclauses > 0); + nlclauses--; + + assert (llits >= cls->size); + llits -= cls->size; + } + else + { + assert (noclauses > 0); + noclauses--; + + assert (olits >= cls->size); + olits -= cls->size; + } + } + +#ifndef NDEBUG + cls->connected = 0; +#endif +} + +static int +clause_is_toplevel_satisfied (Cls * cls) +{ + Lit *lit, **p, **eol = end_of_lits (cls); + Var *v; + + for (p = cls->lits; p < eol; p++) + { + lit = *p; + if (lit->val == TRUE) + { + v = LIT2VAR (lit); + if (!v->level) + return 1; + } + } + + return 0; +} + +static int +collect_clause (Cls * cls) +{ + assert (cls->collect); + cls->collect = 0; + +#ifdef TRACE + assert (!cls->collected); + cls->collected = 1; +#endif + disconnect_clause (cls); + +#ifdef TRACE + if (trace && (!cls->learned || cls->used)) + return 0; +#endif + delete_clause (cls); + + return 1; +} + +static size_t +collect_clauses (void) +{ + Cls *cls, **p, **q, * next; + Lit * lit, * eol; + size_t res; + Var * v; + int i; + + res = current_bytes; + + eol = lits + 2 * max_var + 1; + for (lit = lits + 2; lit <= eol; lit++) + { + for (i = 0; i <= 1; i++) + { + if (i) + { +#ifdef NO_BINARY_CLAUSES + Ltk * lstk = LIT2IMPLS (lit); + Lit ** r, ** s; + r = lstk->start; + for (s = r; s < lstk->start + lstk->count; s++) + { + Lit * other = *s; + Var *v = LIT2VAR (other); + if (v->level || other->val != TRUE) + *r++ = other; + } + lstk->count = r - lstk->start; + continue; +#else + p = LIT2IMPLS (lit); +#endif + } + else + p = LIT2HTPS (lit); + + for (cls = *p; cls; cls = next) + { + q = cls->next; + if (cls->lits[0] != lit) + q++; + + next = *q; + if (cls->collect) + *p = next; + else + p = q; + } + } + } + +#ifndef NDSC + for (lit = lits + 2; lit <= eol; lit++) + { + p = LIT2DHTPS (lit); + while ((cls = *p)) + { + Lit * other = cls->lits[0]; + if (other == lit) + { + q = cls->next + 1; + } + else + { + assert (cls->lits[1] == lit); + q = cls->next; + } + + if (cls->collect) + *p = *q; + else + p = q; + } + } +#endif + + for (v = vars + 1; v <= vars + max_var; v++) + { + cls = v->reason; + if (!cls) + continue; + +#ifdef NO_BINARY_CLAUSES + if (ISLITREASON (cls)) + continue; +#endif + if (cls->collect) + v->reason = 0; + } + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + + if (!cls) + continue; + + if (!cls->collect) + continue; + + if (collect_clause (cls)) + *p = 0; + } + +#ifdef TRACE + if (!trace) +#endif + { + q = oclauses; + for (p = q; p < ohead; p++) + if ((cls = *p)) + *q++ = cls; + ohead = q; + + q = lclauses; + for (p = q; p < lhead; p++) + if ((cls = *p)) + *q++ = cls; + lhead = q; + } + + assert (current_bytes <= res); + res -= current_bytes; + recycled += res; + + LOG (fprintf (out, "%scollected %ld bytes\n", prefix, res)); + + return res; +} + +static int +need_to_reduce (void) +{ + return nlclauses >= reduce_limit_on_lclauses (); +} + +#ifdef NLUBY + +static void +inc_drestart (void) +{ + drestart *= FRESTART; + drestart /= 100; + + if (drestart >= MAXRESTART) + drestart = MAXRESTART; +} + +static void +inc_ddrestart (void) +{ + ddrestart *= FRESTART; + ddrestart /= 100; + + if (ddrestart >= MAXRESTART) + ddrestart = MAXRESTART; +} + +#else + +static int +luby (int i) +{ + int k; + for (k = 1; k < 32; k++) + if (i == (1 << k) - 1) + return 1 << (k - 1); + + for (k = 1;; k++) + if ((1 << (k - 1)) <= i && i < (1 << k) - 1) + return luby (i - (1 << (k-1)) + 1); +} + +#endif + +#ifndef NLUBY +static void +inc_lrestart (int skip) +{ + unsigned delta; + + delta = 100 * luby (++lubycnt); + lrestart = conflicts + delta; + + if (waslubymaxdelta) + report (1, skip ? 'N' : 'R'); + else + report (2, skip ? 'n' : 'r'); + + if (delta > lubymaxdelta) + { + lubymaxdelta = delta; + waslubymaxdelta = 1; + } + else + waslubymaxdelta = 0; +} +#endif + +static void +init_restart (void) +{ +#ifdef NLUBY + /* TODO: why is it better in incremental usage to have smaller initial + * outer restart interval? + */ + ddrestart = calls > 1 ? MINRESTART : 1000; + drestart = MINRESTART; + lrestart = conflicts + drestart; +#else + lubycnt = 0; + lubymaxdelta = 0; + waslubymaxdelta = 0; + inc_lrestart (0); +#endif +} + +static void +restart (void) +{ + int skip; +#ifdef NLUBY + char kind; + int outer; + + inc_drestart (); + outer = (drestart >= ddrestart); + + if (outer) + skip = very_high_agility (); + else + skip = high_agility (); +#else + skip = medium_agility (); +#endif + +#ifdef STATS + if (skip) + skippedrestarts++; +#endif + + assert (conflicts >= lrestart); + + if (!skip) + { + restarts++; + assert (level > 1); + LOG (fprintf (out, "%srestart %u\n", prefix, restarts)); + undo (0); + } + +#ifdef NLUBY + if (outer) + { + kind = skip ? 'N' : 'R'; + inc_ddrestart (); + drestart = MINRESTART; + } + else if (skip) + { + kind = 'n'; + } + else + { + kind = 'r'; + } + + assert (drestart <= MAXRESTART); + lrestart = conflicts + drestart; + assert (lrestart > conflicts); + + report (outer ? 1 : 2, kind); +#else + inc_lrestart (skip); +#endif +} + +inline static void +assign_decision (Lit * lit) +{ + assert (!conflict); + + level++; + + LOG (fprintf (out, "%snew level %u\n", prefix, level)); + LOG (fprintf (out, + "%sassign %d at level %d <= DECISION\n", + prefix, lit2int (lit), level)); + + assign (lit, 0); +} + +#ifndef NFL + +static int +lit_has_binary_clauses (Lit * lit) +{ +#ifdef NO_BINARY_CLAUSES + Ltk* lstk = LIT2IMPLS (lit); + return lstk->count != 0; +#else + return *LIT2IMPLS (lit) != 0; +#endif +} + +static void +flbcp (void) +{ +#ifdef STATS + unsigned long long propagaions_before_bcp = propagations; +#endif + bcp (); +#ifdef STATS + flprops += propagations - propagaions_before_bcp; +#endif +} + +inline static int +cmp_inverse_rnk (Rnk * a, Rnk * b) +{ + return -cmp_rnk (a, b); +} + +inline static Flt +rnk2jwh (Rnk * r) +{ + Flt res, sum, pjwh, njwh; + Lit * plit, * nlit; + + plit = RNK2LIT (r); + nlit = plit + 1; + + pjwh = *LIT2JWH (plit); + njwh = *LIT2JWH (nlit); + + res = mulflt (pjwh, njwh); + + sum = addflt (pjwh, njwh); + sum = mulflt (sum, base2flt (1, -10)); + res = addflt (res, sum); + + return res; +} + +static int +cmp_inverse_jwh_rnk (Rnk * r, Rnk * s) +{ + Flt a = rnk2jwh (r); + Flt b = rnk2jwh (s); + int res = cmpflt (a, b); + + if (res) + return -res; + + return cmp_inverse_rnk (r, s); +} + +static void +faillits (void) +{ + unsigned i, j, old_trail_count, common, saved_count; + unsigned new_saved_size, oldladded = ladded; + unsigned long long limit, delta; + Lit * lit, * other, * pivot; + int new_trail_count; + Rnk * r, ** p, ** q; + Var * v; + + if (heap + 1 >= hhead) + return; + + if (propagations < fllimit) + return; + + flcalls++; +#ifdef STATSA + flrounds++; +#endif + delta = propagations/10; + if (delta >= 100*1000*1000) delta = 100*1000*1000; + else if (delta <= 100*1000) delta = 100*1000; + + limit = propagations + delta; + fllimit = propagations; + + assert (!level); + assert (simplifying); + + if (flcalls <= 1) + sort (Rnk *, cmp_inverse_jwh_rnk, heap + 1, hhead - (heap + 1)); + else + sort (Rnk *, cmp_inverse_rnk, heap + 1, hhead - (heap + 1)); + + i = 1; /* NOTE: heap starts at position '1' */ + + while (propagations < limit) + { + if (heap + i == hhead) + { + if (ladded == oldladded) + break; + + i = 1; +#ifdef STATS + flrounds++; +#endif + oldladded = ladded; + } + + assert (heap + i < hhead); + + r = heap[i++]; + lit = RNK2LIT (r); + + if (lit->val) + continue; + + if (!lit_has_binary_clauses (NOTLIT (lit))) + { +#ifdef STATS + flskipped++; +#endif + continue; + } + +#ifdef STATS + fltried++; +#endif + LOG (fprintf (out, "%strying %d as failed literal\n", + prefix, lit2int (lit))); + + assign_decision (lit); + old_trail_count = thead - trail; + flbcp (); + + if (conflict) + { +EXPLICITLY_FAILED_LITERAL: + LOG (fprintf (out, "%sfound explicitly failed literal %d\n", + prefix, lit2int (lit))); + + failedlits++; + efailedlits++; + + backtrack (); + flbcp (); + + if (!conflict) + continue; + +CONTRADICTION: + assert (!level); + backtrack (); + assert (mtcls); + + goto RETURN; + } + + if (propagations >= limit) + { + undo (0); + break; + } + + lit = NOTLIT (lit); + + if (!lit_has_binary_clauses (NOTLIT (lit))) + { +#ifdef STATS + flskipped++; +#endif + undo (0); + continue; + } + +#ifdef STATS + fltried++; +#endif + LOG (fprintf (out, "%strying %d as failed literals\n", + prefix, lit2int (lit))); + + new_trail_count = thead - trail; + saved_count = new_trail_count - old_trail_count; + + if (saved_count > saved_size) + { + new_saved_size = saved_size ? 2 * saved_size : 1; + while (saved_count > new_saved_size) + new_saved_size *= 2; + + RESIZEN (saved, saved_size, new_saved_size); + saved_size = new_saved_size; + } + + for (j = 0; j < saved_count; j++) + { + other = trail[old_trail_count + j]; + saved[j] = trail[old_trail_count + j]; + } + + undo (0); + + assign_decision (lit); + flbcp (); + + if (conflict) + goto EXPLICITLY_FAILED_LITERAL; + + pivot = (thead - trail <= new_trail_count) ? lit : NOTLIT (lit); + + common = 0; + for (j = 0; j < saved_count; j++) + if ((other = saved[j])->val == TRUE) + saved[common++] = other; + + undo (0); + + LOG (if (common) + fprintf (out, + "%sfound %d literals implied by %d and %d\n", + prefix, common, + lit2int (NOTLIT (lit)), lit2int (lit))); + + for (j = 0; + j < common + /* TODO: For some Velev benchmarks, extracting the common implicit + * failed literals took quite some time. This needs to be fixed by + * a dedicated analyzer. Up to then we bound the number of + * propagations in this loop as well. + */ + && propagations < limit + delta + ; j++) + { + other = saved[j]; + + if (other->val == TRUE) + continue; + + assert (!other->val); + + LOG (fprintf (out, + "%sforcing %d as forced implicitly failed literal\n", + prefix, lit2int (other))); + + assert (pivot != NOTLIT (other)); + assert (pivot != other); + + assign_decision (NOTLIT (other)); + flbcp (); + + assert (level == 1); + + if (conflict) + { + backtrack (); + assert (!level); + } + else + { + assign_decision (pivot); + flbcp (); + + backtrack (); + + if (level) + { + assert (level == 1); + + flbcp (); + + if (conflict) + { + backtrack (); + assert (!level); + } + else + { + assign_decision (NOTLIT (pivot)); + flbcp (); + backtrack (); + + if (level) + { + assert (level == 1); + flbcp (); + + if (!conflict) + { +#ifdef STATS + floopsed++; +#endif + undo (0); + continue; + } + + backtrack (); + } + + assert (!level); + } + + assert (!level); + } + } + assert (!level); + flbcp (); + + failedlits++; + ifailedlits++; + + if (conflict) + goto CONTRADICTION; + } + } + + fllimit += 9 * (propagations - fllimit); /* 10% for failed literals */ + +RETURN: + + /* First flush top level assigned literals. Those are prohibited from + * being pushed up the heap during 'faillits' since 'simplifying' is set. + */ + assert (heap < hhead); + for (p = q = heap + 1; p < hhead; p++) + { + r = *p; + v = vars + (r - rnks); + lit = RNK2LIT (r); + if (lit->val) + r->pos = 0; + else + *q++ = r; + } + + /* Then resort with respect to EVSIDS score and fix positions. + */ + sort (Rnk *, cmp_inverse_rnk, heap + 1, hhead - (heap + 1)); + for (p = heap + 1; p < hhead; p++) + (*p)->pos = p - heap; +} + +#endif + +static void +simplify (void) +{ + unsigned collect, delta; + size_t bytes_collected; + Cls **p, *cls; + + assert (!mtcls); + assert (!satisfied ()); + assert (lsimplify <= propagations); + assert (fsimplify <= fixed); + +#ifndef NFL + if (level) + undo (0); + + simplifying = 1; + faillits (); + simplifying = 0; + + if (mtcls) + return; +#endif + + collect = 0; + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + + if (cls->locked) + continue; + + assert (!cls->collect); + if (clause_is_toplevel_satisfied (cls)) + { + mark_clause_to_be_collected (cls); + collect++; + } + } + + if (collect) + { + bytes_collected = collect_clauses (); +#ifdef STATS + srecycled += bytes_collected; +#endif + } + + delta = 10 * (olits + llits) + 100000; + if (delta > 2000000) + delta = 2000000; + lsimplify = propagations + delta; + fsimplify = fixed; + simps++; + + report (1, 's'); +} + +static void +iteration (void) +{ + assert (!level); + assert (bcp_queue_is_empty ()); + assert (isimplify < fixed); + + iterations++; + report (2, 'i'); +#ifdef NLUBY + drestart = MINRESTART; + lrestart = conflicts + drestart; +#else + init_restart (); +#endif + isimplify = fixed; +} + +static int +cmp_activity (Cls * c, Cls * d) +{ + Act a; + Act b; + + assert (c->learned); + assert (d->learned); + + a = *CLS2ACT (c); + b = *CLS2ACT (d); + + if (a < b) + return -1; + + if (b < a) + return 1; + + /* Prefer shorter clauses. + */ + if (c->size < d->size) + return 1; + + if (c->size > d->size) + return -1; + + return 0; +} + +static void +reduce (unsigned percentage) +{ + unsigned rcount, lcollect, collect, target, ld; + size_t bytes_collected; + Cls **p, *cls; + Act minact; + + lastreduceconflicts = conflicts; + + assert (percentage <= 100); + LOG (fprintf (out, + "%sreducing %u%% learned clauses\n", + prefix, percentage)); + + while (nlclauses - llocked > (unsigned)(eor - resolved)) + ENLARGE (resolved, rhead, eor); + + collect = 0; + lcollect = 0; + + for (p = ((fsimplify < fixed) ? SOC : lclauses); p != EOC; p = NXC (p)) + { + cls = *p; + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + + if (cls->locked) + continue; + + assert (!cls->collect); + if (fsimplify < fixed && clause_is_toplevel_satisfied (cls)) + { + mark_clause_to_be_collected (cls); + collect++; + + if (cls->learned && cls->size > 2) + lcollect++; + + continue; + } + + if (cls->fixed) + continue; + + if (!cls->learned) + continue; + + if (cls->size <= 2) + continue; + + assert (rhead < eor); + *rhead++ = cls; + } + assert (rhead <= eor); + + fsimplify = fixed; + + rcount = rhead - resolved; + sort (Cls *, cmp_activity, resolved, rcount); + + assert (nlclauses >= lcollect); + target = nlclauses - lcollect + 1; + + for (ld = 1; ld < 32 && ((unsigned) (1 << ld)) < target; ld++) + ; + minact = mulflt (cinc, base2flt (1, -ld)); + + target = (percentage * target + 99) / 100; + + if (target >= rcount) + { + target = rcount; + } + else if (*CLS2ACT (resolved[target]) < minact) + { + /* If the distribution of clause activities is skewed and the median + * is actually below the maximum average activity, then we collect all + * clauses below this activity. + */ + while (++target < rcount && *CLS2ACT (resolved[target]) < minact) + ; + } + else + { + while (target > 0 && + !cmp_activity (resolved[target - 1], resolved[target])) + target--; + } + + rhead = resolved + target; + while (rhead > resolved) + { + cls = *--rhead; + mark_clause_to_be_collected (cls); + + collect++; + if (cls->learned && cls->size > 2) /* just for consistency */ + lcollect++; + } + + if (collect) + { + reductions++; + bytes_collected = collect_clauses (); +#ifdef STATS + rrecycled += bytes_collected; +#endif + report (2, '-'); + } + + if (!lcollect) + inc_lreduce (); /* avoid dead lock */ + + assert (rhead == resolved); +} + +static void +init_reduce (void) +{ + lreduce = loadded / 2; + + if (lreduce < 100) + lreduce = 100; + +#if 0 + if (lreduce > 10000) + lreduce = 10000; +#endif + + if (verbosity) + fprintf (out, + "%s\n%sinitial reduction limit %u clauses\n%s\n", + prefix, prefix, lreduce, prefix); +} + +static unsigned +rng (void) +{ + unsigned res = srng; + srng *= 1664525u; + srng += 1013904223u; + NOLOG (fprintf (out, "%srng () = %u\n", prefix, res)); + return res; +} + +static unsigned +rrng (unsigned low, unsigned high) +{ + unsigned long long tmp; + unsigned res, elements; + assert (low <= high); + elements = high - low + 1; + tmp = rng (); + tmp *= elements; + tmp >>= 32; + tmp += low; + res = tmp; + NOLOG (fprintf (out, "%srrng (%u, %u) = %u\n", prefix, low, high, res)); + assert (low <= res); + assert (res <= high); + return res; +} + +static Lit * +decide_phase (Lit * lit) +{ + Lit * not_lit = NOTLIT (lit); + Var *v = LIT2VAR (lit); + + assert (LIT2SGN (lit) > 0); + if (!v->assigned) + { +#ifdef STATS + staticphasedecisions++; +#endif + if (defaultphase == 1) + { + /* assign to TRUE */ + } + else if (defaultphase == 0) + { + /* assign to FALSE */ + lit = not_lit; + } + else if (defaultphase == 3) + { + /* randomly assign default phase */ + if (rrng (1, 2) != 2) + lit = not_lit; + } + else if (*LIT2JWH(lit) <= *LIT2JWH (not_lit)) + { + /* assign to FALSE (Jeroslow-Wang says there are more short + * clauses with negative occurence of this variable, so satisfy + * those, to minimize BCP) + */ + lit = not_lit; + } + else + { + /* assign to TRUE (... but strictly more positive occurrences) */ + } + } + else + { + /* repeat last phase: phase saving heuristic */ + + if (v->phase) + { + /* assign to TRUE (last phase was TRUE as well) */ + } + else + { + /* assign to FALSE (last phase was FALSE as well) */ + lit = not_lit; + } + } + + return lit; +} + +static unsigned +gcd (unsigned a, unsigned b) +{ + unsigned tmp; + + assert (a); + assert (b); + + if (a < b) + { + tmp = a; + a = b; + b = tmp; + } + + while (b) + { + assert (a >= b); + tmp = b; + b = a % b; + a = tmp; + } + + return a; +} + +static Lit * +rdecide (void) +{ + unsigned idx, delta, spread; + Lit * res; + + spread = RDECIDE; + if (rrng (1, spread) != 2) + return 0; + + assert (1 <= max_var); + idx = rrng (1, max_var); + res = int2lit (idx); + + if (res->val != UNDEF) + { + delta = rrng (1, max_var); + while (gcd (delta, max_var) != 1) + delta--; + + assert (1 <= delta); + assert (delta <= max_var); + + do { + idx += delta; + if (idx > max_var) + idx -= max_var; + res = int2lit (idx); + } while (res->val != UNDEF); + } + +#ifdef STATS + rdecisions++; +#endif + res = decide_phase (res); + LOG (fprintf (out, "%srdecide %d\n", prefix, lit2int (res))); + + return res; +} + +static Lit * +sdecide (void) +{ + Rnk *r, * tmp; + Lit *res; + + for (;;) + { + r = htop (); + res = RNK2LIT (r); + if (res->val == UNDEF) break; + tmp = hpop (); + assert (tmp == r); + NOLOG (fprintf (out, + "%shpop %u %u %u\n", + prefix, r - rnks, + FLTMANTISSA(r->score), + FLTEXPONENT(r->score))); + } + +#ifdef STATS + sdecisions++; +#endif + res = decide_phase (res); + + LOG (fprintf (out, "%ssdecide %d\n", prefix, lit2int (res))); + + return res; +} + +static Lit * +adecide (void) +{ + Lit *lit; + Var * v; + + assert (als < alshead); + assert (!failed_assumption); + + while (alstail < alshead) + { + lit = *alstail++; + + if (lit->val == FALSE) + { + failed_assumption = lit; + v = LIT2VAR (lit); + + use_var (v); + + LOG (fprintf (out, "%sfirst failed assumption %d\n", + prefix, lit2int (failed_assumption))); + fanalyze (); + return 0; + } + + if (lit->val == TRUE) + { + v = LIT2VAR (lit); + if (v->level > adecidelevel) + adecidelevel = v->level; + continue; + } + +#ifdef STATS + assumptions++; +#endif + LOG (fprintf (out, "%sadecide %d\n", prefix, lit2int (lit))); + adecidelevel = level + 1; + + return lit; + } + + return 0; +} + +static void +decide (void) +{ + Lit * lit; + + assert (!satisfied ()); + assert (!conflict); + + if (alstail < alshead && (lit = adecide ())) + ; + else if (failed_assumption) + return; + else if (satisfied ()) + return; + else if (!(lit = rdecide ())) + lit = sdecide (); + + assert (lit); + assign_decision (lit); + + levelsum += level; + decisions++; +} + +static int +sat (int l) +{ + int count = 0, backtracked; + + if (!conflict) + bcp (); + + if (conflict) + backtrack (); + + if (mtcls) + return PICOSAT_UNSATISFIABLE; + + if (satisfied ()) + goto SATISFIED; + + if (lsimplify <= propagations) + simplify (); + + if (mtcls) + return PICOSAT_UNSATISFIABLE; + + if (satisfied ()) + goto SATISFIED; + + init_restart (); + + isimplify = fixed; + backtracked = 0; + + for (;;) + { + if (!conflict) + bcp (); + + if (conflict) + { + incincs (); + backtrack (); + + if (mtcls) + return PICOSAT_UNSATISFIABLE; + backtracked = 1; + continue; + } + + if (satisfied ()) + { +SATISFIED: +#ifndef NDEBUG + original_clauses_satisfied (); + assumptions_satisfied (); +#endif + return PICOSAT_SATISFIABLE; + } + + if (backtracked) + { + backtracked = 0; + if (!level && isimplify < fixed) + iteration (); + } + + if (l >= 0 && count >= l) /* decision limit reached ? */ + return PICOSAT_UNKNOWN; + + if (propagations >= lpropagations)/* propagation limit reached ? */ + return PICOSAT_UNKNOWN; + +#ifndef NADC + if (!adodisabled && adoconflicts >= adoconflictlimit) + { + assert (bcp_queue_is_empty ()); + return PICOSAT_UNKNOWN; + } +#endif + + if (fsimplify < fixed && lsimplify <= propagations) + { + simplify (); + if (!bcp_queue_is_empty ()) + continue; +#ifndef NFL + if (mtcls) + return PICOSAT_UNSATISFIABLE; + + if (satisfied ()) + return PICOSAT_SATISFIABLE; + + assert (!level); +#endif + } + + if (!lreduce) + init_reduce (); + + if (need_to_reduce ()) + reduce (50); + + if (conflicts >= lrestart && level > 2) + restart (); + + decide (); + if (failed_assumption) + return PICOSAT_UNSATISFIABLE; + count++; + } +} + +static void +rebias (void) +{ + Cls ** p, * c; + Var * v; + + for (v = vars + 1; v <= vars + max_var; v++) + v->assigned = 0; + + memset (jwh, 0, 2 * (max_var + 1) * sizeof *jwh); + + for (p = oclauses; p < ohead; p++) + { + c = *p; + + if (!c) + continue; + + if (c->learned) + continue; + + incjwh (c); + } +} + +#ifdef TRACE + +static unsigned +core (void) +{ + unsigned idx, prev, this, delta, i, lcore, vcore; + unsigned *stack, *shead, *eos; + Lit **q, **eol, *lit; + Cls *cls, *reason; + Znt *p, byte; + Zhn *zhain; + Var *v; + + assert (trace); + + assert (mtcls || failed_assumption); + if (ocore >= 0) + return ocore; + + lcore = ocore = vcore = 0; + + stack = shead = eos = 0; + ENLARGE (stack, shead, eos); + + if (mtcls) + { + idx = CLS2IDX (mtcls); + *shead++ = idx; + } + else + { + assert (failed_assumption); + v = LIT2VAR (failed_assumption); + reason = v->reason; + assert (reason); + idx = CLS2IDX (reason); + *shead++ = idx; + } + + while (shead > stack) + { + idx = *--shead; + zhain = IDX2ZHN (idx); + + if (zhain) + { + if (zhain->core) + continue; + + zhain->core = 1; + lcore++; + + cls = IDX2CLS (idx); + if (cls) + { + assert (!cls->core); + cls->core = 1; + } + + i = 0; + delta = 0; + prev = 0; + for (p = zhain->znt; (byte = *p); p++, i += 7) + { + delta |= (byte & 0x7f) << i; + if (byte & 0x80) + continue; + + this = prev + delta; + assert (prev < this); /* no overflow */ + + if (shead == eos) + ENLARGE (stack, shead, eos); + *shead++ = this; + + prev = this; + delta = 0; + i = -7; + } + } + else + { + cls = IDX2CLS (idx); + + assert (cls); + assert (!cls->learned); + + if (cls->core) + continue; + + cls->core = 1; + ocore++; + + eol = end_of_lits (cls); + for (q = cls->lits; q < eol; q++) + { + lit = *q; + v = LIT2VAR (lit); + if (v->core) + continue; + + v->core = 1; + vcore++; + + if (!failed_assumption) continue; + if (lit != failed_assumption) continue; + + reason = v->reason; + if (!reason) continue; + if (reason->core) continue; + + idx = CLS2IDX (reason); + if (shead == eos) + ENLARGE (stack, shead, eos); + *shead++ = idx; + } + } + } + + DELETEN (stack, eos - stack); + + if (verbosity) + fprintf (out, + "%s%u core variables out of %u (%.1f%%)\n" + "%s%u core original clauses out of %u (%.1f%%)\n" + "%s%u core learned clauses out of %u (%.1f%%)\n", + prefix, vcore, max_var, PERCENT (vcore, max_var), + prefix, ocore, oadded, PERCENT (ocore, oadded), + prefix, lcore, ladded, PERCENT (lcore, ladded)); + + return ocore; +} + +static void +write_unsigned (unsigned d, FILE * file) +{ + static char write_unsigned_buffer[20]; + unsigned tmp; + char * res; + + assert (sizeof d <= 4); + + res = write_unsigned_buffer + sizeof write_unsigned_buffer; + *--res = 0; + tmp = d; + do { + assert (res > write_unsigned_buffer); + *--res = '0' + (tmp % 10); + tmp /= 10; + } while (tmp); + + fputs (res, file); +} + +static void +trace_lits (Cls * cls, FILE * file) +{ + Lit **p, **eol = end_of_lits (cls); + + assert (cls); + assert (cls->core); + + for (p = cls->lits; p < eol; p++) + { + write_int (LIT2INT (*p), file); + fputc (' ', file); + } + + fputc ('0', file); +} + +static void +write_idx (unsigned idx, FILE * file) +{ + write_unsigned (EXPORTIDX (idx), file); +} + +static void +trace_clause (unsigned idx, Cls * cls, FILE * file, int fmt) +{ + assert (cls); + assert (cls->core); + assert (fmt == RUP_TRACE_FMT || !cls->learned); + assert (CLS2IDX (cls) == idx); + + if (fmt != RUP_TRACE_FMT) + { + write_idx (idx, file); + fputc (' ', file); + } + + trace_lits (cls, file); + + if (fmt != RUP_TRACE_FMT) + fputs (" 0", file); + + fputc ('\n', file); +} + +static void +trace_zhain (unsigned idx, Zhn * zhain, FILE * file, int fmt) +{ + unsigned prev, this, delta, i; + Znt *p, byte; + Cls * cls; + + assert (zhain); + assert (zhain->core); + + write_idx (idx, file); + fputc (' ', file); + + if (fmt == EXTENDED_TRACECHECK_TRACE_FMT) + { + cls = IDX2CLS (idx); + assert (cls); + trace_lits (cls, file); + } + else + { + assert (fmt == COMPACT_TRACECHECK_TRACE_FMT); + putc ('*', file); + } + + i = 0; + delta = 0; + prev = 0; + + for (p = zhain->znt; (byte = *p); p++, i += 7) + { + delta |= (byte & 0x7f) << i; + if (byte & 0x80) + continue; + + this = prev + delta; + + putc (' ', file); + write_idx (this, file); + + prev = this; + delta = 0; + i = -7; + } + + fputs (" 0\n", file); +} + +static void +write_core (FILE * file) +{ + Lit **q, **eol; + Cls **p, *cls; + + fprintf (file, "p cnf %u %u\n", max_var, core ()); + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + + if (!cls || cls->learned || !cls->core) + continue; + + eol = end_of_lits (cls); + for (q = cls->lits; q < eol; q++) + { + write_int (LIT2INT (*q), file); + fputc (' ', file); + } + + fputs ("0\n", file); + } +} + +#endif + +static void +write_trace (FILE * file, int fmt) +{ +#ifdef TRACE + Cls *cls, ** p; + Zhn *zhain; + unsigned i; + + core (); + + if (fmt == RUP_TRACE_FMT) + { + rupvariables = picosat_variables (), + rupclauses = picosat_added_original_clauses (); + write_rup_header (file); + } + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + + if (oclauses <= p && p < eoo) + { + i = OIDX2IDX (p - oclauses); + assert (!cls || CLS2IDX (cls) == i); + } + else + { + assert (lclauses <= p && p < eol); + i = LIDX2IDX (p - lclauses); + } + + zhain = IDX2ZHN (i); + + if (zhain) + { + if (zhain->core) + { + if (fmt == RUP_TRACE_FMT) + trace_clause (i, cls, file, fmt); + else + trace_zhain (i, zhain, file, fmt); + } + } + else if (cls) + { + if (fmt != RUP_TRACE_FMT && cls) + { + if (cls->core) + trace_clause (i, cls, file, fmt); + } + } + } +#else + (void) file; + (void) fmt; +#endif +} + +static void +write_core_wrapper (FILE * file, int fmt) +{ + (void) fmt; +#ifdef TRACE + write_core (file); +#else + (void) file; +#endif +} + +static Lit * +import_lit (int lit) +{ + ABORTIF (lit == INT_MIN, "API usage: INT_MIN literal"); + + while (abs (lit) > (int) max_var) + inc_max_var (); + + return int2lit (lit); +} + +#ifdef TRACE +static void +reset_core (void) +{ + Cls ** p, * c; + Zhn ** q, * z; + unsigned i; + + for (i = 1; i <= max_var; i++) + vars[i].core = 0; + + for (p = SOC; p != EOC; p = NXC (p)) + if ((c = *p)) + c->core = 0; + + for (q = zhains; q != zhead; q++) + if ((z = *q)) + z->core = 0; + + ocore = -1; +} +#endif + +static void +reset_assumptions (void) +{ + Lit ** p; + + failed_assumption = 0; + + if (extracted_all_failed_assumptions) + { + for (p = als; p < alshead; p++) + LIT2VAR (*p)->failed = 0; + + extracted_all_failed_assumptions = 0; + } + + alstail = alshead = als; + adecidelevel = 0; +} + +static void +check_ready (void) +{ + ABORTIF (state == RESET, "API usage: uninitialized"); +} + +static void +check_sat_state (void) +{ + ABORTIF (state != SAT, "API usage: expected to be in SAT state"); +} + +static void +check_unsat_state (void) +{ + ABORTIF (state != UNSAT, "API usage: expected to be in UNSAT state"); +} + +static void +check_sat_or_unsat_or_unknown_state (void) +{ + ABORTIF (state != SAT && state != UNSAT && state != UNKNOWN, + "API usage: expected to be in SAT, UNSAT, or UNKNOWN state"); +} + +static void +reset_incremental_usage (void) +{ + unsigned num_non_false; + Lit * lit, ** q; + + check_sat_or_unsat_or_unknown_state (); + + LOG (fprintf (out, "%sRESET incremental usage\n", prefix)); + + if (level) + undo (0); + + reset_assumptions (); + + if (conflict) + { + num_non_false = 0; + for (q = conflict->lits; q < end_of_lits (conflict); q++) + { + lit = *q; + if (lit->val != FALSE) + num_non_false++; + } + + // assert (num_non_false >= 2); // TODO: why this assertion? +#ifdef NO_BINARY_CLAUSES + if (conflict == &cimpl) + resetcimpl (); +#endif +#ifndef NADC + if (conflict == adoconflict) + resetadoconflict (); +#endif + conflict = 0; + } + +#ifdef TRACE + reset_core (); +#endif + + saved_flips = flips; + min_flipped = UINT_MAX; + saved_max_var = max_var; + + state = READY; +} + +static void +enter (void) +{ + if (nentered++) + return; + + check_ready (); + entered = picosat_time_stamp (); +} + +static void +leave (void) +{ + assert (nentered); + if (--nentered) + return; + + sflush (); +} + +static void +check_trace_support_and_execute (FILE * file, void (*f)(FILE*,int), int fmt) +{ + check_ready (); + check_unsat_state (); +#ifdef TRACE + ABORTIF (!trace, "API usage: tracing disabled"); + enter (); + f (file, fmt); + leave (); +#else + (void) file; + (void) fmt; + (void) f; + ABORT ("compiled without trace support"); +#endif +} + +static void +extract_all_failed_assumptions (void) +{ + Lit ** p, ** eol; + Var * v, * u; + int pos; + Cls * c; + + assert (!extracted_all_failed_assumptions); + + assert (failed_assumption); + assert (mhead == marked); + + if (marked == eom) + ENLARGE (marked, mhead, eom); + + v = LIT2VAR (failed_assumption); + mark_var (v); + pos = 0; + + while (pos < mhead - marked) + { + v = marked[pos++]; + assert (v->mark); + c = var2reason (v); + if (!c) + continue; + eol = end_of_lits (c); + for (p = c->lits; p < eol; p++) + { + u = LIT2VAR (*p); + if (!u->mark) + mark_var (u); + } + } + + for (p = als; p < alshead; p++) + { + u = LIT2VAR (*p); + if (!u->mark) continue; + u->failed = 1; + LOG (fprintf (out, "%sfailed assumption %d\n", prefix, lit2int (*p))); + } + + while (mhead > marked) + (*--mhead)->mark = 0; + + extracted_all_failed_assumptions = 1; +} + +const char * +picosat_copyright (void) +{ + return "Copyright (c) 2006 - 2010 Armin Biere JKU Linz"; +} + +void +picosat_init (void) +{ + init (); +} + +void +picosat_adjust (int new_max_var) +{ + unsigned new_size_vars; + + enter (); + + new_max_var = abs (new_max_var); + new_size_vars = new_max_var + 1; + + if (size_vars < new_size_vars) + enlarge (new_size_vars); + + while (max_var < (unsigned) new_max_var) + inc_max_var (); + + leave (); +} + +int +picosat_inc_max_var (void) +{ + if (measurealltimeinlib) + enter (); + else + check_ready (); + + inc_max_var (); + + if (measurealltimeinlib) + leave (); + + return max_var; +} + +void +picosat_set_verbosity (int new_verbosity_level) +{ + check_ready (); + verbosity = new_verbosity_level; +} + +int +picosat_enable_trace_generation (void) +{ + int res = 0; + check_ready (); +#ifdef TRACE + ABORTIF (addedclauses, + "API usage: trace generation enabled after adding clauses"); + res = trace = 1; +#endif + return res; +} + +void +picosat_set_incremental_rup_file (FILE * rup_file, int m, int n) +{ + check_ready (); + assert (!rupstarted); + rup = rup_file; + rupvariables = m; + rupclauses = n; +} + +void +picosat_set_output (FILE * output_file) +{ + check_ready (); + out = output_file; +} + +void +picosat_measure_all_calls (void) +{ + check_ready (); + measurealltimeinlib = 1; +} + +void +picosat_set_prefix (const char * str) +{ + check_ready (); + new_prefix (str); +} + +void +picosat_set_seed (unsigned s) +{ + check_ready (); + srng = s; +} + +void +picosat_reset (void) +{ + check_ready (); + reset (); +} + +int +picosat_add (int int_lit) +{ + int res = oadded; + Lit *lit; + + if (measurealltimeinlib) + enter (); + else + check_ready (); + + ABORTIF (rup && rupstarted && oadded >= (unsigned)rupclauses, + "API usage: adding too many clauses after RUP header written"); +#ifndef NADC + ABORTIF (addingtoado, + "API usage: 'picosat_add' and 'picosat_add_ado_lit' mixed"); +#endif + if (state != READY) + reset_incremental_usage (); + + lit = import_lit (int_lit); + + if (int_lit) + add_lit (lit); + else + simplify_and_add_original_clause (); + + if (measurealltimeinlib) + leave (); + + return res; +} + +void +picosat_add_ado_lit (int external_lit) +{ +#ifndef NADC + Lit * internal_lit; + + if (measurealltimeinlib) + enter (); + else + check_ready (); + + if (state != READY) + reset_incremental_usage (); + + ABORTIF (!addingtoado && ahead > added, + "API usage: 'picosat_add' and 'picosat_add_ado_lit' mixed"); + + if (external_lit) + { + addingtoado = 1; + internal_lit = import_lit (external_lit); + add_lit (internal_lit); + } + else + { + addingtoado = 0; + add_ado (); + } + if (measurealltimeinlib) + leave (); +#else + (void) external_lit; + ABORT ("compiled without all different constraint support"); +#endif +} + +void +picosat_assume (int int_lit) +{ + Lit *lit; + + if (measurealltimeinlib) + enter (); + else + check_ready (); + + if (state != READY) + reset_incremental_usage (); + + lit = import_lit (int_lit); + if (alshead == eoals) + { + assert (alstail == als); + ENLARGE (als, alshead, eoals); + alstail = als; + } + + *alshead++ = lit; + LOG (fprintf (out, "%sassumption %d\n", prefix, int_lit)); + + if (measurealltimeinlib) + leave (); +} + +int +picosat_sat (int l) +{ + int res; + char ch; + + enter (); + + calls++; + LOG (fprintf (out, "%sSTART call %u\n", prefix, calls)); + + if (added < ahead) + { +#ifndef NADC + if (addingtoado) + ABORT ("API usage: incomplete all different constraint"); + else +#endif + ABORT ("API usage: incomplete clause"); + } + + if (state != READY) + reset_incremental_usage (); + + res = sat (l); + + assert (state == READY); + + switch (res) + { + case PICOSAT_UNSATISFIABLE: + ch = '0'; + state = UNSAT; + break; + case PICOSAT_SATISFIABLE: + ch = '1'; + state = SAT; + break; + default: + ch = '?'; + state = UNKNOWN; + break; + } + + if (verbosity) + { + report (1, ch); + rheader (); + } + + leave (); + LOG (fprintf (out, "%sEND call %u\n", prefix, calls)); + + last_sat_call_result = res; + + return res; +} + +int +picosat_res (void) +{ + return last_sat_call_result; +} + +int +picosat_deref (int int_lit) +{ + Lit *lit; + + check_ready (); + check_sat_state (); + ABORTIF (!int_lit, "API usage: can not deref zero literal"); + ABORTIF (mtcls, "API usage: deref after empty clause generated"); + +#ifdef STATS + derefs++; +#endif + + if (abs (int_lit) > (int) max_var) + return 0; + + lit = int2lit (int_lit); + + if (lit->val == TRUE) + return 1; + + if (lit->val == FALSE) + return -1; + + return 0; +} + +int +picosat_deref_toplevel (int int_lit) +{ + Lit *lit; + Var * v; + + check_ready (); + ABORTIF (!int_lit, "API usage: can not deref zero literal"); + ABORTIF (mtcls, "API usage: deref after empty clause generated"); + +#ifdef STATS + derefs++; +#endif + if (abs (int_lit) > (int) max_var) + return 0; + + lit = int2lit (int_lit); + + v = LIT2VAR (lit); + if (v->level > 0) + return 0; + + if (lit->val == TRUE) + return 1; + + if (lit->val == FALSE) + return -1; + + return 0; +} + +int +picosat_inconsistent (void) +{ + check_ready (); + return mtcls != 0; +} + +int +picosat_corelit (int int_lit) +{ + int res; + + check_ready (); + check_unsat_state (); + ABORTIF (!int_lit, "API usage: zero literal can not be in core"); + + assert (mtcls || failed_assumption); + + res = 0; + +#ifdef TRACE + { + ABORTIF (!trace, "tracing disabled"); + if (measurealltimeinlib) + enter (); + core (); + if (abs (int_lit) <= (int) max_var) + res = vars[abs (int_lit)].core; + assert (!res || failed_assumption || vars[abs (int_lit)].used); + if (measurealltimeinlib) + leave (); + } +#else + ABORT ("compiled without trace support"); +#endif + + return res; +} + +int +picosat_coreclause (int ocls) +{ + int res; + + check_ready (); + check_unsat_state (); + + ABORTIF (ocls < 0, "API usage: negative original clause index"); + ABORTIF (ocls >= (int)oadded, "API usage: original clause index exceeded"); + + assert (mtcls || failed_assumption); + + res = 0; + +#ifdef TRACE + { + Cls ** clsptr, * cls; + + ABORTIF (!trace, "tracing disabled"); + if (measurealltimeinlib) + enter (); + core (); + clsptr = oclauses + ocls; + assert (clsptr < ohead); + cls = *clsptr; + if (cls) + res = cls->core; + if (measurealltimeinlib) + leave (); + } +#else + ABORT ("compiled without trace support"); +#endif + + return res; +} + +int +picosat_failed_assumption (int int_lit) +{ + Lit * lit; + Var * v; + ABORTIF (!int_lit, "API usage: zero literal as assumption"); + check_ready (); + check_unsat_state (); + if (mtcls) + return 0; + assert (failed_assumption); + if (abs (int_lit) > (int) max_var) + return 0; + if (!extracted_all_failed_assumptions) + extract_all_failed_assumptions (); + lit = import_lit (int_lit); + v = LIT2VAR (lit); + return v->failed; +} + +const int * +picosat_failed_assumptions (void) +{ + Lit ** p, * lit; + Var * v; + int ilit; + + falshead = fals; + check_ready (); + check_unsat_state (); + if (!mtcls) + { + assert (failed_assumption); + if (!extracted_all_failed_assumptions) + extract_all_failed_assumptions (); + + for (p = als; p < alshead; p++) + { + lit = *p; + v = LIT2VAR (*p); + if (!v->failed) + continue; + ilit = LIT2INT (lit); + if (falshead == eofals) + ENLARGE (fals, falshead, eofals); + *falshead++ = ilit; + } + } + if (falshead == eofals) + ENLARGE (fals, falshead, eofals); + *falshead++ = 0; + return fals; +} + +static const char * enumstr (int i) { + int last = i % 10; + if (last == 1) return "st"; + if (last == 2) return "nd"; + if (last == 3) return "rd"; + return "th"; +} + +const int * +picosat_mus_assumptions (void * s, void (*cb)(void*,const int*), int fix) +{ + int i, j, ilit, len, oldlen, norig = alshead - als, nwork, * work, res; + signed char * redundant; + Lit ** p, * lit; + int failed; + Var * v; + + check_ready (); + check_unsat_state (); + len = 0; + if (!mtcls) + { + assert (failed_assumption); + if (!extracted_all_failed_assumptions) + extract_all_failed_assumptions (); + + for (p = als; p < alshead; p++) + if (LIT2VAR (*p)->failed) + len++; + } + + if (mass) + DELETEN (mass, szmass); + szmass = len + 1; + NEWN (mass, szmass); + + i = 0; + for (p = als; p < alshead; p++) + { + lit = *p; + v = LIT2VAR (lit); + if (!v->failed) + continue; + ilit = LIT2INT (lit); + assert (i < len); + mass[i++] = ilit; + } + assert (i == len); + mass[i] = 0; + if (verbosity) + fprintf (out, + "%sinitial set of failed assumptions of size %d out of %d (%.0f%%)\n", + prefix, len, norig, PERCENT (len, norig)); + if (cb) + cb (s, mass); + + nwork = len; + NEWN (work, nwork); + for (i = 0; i < len; i++) + work[i] = mass[i]; + + NEWN (redundant, nwork); + CLRN (redundant, nwork); + + for (i = 0; i < nwork; i++) + { + if (redundant[i]) + continue; + + if (verbosity > 1) + fprintf (out, + "%strying to drop %d%s assumption %d\n", + prefix, i, enumstr (i), work[i]); + for (j = 0; j < nwork; j++) + if (i != j && !redundant[j]) + picosat_assume (work[j]); + + res = picosat_sat (-1); + if (res == 10) + { + if (verbosity > 1) + fprintf (out, + "%sfailed to drop %d%s assumption %d\n", + prefix, i, enumstr (i), work[i]); + + if (fix) + { + picosat_add (work[i]); + picosat_add (0); + } + } + else + { + assert (res == 20); + if (verbosity > 1) + fprintf (out, + "%ssuceeded to drop %d%s assumption %d\n", + prefix, i, enumstr (i), work[i]); + redundant[i] = 1; + for (j = 0; j < nwork; j++) + { + failed = picosat_failed_assumption (work[j]); + if (j <= i) + { + assert (redundant[j] == !failed); + continue; + } + + if (!failed) + { + redundant[j] = -1; + if (verbosity > 1) + fprintf (out, + "%salso suceeded to drop %d%s assumption %d\n", + prefix, j, enumstr (j), work[j]); + } + } + + oldlen = len; + len = 0; + for (j = 0; j < nwork; j++) + if (!redundant[j]) + mass[len++] = work[j]; + mass[len] = 0; + assert (len < oldlen); + + if (fix) + { + picosat_add (-work[i]); + picosat_add (0); + } + +#ifndef NDEBUG + for (j = 0; j <= i; j++) + assert (redundant[j] >= 0); +#endif + for (j = i + 1; j < nwork; j++) + { + if (redundant[j] >= 0) + continue; + + if (fix) + { + picosat_add (-work[j]); + picosat_add (0); + } + + redundant[j] = 1; + } + + if (verbosity) + fprintf (out, + "%sreduced set of failed assumptions of size %d out of %d (%.0f%%)\n", + prefix, len, norig, PERCENT (len, norig)); + if (cb) + cb (s, mass); + } + } + + DELETEN (work, nwork); + DELETEN (redundant, nwork); + + if (verbosity) + fprintf (out, "%sreinitializaing unsat state", prefix); + for (i = 0; i < len; i++) + picosat_assume (mass[i]); + res = picosat_sat (-1); + assert (res == 20); + + return mass; +} + +int +picosat_usedlit (int int_lit) +{ + int res; + check_ready (); + check_sat_or_unsat_or_unknown_state (); + ABORTIF (!int_lit, "API usage: zero literal can not be used"); + int_lit = abs (int_lit); + res = (int_lit <= (int) max_var) ? vars[int_lit].used : 0; + return res; +} + +void +picosat_write_clausal_core (FILE * file) +{ + check_trace_support_and_execute (file, write_core_wrapper, 0); +} + +void +picosat_write_compact_trace (FILE * file) +{ + check_trace_support_and_execute (file, write_trace, + COMPACT_TRACECHECK_TRACE_FMT); +} + +void +picosat_write_extended_trace (FILE * file) +{ + check_trace_support_and_execute (file, write_trace, + EXTENDED_TRACECHECK_TRACE_FMT); +} + +void +picosat_write_rup_trace (FILE * file) +{ + check_trace_support_and_execute (file, write_trace, RUP_TRACE_FMT); +} + +size_t +picosat_max_bytes_allocated (void) +{ + check_ready (); + return max_bytes; +} + +void +picosat_set_propagation_limit (unsigned long long l) +{ + lpropagations = l; +} + +unsigned long long +picosat_propagations (void) +{ + return propagations; +} + +int +picosat_variables (void) +{ + check_ready (); + return (int) max_var; +} + +int +picosat_added_original_clauses (void) +{ + check_ready (); + return (int) oadded; +} + +void +picosat_stats (void) +{ + unsigned redlits; +#ifdef STATS + check_ready (); + assert (sdecisions + rdecisions + assumptions == decisions); +#endif + if (calls > 1) + fprintf (out, "%s%u calls\n", prefix, calls); + fprintf (out, "%s%u iterations\n", prefix, iterations); + fprintf (out, "%s%u restarts", prefix, restarts); +#ifdef STATS + fprintf (out, " (%u skipped)", skippedrestarts); +#endif + fputc ('\n', out); +#ifndef NFL + fprintf (out, "%s%u failed literals", prefix, failedlits); +#ifdef STATS + fprintf (out, + ", %u calls, %u rounds, %llu propagations", + flcalls, flrounds, flprops); +#endif + fputc ('\n', out); +#ifdef STATS + fprintf (out, + "%sfl: %u = %.1f%% implicit, %llu oopsed, %llu tried, %llu skipped\n", + prefix, + ifailedlits, PERCENT (ifailedlits, failedlits), + floopsed, fltried, flskipped); +#endif +#endif + fprintf (out, "%s%u conflicts", prefix, conflicts); +#ifdef STATS + fprintf (out, " (%u uips = %.1f%%)\n", uips, PERCENT(uips,conflicts)); +#else + fputc ('\n', out); +#endif +#ifndef NADC + fprintf (out, "%s%u adc conflicts\n", prefix, adoconflicts); +#endif +#ifdef STATS + fprintf (out, "%s%llu dereferenced literals\n", prefix, derefs); +#endif + fprintf (out, "%s%u decisions", prefix, decisions); +#ifdef STATS + fprintf (out, " (%u random = %.2f%%", + rdecisions, PERCENT (rdecisions, decisions)); + fprintf (out, ", %u assumptions", assumptions); + fputc (')', out); +#endif + fputc ('\n', out); +#ifdef STATS + fprintf (out, + "%s%u static phase decisions (%.1f%% of all variables)\n", + prefix, + staticphasedecisions, PERCENT (staticphasedecisions, max_var)); +#endif + fprintf (out, "%s%u fixed variables\n", prefix, fixed); + assert (nonminimizedllits >= minimizedllits); + redlits = nonminimizedllits - minimizedllits; + fprintf (out, "%s%u learned literals\n", prefix, llitsadded); + fprintf (out, "%s%.1f%% deleted literals\n", + prefix, PERCENT (redlits, nonminimizedllits)); + +#ifdef STATS +#ifndef NO_BINARY_CLAUSES + fprintf (out, + "%s%llu antecedents (%.1f antecedents per clause", + prefix, antecedents, AVERAGE (antecedents, conflicts)); +#endif +#ifdef TRACE + if (trace) + fprintf (out, ", %.1f bytes/antecedent)", AVERAGE (znts, antecedents)); +#endif +#if !defined(NO_BINARY_CLAUSES) || defined(TRACE) + fputs (")\n", out); +#endif + + fprintf (out, "%s%llu propagations (%.1f propagations per decision)\n", + prefix, propagations, AVERAGE (propagations, decisions)); + fprintf (out, "%s%llu visits (%.1f per propagation)\n", + prefix, visits, AVERAGE (visits, propagations)); + fprintf (out, + "%s%llu binary clauses visited (%.1f%% %.1f per propagation)\n", + prefix, bvisits, + PERCENT (bvisits, visits), + AVERAGE (bvisits, propagations)); + fprintf (out, + "%s%llu ternary clauses visited (%.1f%% %.1f per propagation)\n", + prefix, tvisits, + PERCENT (tvisits, visits), + AVERAGE (tvisits, propagations)); + fprintf (out, + "%s%llu large clauses visited (%.1f%% %.1f per propagation)\n", + prefix, lvisits, + PERCENT (lvisits, visits), + AVERAGE (lvisits, propagations)); + fprintf (out, "%s%llu other true (%.1f%% of visited clauses)\n", + prefix, othertrue, PERCENT (othertrue, visits)); + fprintf (out, + "%s%llu other true in binary clauses (%.1f%%)" + ", %llu upper (%.1f%%)\n", + prefix, othertrue2, PERCENT (othertrue2, othertrue), + othertrue2u, PERCENT (othertrue2u, othertrue2)); + fprintf (out, + "%s%llu other true in large clauses (%.1f%%)" + ", %llu upper (%.1f%%)\n", + prefix, othertruel, PERCENT (othertruel, othertrue), + othertruelu, PERCENT (othertruelu, othertruel)); + fprintf (out, "%s%llu ternary and large traversals (%.1f per visit)\n", + prefix, traversals, AVERAGE (traversals, visits)); + fprintf (out, "%s%llu large traversals (%.1f per large visit)\n", + prefix, ltraversals, AVERAGE (ltraversals, lvisits)); + fprintf (out, "%s%llu assignments\n", prefix, assignments); +#else + fprintf (out, "%s%llu propagations\n", prefix, picosat_propagations ()); +#endif + fprintf (out, "%s%.1f%% variables used\n", prefix, PERCENT (vused, max_var)); + + sflush (); + fprintf (out, "%s%.1f seconds in library\n", prefix, seconds); + fprintf (out, "%s%.1f megaprops/second\n", + prefix, AVERAGE (propagations / 1e6f, seconds)); +#ifdef STATS + fprintf (out, "%s%.1f million visits per second\n", + prefix, AVERAGE (visits / 1e6f, seconds)); + fprintf (out, + "%srecycled %.1f MB in %u reductions\n", + prefix, rrecycled / (double) (1 << 20), reductions); + fprintf (out, + "%srecycled %.1f MB in %u simplifications\n", + prefix, srecycled / (double) (1 << 20), simps); +#else + fprintf (out, "%s%u simplifications\n", prefix, simps); + fprintf (out, "%s%u reductions\n", prefix, reductions); + fprintf (out, "%s%.1f MB recycled\n", prefix, recycled / (double) (1 << 20)); +#endif + fprintf (out, "%s%.1f MB maximally allocated\n", + prefix, picosat_max_bytes_allocated () / (double) (1 << 20)); +} + +#ifndef NGETRUSAGE +#include <sys/time.h> +#include <sys/resource.h> +#include <sys/unistd.h> +#endif + +double +picosat_time_stamp (void) +{ + double res = -1; +#ifndef NGETRUSAGE + struct rusage u; + res = 0; + if (!getrusage (RUSAGE_SELF, &u)) + { + res += u.ru_utime.tv_sec + 1e-6 * u.ru_utime.tv_usec; + res += u.ru_stime.tv_sec + 1e-6 * u.ru_stime.tv_usec; + } +#endif + return res; +} + +double +picosat_seconds (void) +{ + check_ready (); + return seconds; +} + +void +picosat_print (FILE * file) +{ +#ifdef NO_BINARY_CLAUSES + Lit * lit, *other, * last; + Ltk * stack; +#endif + Lit **q, **eol; + Cls **p, *cls; + unsigned n; + + if (measurealltimeinlib) + enter (); + else + check_ready (); + + n = 0; + n += alshead - als; + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + n++; + } + +#ifdef NO_BINARY_CLAUSES + last = int2lit (-max_var); + for (lit = int2lit (1); lit <= last; lit++) + { + stack = LIT2IMPLS (lit); + eol = stack->start + stack->count; + for (q = stack->start; q < eol; q++) + if (*q >= lit) + n++; + } +#endif + + fprintf (file, "p cnf %d %u\n", max_var, n); + + for (p = SOC; p != EOC; p = NXC (p)) + { + cls = *p; + if (!cls) + continue; + +#ifdef TRACE + if (cls->collected) + continue; +#endif + + eol = end_of_lits (cls); + for (q = cls->lits; q < eol; q++) + { + write_int (lit2int (*q), file); + fputc (' ', file); + } + + fputs ("0\n", file); + } + +#ifdef NO_BINARY_CLAUSES + last = int2lit (-max_var); + for (lit = int2lit (1); lit <= last; lit++) + { + stack = LIT2IMPLS (lit); + eol = stack->start + stack->count; + for (q = stack->start; q < eol; q++) + if ((other = *q) >= lit) + fprintf (file, "%d %d 0\n", lit2int (lit), lit2int (other)); + } +#endif + + { + Lit **r; + for (r = als; r < alshead; r++) + fprintf (file, "%d 0\n", lit2int (*r)); + } + + fflush (file); + + if (measurealltimeinlib) + leave (); +} + +void +picosat_enter (void) +{ + enter (); +} + +void +picosat_leave (void) +{ + leave (); +} + +void +picosat_message (int level, const char * fmt, ...) +{ + va_list ap; + + if (level > verbosity) + return; + + fputs (prefix, out); + va_start (ap, fmt); + vfprintf (out, fmt, ap); + va_end (ap); + fputc ('\n', out); +} + +int +picosat_changed (void) +{ + int res; + + check_ready (); + check_sat_state (); + + res = (min_flipped <= saved_max_var); + assert (!res || saved_flips != flips); + + return res; +} + +static void +setemgr (void * nmgr) +{ + ABORTIF (emgr && emgr != nmgr, + "API usage: mismatched external memory managers"); + emgr = nmgr; +} + +void +picosat_set_new (void * nmgr, void * (*nnew)(void*,size_t)) +{ + ABORTIF (state != RESET, + "API usage: 'picosat_set_new' after 'picosat_init'"); + enew = nnew; + setemgr (nmgr); +} + +void +picosat_set_resize (void * nmgr, void * (*nresize)(void*,void*,size_t,size_t)) +{ + ABORTIF (state != RESET, + "API usage: 'picosat_set_resize' after 'picosat_init'"); + eresize = nresize; + setemgr (nmgr); +} + +void +picosat_set_delete (void * nmgr, void (*ndelete)(void*,void*,size_t)) +{ + ABORTIF (state != RESET, + "API usage: 'picosat_set_delete' after 'picosat_init'"); + edelete = ndelete; + setemgr (nmgr); +} + +void +picosat_reset_phases (void) +{ + rebias (); +} + +void +picosat_reset_scores (void) +{ + Rnk * r; + hhead = heap + 1; + for (r = rnks + 1; r <= rnks + max_var; r++) + { + CLR (r); + hpush (r); + } +} + +void +picosat_remove_learned (unsigned percentage) +{ + reset_incremental_usage (); + reduce (percentage); +} + +void +picosat_set_global_default_phase (int phase) +{ + check_ready (); + ABORTIF (phase < 0, "API usage: 'picosat_set_global_default_phase' " + "with negative argument"); + ABORTIF (phase > 3, "API usage: 'picosat_set_global_default_phase' " + "with argument > 3"); + defaultphase = phase; +} + +void +picosat_set_default_phase_lit (int int_lit, int phase) +{ + unsigned newphase; + Lit * lit; + Var * v; + + check_ready (); + + lit = import_lit (int_lit); + v = LIT2VAR (lit); + + if (phase) + { + newphase = (int_lit < 0) == (phase < 0); + v->phase = newphase; + v->assigned = 1; + } + else + v->assigned = 0; +} + +void +picosat_set_more_important_lit (int int_lit) +{ + Lit * lit; + Var * v; + Rnk * r; + + check_ready (); + + lit = import_lit (int_lit); + v = LIT2VAR (lit); + r = VAR2RNK (v); + + ABORTIF (r->lessimportant, "can not mark variable more and less important"); + + if (r->moreimportant) + return; + + r->moreimportant = 1; + + if (r->pos) + hup (r); +} + +void +picosat_set_less_important_lit (int int_lit) +{ + Lit * lit; + Var * v; + Rnk * r; + + check_ready (); + + lit = import_lit (int_lit); + v = LIT2VAR (lit); + r = VAR2RNK (v); + + ABORTIF (r->moreimportant, "can not mark variable more and less important"); + + if (r->lessimportant) + return; + + r->lessimportant = 1; + + if (r->pos) + hup (r); +} + +#ifndef NADC + +unsigned +picosat_ado_conflicts (void) +{ + check_ready (); + return adoconflicts; +} + +void +picosat_disable_ado (void) +{ + check_ready (); + assert (!adodisabled); + adodisabled = 1; +} + +void +picosat_enable_ado (void) +{ + check_ready (); + assert (adodisabled); + adodisabled = 0; +} + +void +picosat_set_ado_conflict_limit (unsigned newadoconflictlimit) +{ + check_ready (); + adoconflictlimit = newadoconflictlimit; +} + +#endif + +int +picosat_haveados (void) +{ +#ifndef NADC + return 1; +#else + return 0; +#endif +} diff --git a/src/prop/bvpicosat/picosat.h b/src/prop/bvpicosat/picosat.h new file mode 100644 index 000000000..e2b5f3752 --- /dev/null +++ b/src/prop/bvpicosat/picosat.h @@ -0,0 +1,484 @@ +/**************************************************************************** +Copyright (c) 2006 - 2010, Armin Biere, Johannes Kepler University. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +****************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef picosat_h_INCLUDED +#define picosat_h_INCLUDED + +/*------------------------------------------------------------------------*/ + +#include <stdlib.h> +#include <stdio.h> + +/*------------------------------------------------------------------------*/ +/* These are the return values for 'picosat_sat' as for instance + * standardized by the output format of the SAT competition. + */ +#define PICOSAT_UNKNOWN 0 +#define PICOSAT_SATISFIABLE 10 +#define PICOSAT_UNSATISFIABLE 20 + +/*------------------------------------------------------------------------*/ + + + + +const char *picosat_version (void); +const char *picosat_config (void); +const char *picosat_copyright (void); + +/*------------------------------------------------------------------------*/ +/* You can make picosat use an external memory manager instead of the one + * provided by LIBC. But then you need to call these three function before + * 'picosat_init'. The memory manager functions here all have an additional + * first argument which is a pointer to the memory manager, but otherwise + * are supposed to work as their LIBC counter parts 'malloc', 'realloc' and + * 'free'. As exception the 'resize' and 'delete' function have as third + * argument the number of bytes of the block given as second argument. + */ +void picosat_set_new (void * mgr, void * (*)(void *, size_t)); +void picosat_set_resize (void *, void * (*)(void *, void *, size_t, size_t)); +void picosat_set_delete (void *, void (*)(void *, void *, size_t)); + +/*------------------------------------------------------------------------*/ + +void picosat_init (void); /* constructor */ +void picosat_reset (void); /* destructor */ + +/*------------------------------------------------------------------------*/ +/* The following five functions are essentially parameters to 'init', and + * thus should be called right after 'picosat_init' before doing anything + * else. You should not call any of them after adding a literal. + */ + +/* Set output file, default is 'stdout'. + */ +void picosat_set_output (FILE *); + +/* Measure all time spent in all calls in the solver. By default only the + * time spent in 'picosat_sat' is measured. Enabling this function may for + * instance tripple the time needed to add large CNFs, since every call to + * 'picosat_add' will trigger a call to 'getrusage'. + */ +void picosat_measure_all_calls (void); + +/* Set the prefix used for printing verbose messages and statistics. + * Default is "c ". + */ +void picosat_set_prefix (const char *); + +/* The function 'picosat_set_incremental_rup_file' produces + * a proof trace in RUP format on the fly. The resulting RUP file may + * contain learned clauses that are not actual in the clausal core. + */ + +/* Set verbosity level. A verbosity level of 1 and above prints more and + * more detailed progress reports on the output file, set by + * 'picosat_set_output'. Verbose messages are prefixed with the string set + * by 'picosat_set_prefix'. + */ +void picosat_set_verbosity (int new_verbosity_level); + +/* Set default initial phase: + * + * 0 = false + * 1 = true + * 2 = Jeroslow-Wang (default) + * 3 = random initial phase + * + * After a variable has been assigned the first time, it will always + * be assigned the previous value if it is picked as decision variable. + * The initial assignment can be choosen with this function. + */ +void picosat_set_global_default_phase (int); + +/* Set next/initial phase of a particular variable if picked as decision + * variable. Second argument 'phase' has the following meaning: + * + * negative = next value if picked as decision variable is false + * + * positive = next value if picked as decision variable is true + * + * 0 = use global default phase as next value and + * assume 'lit' was never assigned + * + * Again if 'lit' is assigned afterwards through a forced assignment, + * then this forced assignment is the next phase if this variable is + * used as decision variable. + */ +void picosat_set_default_phase_lit (int lit, int phase); + +/* You can reset all phases by the following function. + */ +void picosat_reset_phases (void); + +/* Scores can be erased as well. Not however, that even after erasing + * scores and phases, learned clauses are kept. In addition head tail + * pointers for literals are not moved either. So expect to be a difference + * between calling the solver in incremental mode or with a fresh copy of + * the CNF. + */ +void picosat_reset_scores (void); + +/* Reset assignment if in SAT state and then remove the given percentage of + * less active (large) learned clauses. If you specify 100% all large + * learned clauses are removed. + */ +void picosat_remove_learned (unsigned percentage); + +/* Set some variables to be more important than others. These variables are + * always used as decisions before other variables are used. Dually there + * is a set of variables that is used last. The default is + * to mark all variables as being indifferent only. + */ +void picosat_set_more_important_lit (int lit); +void picosat_set_less_important_lit (int lit); + +/* Allows to print to internal 'out' file from client. + */ +void picosat_message (int verbosity_level, const char * fmt, ...); + +/* Deprecated! + */ +#define picosat_enable_verbosity() picosat_set_verbosity (1) + +/* Set a seed for the random number generator. The random number generator + * is currently just used for generating random decisions. In our + * experiments having random decisions did not really help on industrial + * examples, but was rather helpful to randomize the solver in order to + * do proper benchmarking of different internal parameter sets. + */ +void picosat_set_seed (unsigned random_number_generator_seed); + +/* If you ever want to extract cores or proof traces with the current + * instance of PicoSAT initialized with 'picosat_init', then make sure to + * call 'picosat_enable_trace_generation' right after 'picosat_init'. This + * is not necessary if you only use 'picosat_set_incremental_rup_file'. + * + * NOTE, trace generation code is not necessarily included, e.g. if you + * configure picosat with full optimzation as './configure -O' or with + * './configure --no-trace'. This speeds up the solver slightly. Then you + * you do not get any results by trying to generate traces. + * + * The return value is non-zero if code for generating traces is including + * and it is zero if traces can not be generated. + */ +int picosat_enable_trace_generation (void); + +/* You can dump proof traces in RUP format incrementally even without + * keeping the proof trace in memory. The advantage is a reduction of + * memory usage, but the dumped clauses do not necessarily belong to the + * clausal core. Beside the file the additional parameters denotes the + * maximal number of variables and the number of original clauses. + */ +void picosat_set_incremental_rup_file (FILE * file, int m, int n); + +/*------------------------------------------------------------------------*/ +/* This function returns the next available unused variable index and + * allocates a variable for it even though this variable does not occur as + * assumption, nor in a clause or any other constraints. In future calls to + * 'picosat_sat', 'picosat_deref' and particularly for 'picosat_changed', + * this variable is treated as if it had been used. + */ +int picosat_inc_max_var (void); + +/*------------------------------------------------------------------------*/ +/* If you know a good estimate on how many variables you are going to use + * then calling this function before adding literals will result in less + * resizing of the variable table. But this is just a minor optimization. + * Beside exactly allocating enough variables it has the same effect as + * calling 'picosat_inc_max_var'. + */ +void picosat_adjust (int max_idx); + +/*------------------------------------------------------------------------*/ +/* Statistics. + */ +int picosat_variables (void); /* p cnf <m> n */ +int picosat_added_original_clauses (void); /* p cnf m <n> */ +size_t picosat_max_bytes_allocated (void); +double picosat_time_stamp (void); /* ... in process */ +void picosat_stats (void); /* > output file */ +unsigned long long picosat_propagations (void); /* #propagations */ + +/* The time spent in the library or in 'picosat_sat'. The former is only + * returned if, right after initialization 'picosat_measure_all_calls' + * is called. + */ +double picosat_seconds (void); + +/*------------------------------------------------------------------------*/ +/* Add a literal of the next clause. A zero terminates the clause. The + * solver is incremental. Adding a new literal will reset the previous + * assignment. The return value is the original clause index to which + * this literal respectively the trailing zero belong starting at 0. + */ +int picosat_add (int lit); + +/* Print the CNF to the given file in DIMACS format. + */ +void picosat_print (FILE *); + +/* You can add arbitrary many assumptions before the next 'picosat_sat'. + * This is similar to the using assumptions in MiniSAT, except that you do + * not have to collect all your assumptions yourself. In PicoSAT you can + * add one after the other before the next call to 'picosat_sat'. + * + * These assumptions can be seen as adding unit clauses with those + * assumptions as literals. However these assumption clauses are only valid + * for exactly the next call to 'picosat_sat'. And will be removed + * afterwards, e.g. in future calls to 'picosat_sat' after the next one they + * are not assumed, unless they are assumed again trough 'picosat_assume'. + * + * More precisely, assumptions actually remain valid even after the next + * call to 'picosat_sat' returns. Valid means they remain 'assumed' until a + * call to 'picosat_add', 'picosat_assume', or another 'picosat_sat, + * following the first 'picosat_sat'. They need to stay valid for + * 'picosat_failed_assumption' to return correct values. + * + * Example: + * + * picosat_assume (1); // assume unit clause '1 0' + * picosat_assume (-2); // additionally assume clause '-2 0' + * res = picosat_sat (1000); // assumes 1 and -2 to hold + * // 1000 decisions max. + * + * if (res == PICOSAT_UNSATISFIABLE) + * { + * if (picosat_failed_assumption (1)) + * // unit clause '1 0' was necessary to derive UNSAT + * + * if (picosat_failed_assumption (-2)) + * // unit clause '-2 0' was necessary to derive UNSAT + * + * // at least one but also both could be necessary + * + * picosat_assume (17); // previous assumptions are removed + * // now assume unit clause '17 0' for + * // the next call to 'picosat_sat' + * + * // adding a new clause, actually the first literal of + * // a clause would also make the assumptions used in the previous + * // call to 'picosat_sat' invalid. + * + * // The first two assumptions above are not assumed anymore. Only + * // the assumptions, since the last call to 'picosat_sat' returned + * // are assumed, e.g. the unit clause '17 0'. + * + * res = picosat_sat (-1); + * } + * else if (res == PICOSAT_SATISFIABLE) + * { + * // now the assignment is valid and we can call 'picosat_deref' + * + * assert (picosat_deref (1) == 1)); + * assert (picosat_deref (-2) == 1)); + * + * val = picosat_deref (15); + * + * // previous two assumptions are still valid + * + * // would become invalid if 'picosat_add' or 'picosat_assume' is + * // called here, but we immediately call 'picosat_sat'. Now when + * // entering 'picosat_sat' the solver nows that the previous call + * // returned SAT and it can savely reset the previous assumptions + * + * res = picosat_sat (-1); + * } + * else + * { + * assert (res == PICOSAT_UNKNOWN); + * + * // assumptions valid, but assignment invalid + * // except for top level assigned literals which + * // necessarily need to have this value if the formula is SAT + * + * // as above the solver nows that the previous call returned UNKWOWN + * // and will before doing anything else reset assumptions + * + * picosat_sat (-1); + * } + */ +void picosat_assume (int lit); + +/*------------------------------------------------------------------------*/ +/* This is an experimental feature for handling 'all different constraints' + * (ADC). Currently only one global ADC can be handled. The bit-width of + * all the bit-vectors entered in this ADC (stored in 'all different + * objects' or ADOs) has to be identical. + * + * TODO: also handle top level assigned literals here. + */ +void picosat_add_ado_lit (int); + +/*------------------------------------------------------------------------*/ +/* Call the main SAT routine. A negative decision limit sets no limit on + * the number of decisions. The return values are as above, e.g. + * 'PICOSAT_UNSATISFIABLE', 'PICOSAT_SATISFIABLE', or 'PICOSAT_UNKNOWN'. + */ +int picosat_sat (int decision_limit); + +/* As alternative to a decision limit you can use the number of propagations + * as limit. This is more linearly related to execution time. + */ +void picosat_set_propagation_limit (unsigned long long limit); + +/* Return last result of calling 'picosat_sat' or '0' if not called. + */ +int picosat_res (); + +/* After 'picosat_sat' was called and returned 'PICOSAT_SATISFIABLE', then + * the satisfying assignment can be obtained by 'dereferencing' literals. + * The value of the literal is return as '1' for 'true', '-1' for 'false' + * and '0' for an unknown value. + */ +int picosat_deref (int lit); + +/* Same as before but just returns true resp. false if the literals is + * forced to this assignment at the top level. This function does not + * require that 'picosat_sat' was called and also does not internally reset + * incremental usage. + */ +int picosat_deref_toplevel (int lit); + +/* Returns non zero if the CNF is unsatisfiable because an empty clause was + * added or derived. + */ +int picosat_inconsistent (void); + +/* Returns non zero if the literal is a failed assumption, which is defined + * as an assumption used to derive unsatisfiability. This is as accurate as + * generating core literals, but still of course is an overapproximation of + * the set of assumptions really necessary. The technique does not need + * clausal core generation nor tracing to be enabled and thus can be much + * more effectice. The function can only be called as long the current + * assumptions are valid. See 'picosat_assume' for more details. + */ +int picosat_failed_assumption (int lit); + +/* Returns a zero terminated list of failed assumption in the last call to + * 'picosat_sat'. The pointer is valid until the next call to + * 'picosat_sat' or 'picosat_failed_assumptions'. It only makes sense if the + * last call to 'picosat_sat' returned 'PICOSAT_UNSATISFIABLE'. + */ +const int * picosat_failed_assumptions (void); + +/* Returns a zero terminated minimized list of failed assumption for the last + * call to 'picosat_sat'. The pointer is valid until the next call to this + * function or 'picosat_sat' or 'picosat_mus_assumptions'. It only makes sense + * if the last call to 'picosat_sat' returned 'PICOSAT_UNSATISFIABLE'. + * + * The + * call back function is called for all succesful simplification attempts. The + * first argument of the call back function is the state given as first + * argument to 'picosat_mus_assumptions'. The second argument to the call back + * function is the new reduced list of failed assumptions. + * + * This function will call 'picosat_assume' and 'picosat_sat' internally but + * before returning reestablish a proper UNSAT state, e.g. + * 'picosat_failed_assumption' will work afterwards as expected. + * + * The last argument if non zero fixes assumptions. In particular, if an + * assumption can not be removed it is permanently assigned true, otherwise + * if it turns out to be redundant it is permanently assumed to be false. + */ +const int * picosat_mus_assumptions (void *, void(*)(void*,const int*),int); + +/*------------------------------------------------------------------------*/ +/* Assume that a previous call to 'picosat_sat' in incremental usage, + * returned 'SATISFIABLE'. Then a couple of clauses and optionally new + * variables were added (a new variable is a variable that has an index + * larger then the maximum variable added so far). The next call to + * 'picosat_sat' also returns 'SATISFIABLE'. If this function + * 'picosat_changed' returns '0', then the assignment to the old variables + * did not change. Otherwise it may have changed. The return value to + * this function is only valid until new clauses are added through + * 'picosat_add', an assumption is made through 'picosat_assume', or again + * 'picosat_sat' is called. This is the same assumption as for + * 'picosat_deref'. + * + * TODO currently this function may also return a non zero value even if the + * old assignment did not change, because it only checks whether the + * assignment of at least one old variable was flipped at least once during + * the search. In principle it should be possible to be exact in the other + * direcetion as well by using a counter of variables that have an odd + * number of flips. But this is not implemented yet. + */ +int picosat_changed (void); + +/*------------------------------------------------------------------------*/ +/* The following six functions internally extract the variable and clausal + * core and thus require trace generation to be enabled with + * 'picosat_enable_trace_generation' right after calling 'picosat_init'. + * + * TODO: using these functions in incremental mode with failed assumptions + * has only been tested for 'picosat_corelit' thoroughly. The others may + * only work in non-incremental mode or without using 'picosat_assume'. + */ + +/* This function determines whether the i'th added original clause is in the + * core. The 'i' is the return value of 'picosat_add', which starts at zero + * and is incremented by one after a original clause is added (that is after + * 'picosat_add (0)'). For the index 'i' the following has to hold: + * + * 0 <= i < picosat_added_original_clauses () + */ +int picosat_coreclause (int i); + +/* This function gives access to the variable core, which is made up of the + * variables that were resolved in deriving the empty clauses. + */ +int picosat_corelit (int lit); + +/* Write the clauses that were used in deriving the empty clause to a file + * in DIMACS format. + */ +void picosat_write_clausal_core (FILE * core_file); + +/* Write a proof trace in TraceCheck format to a file. + */ +void picosat_write_compact_trace (FILE * trace_file); +void picosat_write_extended_trace (FILE * trace_file); + +/* Write a RUP trace to a file. This trace file contains only the learned + * core clauses while this is not necessarily the case for the RUP file + * obtained with 'picosat_set_incremental_rup_file'. + */ +void picosat_write_rup_trace (FILE * trace_file); + +/*------------------------------------------------------------------------*/ +/* Keeping the proof trace around is not necessary if an over-approximation + * of the core is enough. A literal is 'used' if it was involved in a + * resolution to derive a learned clause. The core literals are necessarily + * a subset of the 'used' literals. + */ + +int picosat_usedlit (int lit); +/*------------------------------------------------------------------------*/ +#endif + +#ifdef __cplusplus +} +#endif /* extern "C" */ diff --git a/src/prop/bvpicosat/version.c b/src/prop/bvpicosat/version.c new file mode 100644 index 000000000..71c322bd7 --- /dev/null +++ b/src/prop/bvpicosat/version.c @@ -0,0 +1,14 @@ +#include "config.h" + +const char * +picosat_version (void) +{ + return PICOSAT_VERSION; +} + +const char * +picosat_config (void) +{ + return PICOSAT_CC " " PICOSAT_CFLAGS; +} + diff --git a/src/prop/cnf_stream.cpp b/src/prop/cnf_stream.cpp index 681e42a99..74feebd03 100644 --- a/src/prop/cnf_stream.cpp +++ b/src/prop/cnf_stream.cpp @@ -18,7 +18,6 @@ ** of given an equisatisfiable stream of assertions to PropEngine. **/ -#include "prop/sat.h" #include "prop/cnf_stream.h" #include "prop/prop_engine.h" #include "theory/theory_engine.h" @@ -28,6 +27,7 @@ #include "util/output.h" #include "expr/command.h" #include "expr/expr.h" +#include "prop/sat.h" #include <queue> @@ -43,7 +43,8 @@ using namespace CVC4::kind; namespace CVC4 { namespace prop { -CnfStream::CnfStream(SatInputInterface *satSolver, theory::Registrar registrar, bool fullLitToNodeMap) : + +CnfStream::CnfStream(SatSolverInterface *satSolver, Registrar* registrar, bool fullLitToNodeMap) : d_satSolver(satSolver), d_fullLitToNodeMap(fullLitToNodeMap), d_registrar(registrar) { @@ -55,7 +56,7 @@ void CnfStream::recordTranslation(TNode node) { } } -TseitinCnfStream::TseitinCnfStream(SatInputInterface* satSolver, theory::Registrar registrar, bool fullLitToNodeMap) : +TseitinCnfStream::TseitinCnfStream(SatSolverInterface* satSolver, Registrar* registrar, bool fullLitToNodeMap) : CnfStream(satSolver, registrar, fullLitToNodeMap) { } @@ -164,7 +165,7 @@ SatLiteral CnfStream::newLiteral(TNode node, bool theoryLiteral) { SatLiteral lit; if (!hasLiteral(node)) { // If no literal, well make one - lit = variableToLiteral(d_satSolver->newVar(theoryLiteral)); + lit = SatLiteral(d_satSolver->newVar(theoryLiteral)); d_translationCache[node].literal = lit; d_translationCache[node.notNode()].literal = ~lit; } else { @@ -189,7 +190,7 @@ SatLiteral CnfStream::newLiteral(TNode node, bool theoryLiteral) { // If a theory literal, we pre-register it if (theoryLiteral) { bool backup = d_removable; - d_registrar.preRegister(node); + d_registrar->preRegister(node); d_removable = backup; } @@ -212,7 +213,7 @@ SatLiteral CnfStream::convertAtom(TNode node) { Debug("cnf") << "convertAtom(" << node << ")" << endl; Assert(!isTranslated(node), "atom already mapped!"); - + // boolean variables are not theory literals bool theoryLiteral = node.getKind() != kind::VARIABLE && !node.getType().isPseudoboolean(); SatLiteral lit = newLiteral(node, theoryLiteral); diff --git a/src/prop/cnf_stream.h b/src/prop/cnf_stream.h index 4b16a02b9..c9306952b 100644 --- a/src/prop/cnf_stream.h +++ b/src/prop/cnf_stream.h @@ -29,7 +29,7 @@ #include "expr/node.h" #include "prop/sat.h" -#include "theory/registrar.h" +#include "prop/registrar.h" #include <ext/hash_map> @@ -48,7 +48,7 @@ class CnfStream { public: /** Cache of what nodes have been registered to a literal. */ - typedef __gnu_cxx::hash_map<SatLiteral, TNode, SatSolver::SatLiteralHashFunction> NodeCache; + typedef __gnu_cxx::hash_map<SatLiteral, TNode, SatLiteralHashFunction> NodeCache; /** Per node translation information */ struct TranslationInfo { @@ -64,7 +64,7 @@ public: protected: /** The SAT solver we will be using */ - SatInputInterface *d_satSolver; + SatSolverInterface *d_satSolver; TranslationCache d_translationCache; NodeCache d_nodeCache; @@ -77,7 +77,7 @@ protected: const bool d_fullLitToNodeMap; /** The "registrar" for pre-registration of terms */ - theory::Registrar d_registrar; + Registrar* d_registrar; /** Top level nodes that we translated */ std::vector<TNode> d_translationTrail; @@ -98,7 +98,7 @@ protected: * detection," when BIG FORMULA is later asserted, it is clausified * separately, and "lit" is never asserted as a unit clause. */ - KEEP_STATISTIC(IntStat, d_fortunateLiterals, "prop::CnfStream::fortunateLiterals", 0); + //KEEP_STATISTIC(IntStat, d_fortunateLiterals, "prop::CnfStream::fortunateLiterals", 0); /** Remove nots from the node */ TNode stripNot(TNode node) { @@ -189,7 +189,7 @@ public: * @param fullLitToNodeMap maintain a full SAT-literal-to-Node mapping, * even for non-theory literals */ - CnfStream(SatInputInterface* satSolver, theory::Registrar registrar, bool fullLitToNodeMap = false); + CnfStream(SatSolverInterface* satSolver, Registrar* registrar, bool fullLitToNodeMap = false); /** * Destructs a CnfStream. This implementation does nothing, but we @@ -289,7 +289,7 @@ public: * @param fullLitToNodeMap maintain a full SAT-literal-to-Node mapping, * even for non-theory literals */ - TseitinCnfStream(SatInputInterface* satSolver, theory::Registrar registrar, bool fullLitToNodeMap = false); + TseitinCnfStream(SatSolverInterface* satSolver, Registrar* registrar, bool fullLitToNodeMap = false); private: diff --git a/src/prop/minisat/core/Dimacs.h b/src/prop/minisat/core/Dimacs.h index a05e900c1..6bd19fb5b 100644 --- a/src/prop/minisat/core/Dimacs.h +++ b/src/prop/minisat/core/Dimacs.h @@ -23,8 +23,8 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <stdio.h> -#include "utils/ParseUtils.h" -#include "core/SolverTypes.h" +#include "prop/minisat/utils/ParseUtils.h" +#include "prop/minisat/core/SolverTypes.h" namespace Minisat { diff --git a/src/prop/minisat/core/Main.cc b/src/prop/minisat/core/Main.cc index 4388c3e08..de73b7327 100644 --- a/src/prop/minisat/core/Main.cc +++ b/src/prop/minisat/core/Main.cc @@ -23,11 +23,11 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <signal.h> #include <zlib.h> -#include "utils/System.h" -#include "utils/ParseUtils.h" -#include "utils/Options.h" -#include "core/Dimacs.h" -#include "core/Solver.h" +#include "prop/minisat/utils/System.h" +#include "prop/minisat/utils/ParseUtils.h" +#include "prop/minisat/utils/Options.h" +#include "prop/minisat/core/Dimacs.h" +#include "prop/minisat/core/Solver.h" using namespace Minisat; diff --git a/src/prop/minisat/core/Solver.cc b/src/prop/minisat/core/Solver.cc index cdab47163..3fe9db10c 100644 --- a/src/prop/minisat/core/Solver.cc +++ b/src/prop/minisat/core/Solver.cc @@ -22,10 +22,11 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <iostream> -#include "mtl/Sort.h" -#include "core/Solver.h" +#include "prop/minisat/mtl/Sort.h" +#include "prop/minisat/core/Solver.h" #include "prop/sat.h" +#include "prop/sat_module.h" #include "util/output.h" #include "expr/command.h" #include "proof/proof_manager.h" @@ -71,7 +72,7 @@ public: //================================================================================================= // Constructor/Destructor: -Solver::Solver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context, bool enable_incremental) : +Solver::Solver(CVC4::prop::TheoryProxy* proxy, CVC4::context::Context* context, bool enable_incremental) : proxy(proxy) , context(context) , assertionLevel(0) @@ -177,8 +178,10 @@ CRef Solver::reason(Var x) { Lit l = mkLit(x, value(x) != l_True); // Get the explanation from the theory - SatClause explanation; - proxy->explainPropagation(l, explanation); + SatClause explanation_cl; + proxy->explainPropagation(DPLLMinisatSatSolver::toSatLiteral(l), explanation_cl); + vec<Lit> explanation; + DPLLMinisatSatSolver::toMinisatClause(explanation_cl, explanation); // Sort the literals by trail index level lemma_lt lt(*this); @@ -340,7 +343,7 @@ void Solver::cancelUntil(int level) { int currentLevel = decisionLevel(); for(int i = variables_to_register.size() - 1; i >= 0 && variables_to_register[i].level > currentLevel; --i) { variables_to_register[i].level = currentLevel; - proxy->variableNotify(variables_to_register[i].var); + proxy->variableNotify(DPLLMinisatSatSolver::toSatVariable(variables_to_register[i].var)); } } } @@ -358,14 +361,15 @@ Lit Solver::pickBranchLit() Lit nextLit; #ifdef CVC4_REPLAY - nextLit = proxy->getNextReplayDecision(); + nextLit = DPLLMinisatSatSolver::toMinisatLit(proxy->getNextReplayDecision()); + if (nextLit != lit_Undef) { return nextLit; } #endif /* CVC4_REPLAY */ // Theory requests - nextLit = proxy->getNextDecisionRequest(); + nextLit = DPLLMinisatSatSolver::toMinisatLit(proxy->getNextDecisionRequest()); while (nextLit != lit_Undef) { if(value(var(nextLit)) == l_Undef) { Debug("propagateAsDecision") << "propagateAsDecision(): now deciding on " << nextLit << std::endl; @@ -373,7 +377,7 @@ Lit Solver::pickBranchLit() } else { Debug("propagateAsDecision") << "propagateAsDecision(): would decide on " << nextLit << " but it already has an assignment" << std::endl; } - nextLit = proxy->getNextDecisionRequest(); + nextLit = DPLLMinisatSatSolver::toMinisatLit(proxy->getNextDecisionRequest()); } Var next = var_Undef; @@ -638,7 +642,7 @@ void Solver::uncheckedEnqueue(Lit p, CRef from) } if (theory[var(p)]) { // Enqueue to the theory - proxy->enqueueTheoryLiteral(p); + proxy->enqueueTheoryLiteral(DPLLMinisatSatSolver::toSatLiteral(p)); } } @@ -710,8 +714,13 @@ CRef Solver::propagate(TheoryCheckType type) } void Solver::propagateTheory() { - std::vector<Lit> propagatedLiterals; - proxy->theoryPropagate(propagatedLiterals); + + SatClause propagatedLiteralsClause; + proxy->theoryPropagate(propagatedLiteralsClause); + + vec<Lit> propagatedLiterals; + DPLLMinisatSatSolver::toMinisatClause(propagatedLiteralsClause, propagatedLiterals); + int oldTrailSize = trail.size(); Debug("minisat") << "old trail size is " << oldTrailSize << ", propagating " << propagatedLiterals.size() << " lits..." << std::endl; for (unsigned i = 0, i_end = propagatedLiterals.size(); i < i_end; ++ i) { @@ -1069,7 +1078,7 @@ lbool Solver::search(int nof_conflicts) } #ifdef CVC4_REPLAY - proxy->logDecision(next); + proxy->logDecision(DPLLMinisatSatSolver::toSatLiteral(next)); #endif /* CVC4_REPLAY */ } diff --git a/src/prop/minisat/core/Solver.h b/src/prop/minisat/core/Solver.h index a3d449a36..426268b4b 100644 --- a/src/prop/minisat/core/Solver.h +++ b/src/prop/minisat/core/Solver.h @@ -25,11 +25,11 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <iostream> -#include "mtl/Vec.h" -#include "mtl/Heap.h" -#include "mtl/Alg.h" -#include "utils/Options.h" -#include "core/SolverTypes.h" +#include "prop/minisat/mtl/Vec.h" +#include "prop/minisat/mtl/Heap.h" +#include "prop/minisat/mtl/Alg.h" +#include "prop/minisat/utils/Options.h" +#include "prop/minisat/core/SolverTypes.h" #include "context/context.h" #include "theory/theory.h" @@ -40,7 +40,7 @@ namespace CVC4 { class SatProof; namespace prop { - class SatSolver; + class TheoryProxy; }/* CVC4::prop namespace */ }/* CVC4 namespace */ @@ -53,22 +53,22 @@ namespace Minisat { class Solver { /** The only two CVC4 entry points to the private solver data */ - friend class CVC4::prop::SatSolver; + friend class CVC4::prop::TheoryProxy; friend class CVC4::SatProof; protected: /** The pointer to the proxy that provides interfaces to the SMT engine */ - CVC4::prop::SatSolver* proxy; + CVC4::prop::TheoryProxy* proxy; /** The context from the SMT solver */ CVC4::context::Context* context; /** The current assertion level (user) */ int assertionLevel; - +public: /** Returns the current user assertion level */ int getAssertionLevel() const { return assertionLevel; } - +protected: /** Do we allow incremental solving */ bool enable_incremental; @@ -102,7 +102,7 @@ public: // Constructor/Destructor: // - Solver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context, bool enableIncremental = false); + Solver(CVC4::prop::TheoryProxy* proxy, CVC4::context::Context* context, bool enableIncremental = false); CVC4_PUBLIC virtual ~Solver(); // Problem specification: diff --git a/src/prop/minisat/core/SolverTypes.h b/src/prop/minisat/core/SolverTypes.h index 57ca95a41..85e1b9750 100644 --- a/src/prop/minisat/core/SolverTypes.h +++ b/src/prop/minisat/core/SolverTypes.h @@ -25,11 +25,11 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <assert.h> #include "util/output.h" -#include "mtl/IntTypes.h" -#include "mtl/Alg.h" -#include "mtl/Vec.h" -#include "mtl/Map.h" -#include "mtl/Alloc.h" +#include "prop/minisat/mtl/IntTypes.h" +#include "prop/minisat/mtl/Alg.h" +#include "prop/minisat/mtl/Vec.h" +#include "prop/minisat/mtl/Map.h" +#include "prop/minisat/mtl/Alloc.h" namespace Minisat { @@ -119,6 +119,40 @@ inline lbool toLbool(int v) { return lbool((uint8_t)v); } class Clause; typedef RegionAllocator<uint32_t>::Ref CRef; + +/* convenience printing functions */ + + +inline std::ostream& operator <<(std::ostream& out, Minisat::Lit lit) { + const char * s = (Minisat::sign(lit)) ? "~" : " "; + out << s << Minisat::var(lit); + return out; +} + +inline std::ostream& operator <<(std::ostream& out, Minisat::vec<Minisat::Lit>& clause) { + out << "clause:"; + for(int i = 0; i < clause.size(); ++i) { + out << " " << clause[i]; + } + out << ";"; + return out; +} + +inline std::ostream& operator <<(std::ostream& out, Minisat::lbool val) { + std::string val_str; + if( val == l_False ) { + val_str = "0"; + } else if (val == l_True ) { + val_str = "1"; + } else { // unknown + val_str = "_"; + } + + out << val_str; + return out; +} + + } /* Minisat */ diff --git a/src/prop/minisat/mtl/Alg.h b/src/prop/minisat/mtl/Alg.h index bb1ee5ad2..6c3a18450 100644 --- a/src/prop/minisat/mtl/Alg.h +++ b/src/prop/minisat/mtl/Alg.h @@ -21,7 +21,7 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Alg_h #define Minisat_Alg_h -#include "mtl/Vec.h" +#include "prop/minisat/mtl/Vec.h" namespace Minisat { diff --git a/src/prop/minisat/mtl/Alloc.h b/src/prop/minisat/mtl/Alloc.h index 76322b8b6..71f9f7281 100644 --- a/src/prop/minisat/mtl/Alloc.h +++ b/src/prop/minisat/mtl/Alloc.h @@ -21,8 +21,8 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Alloc_h #define Minisat_Alloc_h -#include "mtl/XAlloc.h" -#include "mtl/Vec.h" +#include "prop/minisat/mtl/XAlloc.h" +#include "prop/minisat/mtl/Vec.h" namespace Minisat { diff --git a/src/prop/minisat/mtl/Heap.h b/src/prop/minisat/mtl/Heap.h index 226407e77..5b9fb5822 100644 --- a/src/prop/minisat/mtl/Heap.h +++ b/src/prop/minisat/mtl/Heap.h @@ -21,7 +21,7 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Heap_h #define Minisat_Heap_h -#include "mtl/Vec.h" +#include "prop/minisat/mtl/Vec.h" namespace Minisat { diff --git a/src/prop/minisat/mtl/Map.h b/src/prop/minisat/mtl/Map.h index 8a82d0e28..dda6c73d1 100644 --- a/src/prop/minisat/mtl/Map.h +++ b/src/prop/minisat/mtl/Map.h @@ -20,8 +20,8 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Map_h #define Minisat_Map_h -#include "mtl/IntTypes.h" -#include "mtl/Vec.h" +#include "prop/minisat/mtl/IntTypes.h" +#include "prop/minisat/mtl/Vec.h" namespace Minisat { diff --git a/src/prop/minisat/mtl/Queue.h b/src/prop/minisat/mtl/Queue.h index 17567d694..2c818fcc9 100644 --- a/src/prop/minisat/mtl/Queue.h +++ b/src/prop/minisat/mtl/Queue.h @@ -21,7 +21,7 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Queue_h #define Minisat_Queue_h -#include "mtl/Vec.h" +#include "prop/minisat/mtl/Vec.h" namespace Minisat { diff --git a/src/prop/minisat/mtl/Sort.h b/src/prop/minisat/mtl/Sort.h index e9313ef86..644c39789 100644 --- a/src/prop/minisat/mtl/Sort.h +++ b/src/prop/minisat/mtl/Sort.h @@ -21,7 +21,7 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #ifndef Minisat_Sort_h #define Minisat_Sort_h -#include "mtl/Vec.h" +#include "prop/minisat/mtl/Vec.h" //================================================================================================= // Some sorting algorithms for vec's diff --git a/src/prop/minisat/mtl/Vec.h b/src/prop/minisat/mtl/Vec.h index 9e220852e..faf3c67f9 100644 --- a/src/prop/minisat/mtl/Vec.h +++ b/src/prop/minisat/mtl/Vec.h @@ -24,8 +24,8 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <assert.h> #include <new> -#include "mtl/IntTypes.h" -#include "mtl/XAlloc.h" +#include "prop/minisat/mtl/IntTypes.h" +#include "prop/minisat/mtl/XAlloc.h" namespace Minisat { diff --git a/src/prop/minisat/simp/Main.cc b/src/prop/minisat/simp/Main.cc index e59d73be0..ff0f589cd 100644 --- a/src/prop/minisat/simp/Main.cc +++ b/src/prop/minisat/simp/Main.cc @@ -24,11 +24,11 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <zlib.h> #include <sys/resource.h> -#include "utils/System.h" -#include "utils/ParseUtils.h" -#include "utils/Options.h" -#include "core/Dimacs.h" -#include "simp/SimpSolver.h" +#include "prop/minisat/utils/System.h" +#include "prop/minisat/utils/ParseUtils.h" +#include "prop/minisat/utils/Options.h" +#include "prop/minisat/core/Dimacs.h" +#include "prop/minisat/simp/SimpSolver.h" using namespace Minisat; diff --git a/src/prop/minisat/simp/SimpSolver.cc b/src/prop/minisat/simp/SimpSolver.cc index 6045fc881..2b5468186 100644 --- a/src/prop/minisat/simp/SimpSolver.cc +++ b/src/prop/minisat/simp/SimpSolver.cc @@ -18,9 +18,9 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ -#include "mtl/Sort.h" -#include "simp/SimpSolver.h" -#include "utils/System.h" +#include "prop/minisat/mtl/Sort.h" +#include "prop/minisat/simp/SimpSolver.h" +#include "prop/minisat/utils/System.h" #include "proof/proof.h" using namespace Minisat; using namespace CVC4; @@ -44,7 +44,7 @@ static DoubleOption opt_simp_garbage_frac(_cat, "simp-gc-frac", "The fraction of // Constructor/Destructor: -SimpSolver::SimpSolver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context, bool enableIncremental) : +SimpSolver::SimpSolver(CVC4::prop::TheoryProxy* proxy, CVC4::context::Context* context, bool enableIncremental) : Solver(proxy, context, enableIncremental) , grow (opt_grow) , clause_lim (opt_clause_lim) diff --git a/src/prop/minisat/simp/SimpSolver.h b/src/prop/minisat/simp/SimpSolver.h index 68ea6e463..97f5c2265 100644 --- a/src/prop/minisat/simp/SimpSolver.h +++ b/src/prop/minisat/simp/SimpSolver.h @@ -23,13 +23,13 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include "cvc4_private.h" -#include "mtl/Queue.h" -#include "core/Solver.h" +#include "prop/minisat/mtl/Queue.h" +#include "prop/minisat/core/Solver.h" namespace CVC4 { namespace prop { - class SatSolver; + class TheoryProxy; } } @@ -41,7 +41,7 @@ class SimpSolver : public Solver { public: // Constructor/Destructor: // - SimpSolver(CVC4::prop::SatSolver* proxy, CVC4::context::Context* context, bool enableIncremental = false); + SimpSolver(CVC4::prop::TheoryProxy* proxy, CVC4::context::Context* context, bool enableIncremental = false); CVC4_PUBLIC ~SimpSolver(); // Problem specification: diff --git a/src/prop/minisat/utils/Options.cc b/src/prop/minisat/utils/Options.cc index ec5a6e930..94c6719c3 100644 --- a/src/prop/minisat/utils/Options.cc +++ b/src/prop/minisat/utils/Options.cc @@ -17,9 +17,9 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ -#include "mtl/Sort.h" -#include "utils/Options.h" -#include "utils/ParseUtils.h" +#include "prop/minisat/mtl/Sort.h" +#include "prop/minisat/utils/Options.h" +#include "prop/minisat/utils/ParseUtils.h" using namespace Minisat; diff --git a/src/prop/minisat/utils/Options.h b/src/prop/minisat/utils/Options.h index 9c1f40699..d2611be94 100644 --- a/src/prop/minisat/utils/Options.h +++ b/src/prop/minisat/utils/Options.h @@ -25,9 +25,9 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <math.h> #include <string.h> -#include "mtl/IntTypes.h" -#include "mtl/Vec.h" -#include "utils/ParseUtils.h" +#include "prop/minisat/mtl/IntTypes.h" +#include "prop/minisat/mtl/Vec.h" +#include "prop/minisat/utils/ParseUtils.h" namespace Minisat { diff --git a/src/prop/minisat/utils/System.cc b/src/prop/minisat/utils/System.cc index a7cf53f55..5856e4897 100644 --- a/src/prop/minisat/utils/System.cc +++ b/src/prop/minisat/utils/System.cc @@ -18,7 +18,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************************************/ -#include "utils/System.h" +#include "prop/minisat/utils/System.h" #if defined(__linux__) diff --git a/src/prop/minisat/utils/System.h b/src/prop/minisat/utils/System.h index 17581927a..f5381e568 100644 --- a/src/prop/minisat/utils/System.h +++ b/src/prop/minisat/utils/System.h @@ -25,7 +25,7 @@ OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWA #include <fpu_control.h> #endif -#include "mtl/IntTypes.h" +#include "prop/minisat/mtl/IntTypes.h" //------------------------------------------------------------------------------------------------- diff --git a/src/prop/prop_engine.cpp b/src/prop/prop_engine.cpp index 3430fd7c6..7d0353122 100644 --- a/src/prop/prop_engine.cpp +++ b/src/prop/prop_engine.cpp @@ -19,9 +19,10 @@ #include "prop/cnf_stream.h" #include "prop/prop_engine.h" #include "prop/sat.h" +#include "prop/sat_module.h" #include "theory/theory_engine.h" -#include "theory/registrar.h" +#include "theory/theory_registrar.h" #include "util/Assert.h" #include "util/options.h" #include "util/output.h" @@ -70,12 +71,12 @@ PropEngine::PropEngine(TheoryEngine* te, Context* context) : Debug("prop") << "Constructing the PropEngine" << endl; - d_satSolver = new SatSolver(this, d_theoryEngine, d_context); + d_satSolver = SatSolverFactory::createDPLLMinisat(); - theory::Registrar registrar(d_theoryEngine); + theory::TheoryRegistrar* registrar = new theory::TheoryRegistrar(d_theoryEngine); d_cnfStream = new CVC4::prop::TseitinCnfStream(d_satSolver, registrar, Options::current()->threads > 1); - d_satSolver->setCnfStream(d_cnfStream); + d_satSolver->initialize(d_context, new TheoryProxy(this, d_theoryEngine, d_context, d_cnfStream)); } PropEngine::~PropEngine() { @@ -118,7 +119,7 @@ void PropEngine::printSatisfyingAssignment(){ ++i) { pair<Node, CnfStream::TranslationInfo> curr = *i; SatLiteral l = curr.second.literal; - if(!sign(l)) { + if(!l.isNegated()) { Node n = curr.first; SatLiteralValue value = d_satSolver->modelValue(l); Debug("prop-value") << "'" << l << "' " << value << " " << n << endl; @@ -153,22 +154,22 @@ Result PropEngine::checkSat(unsigned long& millis, unsigned long& resource) { millis = d_satTimer.elapsed(); - if( result == l_Undef ) { + if( result == SatValUnknown ) { Result::UnknownExplanation why = d_satTimer.expired() ? Result::TIMEOUT : (d_interrupted ? Result::INTERRUPTED : Result::RESOURCEOUT); return Result(Result::SAT_UNKNOWN, why); } - if( result == l_True && Debug.isOn("prop") ) { + if( result == SatValTrue && Debug.isOn("prop") ) { printSatisfyingAssignment(); } Debug("prop") << "PropEngine::checkSat() => " << result << endl; - if(result == l_True && d_theoryEngine->isIncomplete()) { + if(result == SatValTrue && d_theoryEngine->isIncomplete()) { return Result(Result::SAT_UNKNOWN, Result::INCOMPLETE); } - return Result(result == l_True ? Result::SAT : Result::UNSAT); + return Result(result == SatValTrue ? Result::SAT : Result::UNSAT); } Node PropEngine::getValue(TNode node) const { @@ -178,12 +179,12 @@ Node PropEngine::getValue(TNode node) const { SatLiteral lit = d_cnfStream->getLiteral(node); SatLiteralValue v = d_satSolver->value(lit); - if(v == l_True) { + if(v == SatValTrue) { return NodeManager::currentNM()->mkConst(true); - } else if(v == l_False) { + } else if(v == SatValFalse) { return NodeManager::currentNM()->mkConst(false); } else { - Assert(v == l_Undef); + Assert(v == SatValUnknown); return Node::null(); } } @@ -203,14 +204,14 @@ bool PropEngine::hasValue(TNode node, bool& value) const { SatLiteral lit = d_cnfStream->getLiteral(node); SatLiteralValue v = d_satSolver->value(lit); - if(v == l_True) { + if(v == SatValTrue) { value = true; return true; - } else if(v == l_False) { + } else if(v == SatValFalse) { value = false; return true; } else { - Assert(v == l_Undef); + Assert(v == SatValUnknown); return false; } } diff --git a/src/prop/prop_engine.h b/src/prop/prop_engine.h index 0b5be4647..4f83888fc 100644 --- a/src/prop/prop_engine.h +++ b/src/prop/prop_engine.h @@ -27,7 +27,6 @@ #include "util/options.h" #include "util/result.h" #include "smt/modal_exception.h" - #include <sys/time.h> namespace CVC4 { @@ -37,7 +36,7 @@ class TheoryEngine; namespace prop { class CnfStream; -class SatSolver; +class DPLLSatSolverInterface; class PropEngine; @@ -132,7 +131,7 @@ class PropEngine { context::Context* d_context; /** The SAT solver proxy */ - SatSolver* d_satSolver; + DPLLSatSolverInterface* d_satSolver; /** List of all of the assertions that need to be made */ std::vector<Node> d_assertionList; diff --git a/src/prop/registrar.h b/src/prop/registrar.h new file mode 100644 index 000000000..e1fefc1bd --- /dev/null +++ b/src/prop/registrar.h @@ -0,0 +1,48 @@ +/********************* */ +/*! \file registrar.h + ** \verbatim + ** Original author: taking + ** Major contributors: mdeters + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief Class to encapsulate preregistration duties + ** + ** Class to encapsulate preregistration duties. This class permits the + ** CNF stream implementation to reach into the theory engine to + ** preregister only those terms with an associated SAT literal (at the + ** point when they get the SAT literal), without having to refer to the + ** TheoryEngine class directly. + **/ + +#include "cvc4_private.h" + +#ifndef __CVC4__PROP__REGISTRAR_H +#define __CVC4__PROP__REGISTRAR_H + +namespace CVC4 { +namespace prop { + +class Registrar { +public: + virtual void preRegister(Node n) = 0; + +};/* class Registrar */ + +class NullRegistrar: public Registrar { +public: + void preRegister(Node n) {}; + +};/* class Registrar */ + + + +}/* CVC4::prop namespace */ +}/* CVC4 namespace */ + +#endif /* __CVC4__PROP__REGISTRAR_H */ diff --git a/src/prop/sat.cpp b/src/prop/sat.cpp index 559467922..ab8be39eb 100644 --- a/src/prop/sat.cpp +++ b/src/prop/sat.cpp @@ -28,15 +28,15 @@ namespace CVC4 { namespace prop { -void SatSolver::variableNotify(SatVariable var) { - d_theoryEngine->preRegister(getNode(variableToLiteral(var))); +void TheoryProxy::variableNotify(SatVariable var) { + d_theoryEngine->preRegister(getNode(SatLiteral(var))); } -void SatSolver::theoryCheck(theory::Theory::Effort effort) { +void TheoryProxy::theoryCheck(theory::Theory::Effort effort) { d_theoryEngine->check(effort); } -void SatSolver::theoryPropagate(std::vector<SatLiteral>& output) { +void TheoryProxy::theoryPropagate(std::vector<SatLiteral>& output) { // Get the propagated literals std::vector<TNode> outputNodes; d_theoryEngine->getPropagatedLiterals(outputNodes); @@ -46,7 +46,7 @@ void SatSolver::theoryPropagate(std::vector<SatLiteral>& output) { } } -void SatSolver::explainPropagation(SatLiteral l, SatClause& explanation) { +void TheoryProxy::explainPropagation(SatLiteral l, SatClause& explanation) { TNode lNode = d_cnfStream->getNode(l); Debug("prop-explain") << "explainPropagation(" << lNode << ")" << std::endl; Node theoryExplanation = d_theoryEngine->getExplanation(lNode); @@ -54,45 +54,41 @@ void SatSolver::explainPropagation(SatLiteral l, SatClause& explanation) { if (theoryExplanation.getKind() == kind::AND) { Node::const_iterator it = theoryExplanation.begin(); Node::const_iterator it_end = theoryExplanation.end(); - explanation.push(l); + explanation.push_back(l); for (; it != it_end; ++ it) { - explanation.push(~d_cnfStream->getLiteral(*it)); + explanation.push_back(~d_cnfStream->getLiteral(*it)); } } else { - explanation.push(l); - explanation.push(~d_cnfStream->getLiteral(theoryExplanation)); + explanation.push_back(l); + explanation.push_back(~d_cnfStream->getLiteral(theoryExplanation)); } } -void SatSolver::enqueueTheoryLiteral(const SatLiteral& l) { +void TheoryProxy::enqueueTheoryLiteral(const SatLiteral& l) { Node literalNode = d_cnfStream->getNode(l); Debug("prop") << "enqueueing theory literal " << l << " " << literalNode << std::endl; Assert(!literalNode.isNull()); d_theoryEngine->assertFact(literalNode); } -SatLiteral SatSolver::getNextDecisionRequest() { +SatLiteral TheoryProxy::getNextDecisionRequest() { TNode n = d_theoryEngine->getNextDecisionRequest(); - return n.isNull() ? Minisat::lit_Undef : d_cnfStream->getLiteral(n); + return n.isNull() ? undefSatLiteral : d_cnfStream->getLiteral(n); } -bool SatSolver::theoryNeedCheck() const { +bool TheoryProxy::theoryNeedCheck() const { return d_theoryEngine->needCheck(); } -void SatSolver::setCnfStream(CnfStream* cnfStream) { - d_cnfStream = cnfStream; -} - -void SatSolver::removeClausesAboveLevel(int level) { +void TheoryProxy::removeClausesAboveLevel(int level) { d_cnfStream->removeClausesAboveLevel(level); } -TNode SatSolver::getNode(SatLiteral lit) { +TNode TheoryProxy::getNode(SatLiteral lit) { return d_cnfStream->getNode(lit); } -void SatSolver::notifyRestart() { +void TheoryProxy::notifyRestart() { d_propEngine->checkTime(); d_theoryEngine->notifyRestart(); @@ -123,7 +119,7 @@ void SatSolver::notifyRestart() { } } -void SatSolver::notifyNewLemma(SatClause& lemma) { +void TheoryProxy::notifyNewLemma(SatClause& lemma) { Assert(lemma.size() > 0); if(Options::current()->lemmaOutputChannel != NULL) { if(lemma.size() == 1) { @@ -146,7 +142,7 @@ void SatSolver::notifyNewLemma(SatClause& lemma) { } } -SatLiteral SatSolver::getNextReplayDecision() { +SatLiteral TheoryProxy::getNextReplayDecision() { #ifdef CVC4_REPLAY if(Options::current()->replayStream != NULL) { Expr e = Options::current()->replayStream->nextExpr(); @@ -156,19 +152,20 @@ SatLiteral SatSolver::getNextReplayDecision() { } } #endif /* CVC4_REPLAY */ - return Minisat::lit_Undef; + //FIXME! + return undefSatLiteral; } -void SatSolver::logDecision(SatLiteral lit) { +void TheoryProxy::logDecision(SatLiteral lit) { #ifdef CVC4_REPLAY if(Options::current()->replayLog != NULL) { - Assert(lit != Minisat::lit_Undef, "logging an `undef' decision ?!"); + Assert(lit != undefSatLiteral, "logging an `undef' decision ?!"); *Options::current()->replayLog << d_cnfStream->getNode(lit) << std::endl; } #endif /* CVC4_REPLAY */ } -void SatSolver::checkTime() { +void TheoryProxy::checkTime() { d_propEngine->checkTime(); } diff --git a/src/prop/sat.h b/src/prop/sat.h index 3f3166c14..a6bdcb309 100644 --- a/src/prop/sat.h +++ b/src/prop/sat.h @@ -29,6 +29,8 @@ #include "util/options.h" #include "util/stats.h" +#include "prop/sat_module.h" + #ifdef __CVC4_USE_MINISAT #include "prop/minisat/core/Solver.h" @@ -48,82 +50,10 @@ class CnfStream; /* Definitions of abstract types and conversion functions for SAT interface */ -#ifdef __CVC4_USE_MINISAT - -/** Type of the SAT variables */ -typedef Minisat::Var SatVariable; - -/** Type of the SAT literals */ -typedef Minisat::Lit SatLiteral; - -/** Type of the SAT clauses */ -typedef Minisat::vec<SatLiteral> SatClause; - -/** Type of a SAT variable assignment (T, F, unknown) */ -typedef Minisat::lbool SatLiteralValue; - /** - * Returns the variable of the literal. - * @param lit the literal + * The proxy class that allows the SatSolver to communicate with the theories */ -inline SatVariable literalToVariable(SatLiteral lit) { - return Minisat::var(lit); -} - -inline SatLiteral variableToLiteral(SatVariable var) { - return Minisat::mkLit(var); -} - -inline bool literalSign(SatLiteral lit) { - return Minisat::sign(lit); -} - -static inline size_t -hashSatLiteral(const SatLiteral& literal) { - return (size_t) Minisat::toInt(literal); -} - -inline std::string stringOfLiteralValue(SatLiteralValue val) { - if( val == l_False ) { - return "0"; - } else if (val == l_True ) { - return "1"; - } else { // unknown - return "_"; - } -} -#endif /* __CVC4_USE_MINISAT */ - -/** Interface encapsulating the "input" to the solver, e.g., from the - * CNF converter. - * - * TODO: Is it possible to push the typedefs of SatClause and SatVariable - * into here, somehow? - */ -class SatInputInterface { -public: - /** Virtual destructor to make g++ happy */ - virtual ~SatInputInterface() { } - /** Assert a clause in the solver. */ - virtual void addClause(SatClause& clause, bool removable) = 0; - /** Create a new boolean variable in the solver. */ - virtual SatVariable newVar(bool theoryAtom = false) = 0; - /** Get the current user assertion level of the solver */ - virtual int getAssertionLevel() const = 0; - /** Unregister the variable (of the literal) from solving */ - virtual void unregisterVar(SatLiteral lit) = 0; - /** Register the variable (of the literal) for solving */ - virtual void renewVar(SatLiteral lit, int level = -1) = 0; - /** Interrupt the solver */ - virtual void interrupt() = 0; -}; - -/** - * The proxy class that allows us to modify the internals of the SAT solver. - * It's only accessible from the PropEngine, and should be treated with major - * care. - */ -class SatSolver : public SatInputInterface { +class TheoryProxy { /** The prop engine we are using */ PropEngine* d_propEngine; @@ -143,96 +73,20 @@ class SatSolver : public SatInputInterface { */ std::hash_set<Node, NodeHashFunction> d_shared; - /* Pointer to the concrete SAT solver. Including this via the - preprocessor saves us a level of indirection vs, e.g., defining a - sub-class for each solver. */ - -#ifdef __CVC4_USE_MINISAT - - /** Minisat solver */ - Minisat::SimpSolver* d_minisat; - - class Statistics { - private: - ReferenceStat<uint64_t> d_statStarts, d_statDecisions; - ReferenceStat<uint64_t> d_statRndDecisions, d_statPropagations; - ReferenceStat<uint64_t> d_statConflicts, d_statClausesLiterals; - ReferenceStat<uint64_t> d_statLearntsLiterals, d_statMaxLiterals; - ReferenceStat<uint64_t> d_statTotLiterals; - public: - Statistics() : - d_statStarts("sat::starts"), - d_statDecisions("sat::decisions"), - d_statRndDecisions("sat::rnd_decisions"), - d_statPropagations("sat::propagations"), - d_statConflicts("sat::conflicts"), - d_statClausesLiterals("sat::clauses_literals"), - d_statLearntsLiterals("sat::learnts_literals"), - d_statMaxLiterals("sat::max_literals"), - d_statTotLiterals("sat::tot_literals") - { - StatisticsRegistry::registerStat(&d_statStarts); - StatisticsRegistry::registerStat(&d_statDecisions); - StatisticsRegistry::registerStat(&d_statRndDecisions); - StatisticsRegistry::registerStat(&d_statPropagations); - StatisticsRegistry::registerStat(&d_statConflicts); - StatisticsRegistry::registerStat(&d_statClausesLiterals); - StatisticsRegistry::registerStat(&d_statLearntsLiterals); - StatisticsRegistry::registerStat(&d_statMaxLiterals); - StatisticsRegistry::registerStat(&d_statTotLiterals); - } - ~Statistics() { - StatisticsRegistry::unregisterStat(&d_statStarts); - StatisticsRegistry::unregisterStat(&d_statDecisions); - StatisticsRegistry::unregisterStat(&d_statRndDecisions); - StatisticsRegistry::unregisterStat(&d_statPropagations); - StatisticsRegistry::unregisterStat(&d_statConflicts); - StatisticsRegistry::unregisterStat(&d_statClausesLiterals); - StatisticsRegistry::unregisterStat(&d_statLearntsLiterals); - StatisticsRegistry::unregisterStat(&d_statMaxLiterals); - StatisticsRegistry::unregisterStat(&d_statTotLiterals); - } - void init(Minisat::SimpSolver* d_minisat){ - d_statStarts.setData(d_minisat->starts); - d_statDecisions.setData(d_minisat->decisions); - d_statRndDecisions.setData(d_minisat->rnd_decisions); - d_statPropagations.setData(d_minisat->propagations); - d_statConflicts.setData(d_minisat->conflicts); - d_statClausesLiterals.setData(d_minisat->clauses_literals); - d_statLearntsLiterals.setData(d_minisat->learnts_literals); - d_statMaxLiterals.setData(d_minisat->max_literals); - d_statTotLiterals.setData(d_minisat->tot_literals); - } - }; - Statistics d_statistics; - -#endif /* __CVC4_USE_MINISAT */ - -protected: - public: - /** Hash function for literals */ - struct SatLiteralHashFunction { - inline size_t operator()(const SatLiteral& literal) const; - }; - - SatSolver(PropEngine* propEngine, - TheoryEngine* theoryEngine, - context::Context* context); - - virtual ~SatSolver(); + TheoryProxy(PropEngine* propEngine, + TheoryEngine* theoryEngine, + context::Context* context, + CnfStream* cnfStream); - SatLiteralValue solve(unsigned long& resource); + ~TheoryProxy(); - void addClause(SatClause& clause, bool removable); - - SatVariable newVar(bool theoryAtom = false); void theoryCheck(theory::Theory::Effort effort); void explainPropagation(SatLiteral l, SatClause& explanation); - void theoryPropagate(std::vector<SatLiteral>& output); + void theoryPropagate(SatClause& output); void enqueueTheoryLiteral(const SatLiteral& l); @@ -240,20 +94,6 @@ public: bool theoryNeedCheck() const; - void setCnfStream(CnfStream* cnfStream); - - /** Call value() during the search.*/ - SatLiteralValue value(SatLiteral l); - - /** Call modelValue() when the search is done.*/ - SatLiteralValue modelValue(SatLiteral l); - - int getAssertionLevel() const; - - void push(); - - void pop(); - void removeClausesAboveLevel(int level); /** @@ -265,8 +105,6 @@ public: void renewVar(SatLiteral lit, int level = -1); - void interrupt(); - TNode getNode(SatLiteral lit); void notifyRestart(); @@ -283,114 +121,26 @@ public: /* Functions that delegate to the concrete SAT solver. */ -#ifdef __CVC4_USE_MINISAT - -inline SatSolver::SatSolver(PropEngine* propEngine, - TheoryEngine* theoryEngine, - context::Context* context) : +inline TheoryProxy::TheoryProxy(PropEngine* propEngine, + TheoryEngine* theoryEngine, + context::Context* context, + CnfStream* cnfStream) : d_propEngine(propEngine), - d_cnfStream(NULL), + d_cnfStream(cnfStream), d_theoryEngine(theoryEngine), - d_context(context), - d_statistics() -{ - // Create the solver - d_minisat = new Minisat::SimpSolver(this, d_context, - Options::current()->incrementalSolving); - // Setup the verbosity - d_minisat->verbosity = (Options::current()->verbosity > 0) ? 1 : -1; - - // Setup the random decision parameters - d_minisat->random_var_freq = Options::current()->satRandomFreq; - d_minisat->random_seed = Options::current()->satRandomSeed; - - // Give access to all possible options in the sat solver - d_minisat->var_decay = Options::current()->satVarDecay; - d_minisat->clause_decay = Options::current()->satClauseDecay; - d_minisat->restart_first = Options::current()->satRestartFirst; - d_minisat->restart_inc = Options::current()->satRestartInc; - - d_statistics.init(d_minisat); -} - -inline SatSolver::~SatSolver() { - delete d_minisat; -} - -inline SatLiteralValue SatSolver::solve(unsigned long& resource) { - Trace("limit") << "SatSolver::solve(): have limit of " << resource << " conflicts" << std::endl; - if(resource == 0) { - d_minisat->budgetOff(); - } else { - d_minisat->setConfBudget(resource); - } - Minisat::vec<SatLiteral> empty; - unsigned long conflictsBefore = d_minisat->conflicts; - SatLiteralValue result = d_minisat->solveLimited(empty); - d_minisat->clearInterrupt(); - resource = d_minisat->conflicts - conflictsBefore; - Trace("limit") << "SatSolver::solve(): it took " << resource << " conflicts" << std::endl; - return result; -} - -inline void SatSolver::addClause(SatClause& clause, bool removable) { - d_minisat->addClause(clause, removable); -} - -inline SatVariable SatSolver::newVar(bool theoryAtom) { - return d_minisat->newVar(true, true, theoryAtom); -} - -inline SatLiteralValue SatSolver::value(SatLiteral l) { - return d_minisat->value(l); -} - -inline SatLiteralValue SatSolver::modelValue(SatLiteral l) { - return d_minisat->modelValue(l); -} - -inline void SatSolver::push() { - d_minisat->push(); -} - -inline void SatSolver::pop() { - d_minisat->pop(); -} - -inline int SatSolver::getAssertionLevel() const { - return d_minisat->getAssertionLevel(); -} - -inline void SatSolver::unregisterVar(SatLiteral lit) { - d_minisat->unregisterVar(lit); -} - -inline void SatSolver::renewVar(SatLiteral lit, int level) { - d_minisat->renewVar(lit, level); -} - -inline void SatSolver::interrupt() { - d_minisat->interrupt(); -} - -#endif /* __CVC4_USE_MINISAT */ - -inline size_t -SatSolver::SatLiteralHashFunction::operator()(const SatLiteral& literal) const { - return hashSatLiteral(literal); -} + d_context(context) +{} }/* CVC4::prop namespace */ inline std::ostream& operator <<(std::ostream& out, prop::SatLiteral lit) { - const char * s = (prop::literalSign(lit)) ? "~" : " "; - out << s << prop::literalToVariable(lit); + out << lit.toString(); return out; } inline std::ostream& operator <<(std::ostream& out, const prop::SatClause& clause) { out << "clause:"; - for(int i = 0; i < clause.size(); ++i) { + for(unsigned i = 0; i < clause.size(); ++i) { out << " " << clause[i]; } out << ";"; @@ -398,10 +148,23 @@ inline std::ostream& operator <<(std::ostream& out, const prop::SatClause& claus } inline std::ostream& operator <<(std::ostream& out, prop::SatLiteralValue val) { - out << prop::stringOfLiteralValue(val); + std::string str; + switch(val) { + case prop::SatValUnknown: + str = "_"; + case prop::SatValTrue: + str = "1"; + case prop::SatValFalse: + str = "0"; + default: + str = "Error"; + + out << str; return out; } +} /* prop namespace */ + }/* CVC4 namespace */ #endif /* __CVC4__PROP__SAT_H */ diff --git a/src/prop/sat_module.cpp b/src/prop/sat_module.cpp new file mode 100644 index 000000000..1c1251545 --- /dev/null +++ b/src/prop/sat_module.cpp @@ -0,0 +1,354 @@ +/********************* */ +/*! \file sat.cpp + ** \verbatim + ** Original author: cconway + ** Major contributors: dejan, taking, mdeters, lianah + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief [[ Add one-line brief description here ]] + ** + ** [[ Add lengthier description here ]] + ** \todo document this file + **/ + +#include "prop/prop_engine.h" +#include "prop/sat_module.h" +#include "context/context.h" +#include "theory/theory_engine.h" +#include "expr/expr_stream.h" +#include "prop/sat.h" + +using namespace std; + +namespace CVC4 { +namespace prop { + +string SatLiteral::toString() { + ostringstream os; + os << (isNegated()? "~" : "") << getSatVariable() << " "; + return os.str(); +} + +MinisatSatSolver::MinisatSatSolver() : + d_minisat(new BVMinisat::SimpSolver()) +{ + d_statistics.init(d_minisat); +} + +void MinisatSatSolver::addClause(SatClause& clause, bool removable) { + Debug("sat::minisat") << "Add clause " << clause <<"\n"; + BVMinisat::vec<BVMinisat::Lit> minisat_clause; + toMinisatClause(clause, minisat_clause); + d_minisat->addClause(minisat_clause); +} + +SatVariable MinisatSatSolver::newVar(bool freeze){ + return d_minisat->newVar(true, true, freeze); +} + +void MinisatSatSolver::markUnremovable(SatLiteral lit){ + d_minisat->setFrozen(BVMinisat::var(toMinisatLit(lit)), true); +} + +void MinisatSatSolver::interrupt(){ + d_minisat->interrupt(); +} + +SatLiteralValue MinisatSatSolver::solve(){ + return toSatLiteralValue(d_minisat->solve()); +} + +SatLiteralValue MinisatSatSolver::solve(long unsigned int& resource){ + Trace("limit") << "MinisatSatSolver::solve(): have limit of " << resource << " conflicts" << std::endl; + if(resource == 0) { + d_minisat->budgetOff(); + } else { + d_minisat->setConfBudget(resource); + } + BVMinisat::vec<BVMinisat::Lit> empty; + unsigned long conflictsBefore = d_minisat->conflicts; + SatLiteralValue result = toSatLiteralValue(d_minisat->solveLimited(empty)); + d_minisat->clearInterrupt(); + resource = d_minisat->conflicts - conflictsBefore; + Trace("limit") << "<MinisatSatSolver::solve(): it took " << resource << " conflicts" << std::endl; + return result; +} + +SatLiteralValue MinisatSatSolver::solve(const context::CDList<SatLiteral> & assumptions){ + Debug("sat::minisat") << "Solve with assumptions "; + context::CDList<SatLiteral>::const_iterator it = assumptions.begin(); + BVMinisat::vec<BVMinisat::Lit> assump; + for(; it!= assumptions.end(); ++it) { + SatLiteral lit = *it; + Debug("sat::minisat") << lit <<" "; + assump.push(toMinisatLit(lit)); + } + Debug("sat::minisat") <<"\n"; + + SatLiteralValue result = toSatLiteralValue(d_minisat->solve(assump)); + return result; +} + + +void MinisatSatSolver::getUnsatCore(SatClause& unsatCore) { + // TODO add assertion to check the call was after an unsat call + for (int i = 0; i < d_minisat->conflict.size(); ++i) { + unsatCore.push_back(toSatLiteral(d_minisat->conflict[i])); + } +} + +SatLiteralValue MinisatSatSolver::value(SatLiteral l){ + Unimplemented(); + return SatValUnknown; +} + +SatLiteralValue MinisatSatSolver::modelValue(SatLiteral l){ + Unimplemented(); + return SatValUnknown; +} + +void MinisatSatSolver::unregisterVar(SatLiteral lit) { + // this should only be called when user context is implemented + // in the BVSatSolver + Unreachable(); +} + +void MinisatSatSolver::renewVar(SatLiteral lit, int level) { + // this should only be called when user context is implemented + // in the BVSatSolver + + Unreachable(); +} + +int MinisatSatSolver::getAssertionLevel() const { + // we have no user context implemented so far + return 0; +} + +// converting from internal Minisat representation + +SatVariable MinisatSatSolver::toSatVariable(BVMinisat::Var var) { + if (var == var_Undef) { + return undefSatVariable; + } + return SatVariable(var); +} + +BVMinisat::Lit MinisatSatSolver::toMinisatLit(SatLiteral lit) { + if (lit == undefSatLiteral) { + return BVMinisat::lit_Undef; + } + return BVMinisat::mkLit(lit.getSatVariable(), lit.isNegated()); +} + +SatLiteral MinisatSatSolver::toSatLiteral(BVMinisat::Lit lit) { + if (lit == BVMinisat::lit_Undef) { + return undefSatLiteral; + } + + return SatLiteral(SatVariable(BVMinisat::var(lit)), + BVMinisat::sign(lit)); +} + +SatLiteralValue MinisatSatSolver::toSatLiteralValue(bool res) { + if(res) return SatValTrue; + else return SatValFalse; +} + +SatLiteralValue MinisatSatSolver::toSatLiteralValue(BVMinisat::lbool res) { + if(res == (BVMinisat::lbool((uint8_t)0))) return SatValTrue; + if(res == (BVMinisat::lbool((uint8_t)2))) return SatValUnknown; + Assert(res == (BVMinisat::lbool((uint8_t)1))); + return SatValFalse; +} + +void MinisatSatSolver::toMinisatClause(SatClause& clause, + BVMinisat::vec<BVMinisat::Lit>& minisat_clause) { + for (unsigned i = 0; i < clause.size(); ++i) { + minisat_clause.push(toMinisatLit(clause[i])); + } + Assert(clause.size() == minisat_clause.size()); +} + +void MinisatSatSolver::toSatClause(BVMinisat::vec<BVMinisat::Lit>& clause, + SatClause& sat_clause) { + for (int i = 0; i < clause.size(); ++i) { + sat_clause.push_back(toSatLiteral(clause[i])); + } + Assert(clause.size() == sat_clause.size()); +} + + +//// DPllMinisatSatSolver + +DPLLMinisatSatSolver::DPLLMinisatSatSolver() : + d_minisat(NULL), + d_theoryProxy(NULL), + d_context(NULL) +{} + +DPLLMinisatSatSolver::~DPLLMinisatSatSolver() { + delete d_minisat; +} + +SatVariable DPLLMinisatSatSolver::toSatVariable(Minisat::Var var) { + if (var == var_Undef) { + return undefSatVariable; + } + return SatVariable(var); +} + +Minisat::Lit DPLLMinisatSatSolver::toMinisatLit(SatLiteral lit) { + if (lit == undefSatLiteral) { + return Minisat::lit_Undef; + } + return Minisat::mkLit(lit.getSatVariable(), lit.isNegated()); +} + +SatLiteral DPLLMinisatSatSolver::toSatLiteral(Minisat::Lit lit) { + if (lit == Minisat::lit_Undef) { + return undefSatLiteral; + } + + return SatLiteral(SatVariable(Minisat::var(lit)), + Minisat::sign(lit)); +} + +SatLiteralValue DPLLMinisatSatSolver::toSatLiteralValue(bool res) { + if(res) return SatValTrue; + else return SatValFalse; +} + +SatLiteralValue DPLLMinisatSatSolver::toSatLiteralValue(Minisat::lbool res) { + if(res == (Minisat::lbool((uint8_t)0))) return SatValTrue; + if(res == (Minisat::lbool((uint8_t)2))) return SatValUnknown; + Assert(res == (Minisat::lbool((uint8_t)1))); + return SatValFalse; +} + + +void DPLLMinisatSatSolver::toMinisatClause(SatClause& clause, + Minisat::vec<Minisat::Lit>& minisat_clause) { + for (unsigned i = 0; i < clause.size(); ++i) { + minisat_clause.push(toMinisatLit(clause[i])); + } + Assert(clause.size() == minisat_clause.size()); +} + +void DPLLMinisatSatSolver::toSatClause(Minisat::vec<Minisat::Lit>& clause, + SatClause& sat_clause) { + for (int i = 0; i < clause.size(); ++i) { + sat_clause.push_back(toSatLiteral(clause[i])); + } + Assert(clause.size() == sat_clause.size()); +} + + +void DPLLMinisatSatSolver::initialize(context::Context* context, TheoryProxy* theoryProxy) +{ + + d_context = context; + + // Create the solver + d_minisat = new Minisat::SimpSolver(theoryProxy, d_context, + Options::current()->incrementalSolving); + // Setup the verbosity + d_minisat->verbosity = (Options::current()->verbosity > 0) ? 1 : -1; + + // Setup the random decision parameters + d_minisat->random_var_freq = Options::current()->satRandomFreq; + d_minisat->random_seed = Options::current()->satRandomSeed; + // Give access to all possible options in the sat solver + d_minisat->var_decay = Options::current()->satVarDecay; + d_minisat->clause_decay = Options::current()->satClauseDecay; + d_minisat->restart_first = Options::current()->satRestartFirst; + d_minisat->restart_inc = Options::current()->satRestartInc; + + d_statistics.init(d_minisat); +} + +void DPLLMinisatSatSolver::addClause(SatClause& clause, bool removable) { + Minisat::vec<Minisat::Lit> minisat_clause; + toMinisatClause(clause, minisat_clause); + d_minisat->addClause(minisat_clause, removable); +} + +SatVariable DPLLMinisatSatSolver::newVar(bool theoryAtom) { + return d_minisat->newVar(true, true, theoryAtom); +} + + +SatLiteralValue DPLLMinisatSatSolver::solve(unsigned long& resource) { + Trace("limit") << "SatSolver::solve(): have limit of " << resource << " conflicts" << std::endl; + if(resource == 0) { + d_minisat->budgetOff(); + } else { + d_minisat->setConfBudget(resource); + } + Minisat::vec<Minisat::Lit> empty; + unsigned long conflictsBefore = d_minisat->conflicts; + SatLiteralValue result = toSatLiteralValue(d_minisat->solveLimited(empty)); + d_minisat->clearInterrupt(); + resource = d_minisat->conflicts - conflictsBefore; + Trace("limit") << "SatSolver::solve(): it took " << resource << " conflicts" << std::endl; + return result; +} + +SatLiteralValue DPLLMinisatSatSolver::solve() { + d_minisat->budgetOff(); + return toSatLiteralValue(d_minisat->solve()); +} + + +void DPLLMinisatSatSolver::interrupt() { + d_minisat->interrupt(); +} + +SatLiteralValue DPLLMinisatSatSolver::value(SatLiteral l) { + return toSatLiteralValue(d_minisat->value(toMinisatLit(l))); +} + +SatLiteralValue DPLLMinisatSatSolver::modelValue(SatLiteral l){ + return toSatLiteralValue(d_minisat->modelValue(toMinisatLit(l))); +} + + +/** Incremental interface */ + +int DPLLMinisatSatSolver::getAssertionLevel() const { + return d_minisat->getAssertionLevel(); +} + +void DPLLMinisatSatSolver::push() { + d_minisat->push(); +} + +void DPLLMinisatSatSolver::pop(){ + d_minisat->pop(); +} + +void DPLLMinisatSatSolver::unregisterVar(SatLiteral lit) { + d_minisat->unregisterVar(toMinisatLit(lit)); +} + +void DPLLMinisatSatSolver::renewVar(SatLiteral lit, int level) { + d_minisat->renewVar(toMinisatLit(lit), level); +} + +MinisatSatSolver* SatSolverFactory::createMinisat() { + return new MinisatSatSolver(); +} + +DPLLMinisatSatSolver* SatSolverFactory::createDPLLMinisat(){ + return new DPLLMinisatSatSolver(); +} + + +}/* CVC4::prop namespace */ +}/* CVC4 namespace */ diff --git a/src/prop/sat_module.h b/src/prop/sat_module.h new file mode 100644 index 000000000..94e39e5c6 --- /dev/null +++ b/src/prop/sat_module.h @@ -0,0 +1,401 @@ +/********************* */ +/*! \file sat_module.h + ** \verbatim + ** Original author: lianah + ** Major contributors: + ** Minor contributors (to current version): + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief SAT Solver. + ** + ** SAT Solver. + **/ + +#include "cvc4_private.h" + +#ifndef __CVC4__PROP__SAT_MODULE_H +#define __CVC4__PROP__SAT_MODULE_H + +#include <stdint.h> +#include "util/options.h" +#include "util/stats.h" + + +// DPLLT Minisat +#include "prop/minisat/core/Solver.h" +#include "prop/minisat/core/SolverTypes.h" +#include "prop/minisat/simp/SimpSolver.h" + +// BV Minisat +#include "prop/bvminisat/core/Solver.h" +#include "prop/bvminisat/core/SolverTypes.h" +#include "prop/bvminisat/simp/SimpSolver.h" + + +namespace CVC4 { +namespace prop { + +class TheoryProxy; + +enum SatLiteralValue { + SatValUnknown, + SatValTrue, + SatValFalse +}; + + +typedef uint64_t SatVariable; +// special constant +const SatVariable undefSatVariable = SatVariable(-1); + +class SatLiteral { + uint64_t d_value; +public: + SatLiteral() : + d_value(undefSatVariable) + {} + + SatLiteral(SatVariable var, bool negated = false) { d_value = var + var + (int)negated; } + SatLiteral operator~() { + return SatLiteral(getSatVariable(), !isNegated()); + } + bool operator==(const SatLiteral& other) const { + return d_value == other.d_value; + } + bool operator!=(const SatLiteral& other) const { + return !(*this == other); + } + std::string toString(); + bool isNegated() const { return d_value & 1; } + size_t toHash() const {return (size_t)d_value; } + bool isNull() const { return d_value == (uint64_t)-1; } + SatVariable getSatVariable() const {return d_value >> 1; } +}; + +// special constant +const SatLiteral undefSatLiteral = SatLiteral(undefSatVariable); + + +struct SatLiteralHashFunction { + inline size_t operator() (const SatLiteral& literal) const { + return literal.toHash(); + } +}; + +typedef std::vector<SatLiteral> SatClause; + + + +class SatSolverInterface { +public: + /** Virtual destructor to make g++ happy */ + virtual ~SatSolverInterface() { } + + /** Assert a clause in the solver. */ + virtual void addClause(SatClause& clause, bool removable) = 0; + + /** Create a new boolean variable in the solver. */ + virtual SatVariable newVar(bool theoryAtom = false) = 0; + + + /** Check the satisfiability of the added clauses */ + virtual SatLiteralValue solve() = 0; + + /** Check the satisfiability of the added clauses */ + virtual SatLiteralValue solve(long unsigned int&) = 0; + + /** Interrupt the solver */ + virtual void interrupt() = 0; + + /** Call value() during the search.*/ + virtual SatLiteralValue value(SatLiteral l) = 0; + + /** Call modelValue() when the search is done.*/ + virtual SatLiteralValue modelValue(SatLiteral l) = 0; + + virtual void unregisterVar(SatLiteral lit) = 0; + + virtual void renewVar(SatLiteral lit, int level = -1) = 0; + + virtual int getAssertionLevel() const = 0; + +}; + + +class BVSatSolverInterface: public SatSolverInterface { +public: + virtual SatLiteralValue solve(const context::CDList<SatLiteral> & assumptions) = 0; + + virtual void markUnremovable(SatLiteral lit) = 0; + + virtual void getUnsatCore(SatClause& unsatCore) = 0; +}; + + +class DPLLSatSolverInterface: public SatSolverInterface { +public: + virtual void initialize(context::Context* context, prop::TheoryProxy* theoryProxy) = 0; + + virtual void push() = 0; + + virtual void pop() = 0; + +}; + +// toodo add ifdef + + +class MinisatSatSolver: public BVSatSolverInterface { + BVMinisat::SimpSolver* d_minisat; + + MinisatSatSolver(); +public: + ~MinisatSatSolver() {delete d_minisat;} + void addClause(SatClause& clause, bool removable); + + SatVariable newVar(bool theoryAtom = false); + + void markUnremovable(SatLiteral lit); + + void interrupt(); + + SatLiteralValue solve(); + SatLiteralValue solve(long unsigned int&); + SatLiteralValue solve(const context::CDList<SatLiteral> & assumptions); + void getUnsatCore(SatClause& unsatCore); + + SatLiteralValue value(SatLiteral l); + SatLiteralValue modelValue(SatLiteral l); + + + void unregisterVar(SatLiteral lit); + void renewVar(SatLiteral lit, int level = -1); + int getAssertionLevel() const; + + // helper methods for converting from the internal Minisat representation + + static SatVariable toSatVariable(BVMinisat::Var var); + static BVMinisat::Lit toMinisatLit(SatLiteral lit); + static SatLiteral toSatLiteral(BVMinisat::Lit lit); + static SatLiteralValue toSatLiteralValue(bool res); + static SatLiteralValue toSatLiteralValue(BVMinisat::lbool res); + + static void toMinisatClause(SatClause& clause, BVMinisat::vec<BVMinisat::Lit>& minisat_clause); + static void toSatClause (BVMinisat::vec<BVMinisat::Lit>& clause, SatClause& sat_clause); + + + class Statistics { + public: + ReferenceStat<uint64_t> d_statStarts, d_statDecisions; + ReferenceStat<uint64_t> d_statRndDecisions, d_statPropagations; + ReferenceStat<uint64_t> d_statConflicts, d_statClausesLiterals; + ReferenceStat<uint64_t> d_statLearntsLiterals, d_statMaxLiterals; + ReferenceStat<uint64_t> d_statTotLiterals; + ReferenceStat<int> d_statEliminatedVars; + Statistics() : + d_statStarts("theory::bv::bvminisat::starts"), + d_statDecisions("theory::bv::bvminisat::decisions"), + d_statRndDecisions("theory::bv::bvminisat::rnd_decisions"), + d_statPropagations("theory::bv::bvminisat::propagations"), + d_statConflicts("theory::bv::bvminisat::conflicts"), + d_statClausesLiterals("theory::bv::bvminisat::clauses_literals"), + d_statLearntsLiterals("theory::bv::bvminisat::learnts_literals"), + d_statMaxLiterals("theory::bv::bvminisat::max_literals"), + d_statTotLiterals("theory::bv::bvminisat::tot_literals"), + d_statEliminatedVars("theory::bv::bvminisat::eliminated_vars") + { + StatisticsRegistry::registerStat(&d_statStarts); + StatisticsRegistry::registerStat(&d_statDecisions); + StatisticsRegistry::registerStat(&d_statRndDecisions); + StatisticsRegistry::registerStat(&d_statPropagations); + StatisticsRegistry::registerStat(&d_statConflicts); + StatisticsRegistry::registerStat(&d_statClausesLiterals); + StatisticsRegistry::registerStat(&d_statLearntsLiterals); + StatisticsRegistry::registerStat(&d_statMaxLiterals); + StatisticsRegistry::registerStat(&d_statTotLiterals); + StatisticsRegistry::registerStat(&d_statEliminatedVars); + } + ~Statistics() { + StatisticsRegistry::unregisterStat(&d_statStarts); + StatisticsRegistry::unregisterStat(&d_statDecisions); + StatisticsRegistry::unregisterStat(&d_statRndDecisions); + StatisticsRegistry::unregisterStat(&d_statPropagations); + StatisticsRegistry::unregisterStat(&d_statConflicts); + StatisticsRegistry::unregisterStat(&d_statClausesLiterals); + StatisticsRegistry::unregisterStat(&d_statLearntsLiterals); + StatisticsRegistry::unregisterStat(&d_statMaxLiterals); + StatisticsRegistry::unregisterStat(&d_statTotLiterals); + StatisticsRegistry::unregisterStat(&d_statEliminatedVars); + } + + void init(BVMinisat::SimpSolver* minisat){ + d_statStarts.setData(minisat->starts); + d_statDecisions.setData(minisat->decisions); + d_statRndDecisions.setData(minisat->rnd_decisions); + d_statPropagations.setData(minisat->propagations); + d_statConflicts.setData(minisat->conflicts); + d_statClausesLiterals.setData(minisat->clauses_literals); + d_statLearntsLiterals.setData(minisat->learnts_literals); + d_statMaxLiterals.setData(minisat->max_literals); + d_statTotLiterals.setData(minisat->tot_literals); + d_statEliminatedVars.setData(minisat->eliminated_vars); + } + }; + + Statistics d_statistics; + friend class SatSolverFactory; +}; + + +// class PicosatSatSolver: public SatSolverInterface { + +// public: +// PicosatSatSolver(); + +// void addClause(SatClause& clause, bool removable); + +// SatVariable newVar(bool theoryAtom = false); + +// void markUnremovable(SatLiteral lit); + +// SatLiteralValue solve(unsigned long& resource = 0); + +// SatLiteralValue solve(const std::vector<SatLiteral>& assumptions); + +// void interrupt(); + +// SatLiteralValue value(SatLiteral l); + +// SatLiteralValue modelValue(SatLiteral l); + +// }; + + + +class DPLLMinisatSatSolver : public DPLLSatSolverInterface { + + /** The SatSolver used */ + Minisat::SimpSolver* d_minisat; + + + /** The SatSolver uses this to communicate with the theories */ + TheoryProxy* d_theoryProxy; + + /** Context we will be using to synchronzie the sat solver */ + context::Context* d_context; + + DPLLMinisatSatSolver (); + +public: + + ~DPLLMinisatSatSolver(); + static SatVariable toSatVariable(Minisat::Var var); + static Minisat::Lit toMinisatLit(SatLiteral lit); + static SatLiteral toSatLiteral(Minisat::Lit lit); + static SatLiteralValue toSatLiteralValue(bool res); + static SatLiteralValue toSatLiteralValue(Minisat::lbool res); + + static void toMinisatClause(SatClause& clause, Minisat::vec<Minisat::Lit>& minisat_clause); + static void toSatClause (Minisat::vec<Minisat::Lit>& clause, SatClause& sat_clause); + + void initialize(context::Context* context, TheoryProxy* theoryProxy); + + void addClause(SatClause& clause, bool removable); + + SatVariable newVar(bool theoryAtom = false); + + SatLiteralValue solve(); + SatLiteralValue solve(long unsigned int&); + + void interrupt(); + + SatLiteralValue value(SatLiteral l); + + SatLiteralValue modelValue(SatLiteral l); + + /** Incremental interface */ + + int getAssertionLevel() const; + + void push(); + + void pop(); + + void unregisterVar(SatLiteral lit); + + void renewVar(SatLiteral lit, int level = -1); + + class Statistics { + private: + ReferenceStat<uint64_t> d_statStarts, d_statDecisions; + ReferenceStat<uint64_t> d_statRndDecisions, d_statPropagations; + ReferenceStat<uint64_t> d_statConflicts, d_statClausesLiterals; + ReferenceStat<uint64_t> d_statLearntsLiterals, d_statMaxLiterals; + ReferenceStat<uint64_t> d_statTotLiterals; + public: + Statistics() : + d_statStarts("sat::starts"), + d_statDecisions("sat::decisions"), + d_statRndDecisions("sat::rnd_decisions"), + d_statPropagations("sat::propagations"), + d_statConflicts("sat::conflicts"), + d_statClausesLiterals("sat::clauses_literals"), + d_statLearntsLiterals("sat::learnts_literals"), + d_statMaxLiterals("sat::max_literals"), + d_statTotLiterals("sat::tot_literals") + { + StatisticsRegistry::registerStat(&d_statStarts); + StatisticsRegistry::registerStat(&d_statDecisions); + StatisticsRegistry::registerStat(&d_statRndDecisions); + StatisticsRegistry::registerStat(&d_statPropagations); + StatisticsRegistry::registerStat(&d_statConflicts); + StatisticsRegistry::registerStat(&d_statClausesLiterals); + StatisticsRegistry::registerStat(&d_statLearntsLiterals); + StatisticsRegistry::registerStat(&d_statMaxLiterals); + StatisticsRegistry::registerStat(&d_statTotLiterals); + } + ~Statistics() { + StatisticsRegistry::unregisterStat(&d_statStarts); + StatisticsRegistry::unregisterStat(&d_statDecisions); + StatisticsRegistry::unregisterStat(&d_statRndDecisions); + StatisticsRegistry::unregisterStat(&d_statPropagations); + StatisticsRegistry::unregisterStat(&d_statConflicts); + StatisticsRegistry::unregisterStat(&d_statClausesLiterals); + StatisticsRegistry::unregisterStat(&d_statLearntsLiterals); + StatisticsRegistry::unregisterStat(&d_statMaxLiterals); + StatisticsRegistry::unregisterStat(&d_statTotLiterals); + } + void init(Minisat::SimpSolver* d_minisat){ + d_statStarts.setData(d_minisat->starts); + d_statDecisions.setData(d_minisat->decisions); + d_statRndDecisions.setData(d_minisat->rnd_decisions); + d_statPropagations.setData(d_minisat->propagations); + d_statConflicts.setData(d_minisat->conflicts); + d_statClausesLiterals.setData(d_minisat->clauses_literals); + d_statLearntsLiterals.setData(d_minisat->learnts_literals); + d_statMaxLiterals.setData(d_minisat->max_literals); + d_statTotLiterals.setData(d_minisat->tot_literals); + } + }; + Statistics d_statistics; + + friend class SatSolverFactory; +}; + +class SatSolverFactory { +public: + static MinisatSatSolver* createMinisat(); + static DPLLMinisatSatSolver* createDPLLMinisat(); + //static PicosatSatSolver* createPicosat(); + //static DPLLPicosatSatSolver* createDPLLPicosat(context::Context* context); +}; + +}/* prop namespace */ +}/* CVC4 namespace */ + +#endif /* __CVC4__PROP__SAT_MODULE_H */ diff --git a/src/theory/Makefile.am b/src/theory/Makefile.am index c1a77d988..eb289937f 100644 --- a/src/theory/Makefile.am +++ b/src/theory/Makefile.am @@ -16,7 +16,7 @@ libtheory_la_SOURCES = \ theory_test_utils.h \ theory.h \ theory.cpp \ - registrar.h \ + theory_registrar.h \ rewriter.h \ rewriter_attributes.h \ rewriter.cpp \ diff --git a/src/theory/bv/Makefile.am b/src/theory/bv/Makefile.am index 08dde4349..1b8e902e0 100644 --- a/src/theory/bv/Makefile.am +++ b/src/theory/bv/Makefile.am @@ -1,22 +1,26 @@ AM_CPPFLAGS = \ -D__BUILDING_CVC4LIB \ + -D __STDC_LIMIT_MACROS \ + -D __STDC_FORMAT_MACROS \ -I@srcdir@/../../include -I@srcdir@/../.. -I@builddir@/../.. AM_CXXFLAGS = -Wall -Wno-unknown-pragmas $(FLAG_VISIBILITY_HIDDEN) noinst_LTLIBRARIES = libbv.la libbv_la_SOURCES = \ + theory_bv_utils.h \ + bv_sat.h \ + bv_sat.cpp \ + bitblast_strategies.h \ + bitblast_strategies.cpp \ theory_bv.h \ theory_bv.cpp \ - theory_bv_utils.h \ theory_bv_rewrite_rules.h \ theory_bv_rewrite_rules_core.h \ + theory_bv_rewrite_rules_arith.h \ theory_bv_type_rules.h \ theory_bv_rewriter.h \ theory_bv_rewriter.cpp \ - equality_engine.h \ - equality_engine.cpp \ - slice_manager.h \ cd_set_collection.h EXTRA_DIST = kinds diff --git a/src/theory/bv/bitblast_strategies.cpp b/src/theory/bv/bitblast_strategies.cpp new file mode 100644 index 000000000..b0a02c0a5 --- /dev/null +++ b/src/theory/bv/bitblast_strategies.cpp @@ -0,0 +1,824 @@ +/********************* */ +/*! \file bitblast_strategies.cpp + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief Implementation of bitblasting functions for various operators. + ** + ** Implementation of bitblasting functions for various operators. + **/ + +#include "bitblast_strategies.h" +#include "bv_sat.h" +#include "prop/sat_module.h" +#include "theory/booleans/theory_bool_rewriter.h" + +using namespace CVC4::prop; +using namespace CVC4::theory::bv::utils; +namespace CVC4 { +namespace theory { +namespace bv { + +/* + Purely debugging + */ + +Bits* rewriteBits(const Bits& bits) { + Bits* newbits = new Bits(); + for (unsigned i = 0; i < bits.size(); ++i) { + newbits->push_back(Rewriter::rewrite(bits[i])); + } + return newbits; +} + +Node rewrite(Node node) { + return Rewriter::rewrite(node); +} + +/* + Various helper functions that get called by the bitblasting procedures + */ + +void inline extractBits(const Bits& b, Bits& dest, unsigned lo, unsigned hi) { + Assert ( lo < b.size() && hi < b.size() && lo <= hi); + for (unsigned i = lo; i <= hi; ++i) { + dest.push_back(b[i]); + } +} + +void inline negateBits(const Bits& bits, Bits& negated_bits) { + for(int i = 0; i < bits.size(); ++i) { + negated_bits.push_back(utils::mkNot(bits[i])); + } +} + +bool inline isZero(const Bits& bits) { + for(int i = 0; i < bits.size(); ++i) { + if(bits[i] != mkFalse()) { + return false; + } + } + return true; +} + +void inline rshift(Bits& bits, unsigned amount) { + for (unsigned i = 0; i < bits.size() - amount; ++i) { + bits[i] = bits[i+amount]; + } + for(unsigned i = bits.size() - amount; i < bits.size(); ++i) { + bits[i] = mkFalse(); + } +} + +void inline lshift(Bits& bits, unsigned amount) { + for (int i = bits.size() - 1; i >= amount ; --i) { + bits[i] = bits[i-amount]; + } + for(unsigned i = 0; i < amount; ++i) { + bits[i] = mkFalse(); + } +} + +void inline makeZero(Bits& bits, unsigned width) { + Assert(bits.size() == 0); + for(unsigned i = 0; i < width; ++i) { + bits.push_back(mkFalse()); + } +} + + +/** + * Constructs a simple ripple carry adder + * + * @param a first term to be added + * @param b second term to be added + * @param sum the sum + * @param carry the carry-in bit + * + * @return the carry-out + */ +Node inline rippleCarryAdder(const Bits&a, const Bits& b, Bits& res, Node carry) { + Assert(res.size() == 0 && a.size() == b.size()); + + for (unsigned i = 0 ; i < a.size(); ++i) { + Node sum = mkXor(mkXor(a[i], b[i]), carry); + carry = mkOr( mkAnd(a[i], b[i]), + mkAnd( mkXor(a[i], b[i]), + carry)); + res.push_back(sum); + } + + return carry; +} + + +Node inline uLessThanBB(const Bits&a, const Bits& b, bool orEqual) { + Assert (a.size() && b.size()); + + Node res = mkNode(kind::AND, mkNode(kind::NOT, a[0]), b[0]); + + if(orEqual) { + res = mkNode(kind::OR, res, mkNode(kind::IFF, a[0], b[0])); + } + + for (unsigned i = 1; i < a.size(); ++i) { + // a < b iff ( a[i] <-> b[i] AND a[i-1:0] < b[i-1:0]) OR (~a[i] AND b[i]) + res = mkNode(kind::OR, + mkNode(kind::AND, mkNode(kind::IFF, a[i], b[i]), res), + mkNode(kind::AND, mkNode(kind::NOT, a[i]), b[i])); + } + return res; +} + +Node inline sLessThanBB(const Bits&a, const Bits& b, bool orEqual) { + Assert (a.size() && b.size()); + if (a.size() == 1) { + if(orEqual) { + return mkNode(kind::OR, + mkNode(kind::IFF, a[0], b[0]), + mkNode(kind::AND, a[0], mkNode(kind::NOT, b[0]))); + } + + return mkNode(kind::AND, a[0], mkNode(kind::NOT, b[0])); + } + unsigned n = a.size() - 1; + Bits a1, b1; + extractBits(a, a1, 0, n-1); + extractBits(b, b1, 0, n-1); + + // unsigned comparison of the first n-1 bits + Node ures = uLessThanBB(a1, b1, orEqual); + Node res = mkNode(kind::OR, + // a b have the same sign + mkNode(kind::AND, + mkNode(kind::IFF, a[n], b[n]), + ures), + // a is negative and b positive + mkNode(kind::AND, + a[n], + mkNode(kind::NOT, b[n]))); + return res; +} + + +/* + Atom bitblasting strategies + */ + + +Node UndefinedAtomBBStrategy(TNode node, Bitblaster* bb) { + Debug("bitvector") << "TheoryBV::Bitblaster Undefined bitblasting strategy for kind: " + << node.getKind() << "\n"; + Unreachable(); +} + +Node DefaultEqBB(TNode node, Bitblaster* bb) { + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + + Assert(node.getKind() == kind::EQUAL); + Bits lhs, rhs; + bb->bbTerm(node[0], lhs); + bb->bbTerm(node[1], rhs); + + Assert(lhs.size() == rhs.size()); + + NodeManager* nm = NodeManager::currentNM(); + + std::vector<Node> bits_eq; + for (unsigned i = 0; i < lhs.size(); i++) { + Node bit_eq = nm->mkNode(kind::IFF, lhs[i], rhs[i]); + bits_eq.push_back(bit_eq); + } + Node bv_eq = utils::mkAnd(bits_eq); + return bv_eq; +} + + +Node AdderUltBB(TNode node, Bitblaster* bb) { + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_ULT); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size()); + + // a < b <=> ~ (add(a, ~b, 1).carry_out) + Bits not_b; + negateBits(b, not_b); + Node carry = mkTrue(); + + for (unsigned i = 0 ; i < a.size(); ++i) { + carry = mkOr( mkAnd(a[i], not_b[i]), + mkAnd( mkXor(a[i], not_b[i]), + carry)); + } + return mkNot(carry); +} + + +Node DefaultUltBB(TNode node, Bitblaster* bb) { + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_ULT); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size()); + + // construct bitwise comparison + Node res = uLessThanBB(a, b, false); + return res; +} + +Node DefaultUleBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_ULE); + Bits a, b; + + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size()); + // construct bitwise comparison + Node res = uLessThanBB(a, b, true); + return res; +} + +Node DefaultUgtBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + // should be rewritten + Unimplemented(); +} +Node DefaultUgeBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + // should be rewritten + Unimplemented(); +} + +Node DefaultSltBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size()); + + Node res = sLessThanBB(a, b, false); + return res; +} + +Node DefaultSleBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size()); + + Node res = sLessThanBB(a, b, true); + return res; +} + +Node DefaultSgtBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + // should be rewritten + Unimplemented(); +} + +Node DefaultSgeBB(TNode node, Bitblaster* bb){ + Debug("bitvector-bb") << "Bitblasting node " << node << "\n"; + // should be rewritten + Unimplemented(); +} + + +/// Term bitblasting strategies + +void UndefinedTermBBStrategy(TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Undefined bitblasting strategy for kind: " + << node.getKind() << "\n"; + Unreachable(); +} + +void DefaultVarBB (TNode node, Bits& bits, Bitblaster* bb) { + Assert (node.getKind() == kind::VARIABLE); + Assert(bits.size() == 0); + + for (unsigned i = 0; i < utils::getSize(node); ++i) { + bits.push_back(utils::mkBitOf(node, i)); + } + + Debug("bitvector-bb") << "theory::bv::DefaultVarBB bitblasting " << node << "\n"; + Debug("bitvector-bb") << " with bits " << toString(bits); +} + +void DefaultConstBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultConstBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::CONST_BITVECTOR); + Assert(bits.size() == 0); + + NodeManager* nm = NodeManager::currentNM(); + for (unsigned i = 0; i < utils::getSize(node); ++i) { + Integer bit = node.getConst<BitVector>().extract(i, i).getValue(); + if(bit == Integer(0)){ + bits.push_back(utils::mkFalse()); + } else { + Assert (bit == Integer(1)); + bits.push_back(utils::mkTrue()); + } + } + Debug("bitvector-bb") << "with bits: " << toString(bits) << "\n"; +} + + +void DefaultNotBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultNotBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_NOT); + Assert(bits.size() == 0); + Bits bv; + bb->bbTerm(node[0], bv); + negateBits(bv, bits); +} + +void DefaultConcatBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultConcatBB bitblasting " << node << "\n"; + Assert(bits.size() == 0); + + Assert (node.getKind() == kind::BITVECTOR_CONCAT); + for (int i = node.getNumChildren() -1 ; i >= 0; --i ) { + TNode current = node[i]; + Bits current_bits; + bb->bbTerm(current, current_bits); + + for(unsigned j = 0; j < utils::getSize(current); ++j) { + bits.push_back(current_bits[j]); + } + } + Assert (bits.size() == utils::getSize(node)); + Debug("bitvector-bb") << "with bits: " << toString(bits) << "\n"; +} + + +void DefaultAndBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultAndBB bitblasting " << node << "\n"; + + Assert(node.getNumChildren() == 2 && + node.getKind() == kind::BITVECTOR_AND && + bits.size() == 0); + + Bits lhs, rhs; + bb->bbTerm(node[0], rhs); + bb->bbTerm(node[1], lhs); + + Assert (lhs.size() == rhs.size()); + for (unsigned i = 0; i < lhs.size(); ++i) { + bits.push_back(utils::mkAnd(lhs[i], rhs[i])); + } + +} + +void DefaultOrBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultOrBB bitblasting " << node << "\n"; + + Assert(node.getNumChildren() == 2 && + node.getKind() == kind::BITVECTOR_OR && + bits.size() == 0); + + Bits lhs, rhs; + bb->bbTerm(node[0], lhs); + bb->bbTerm(node[1], rhs); + Assert(lhs.size() == rhs.size()); + + for (unsigned i = 0; i < lhs.size(); ++i) { + bits.push_back(utils::mkOr(lhs[i], rhs[i])); + } +} + +void DefaultXorBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultXorBB bitblasting " << node << "\n"; + + Assert(node.getNumChildren() == 2 && + node.getKind() == kind::BITVECTOR_XOR && + bits.size() == 0); + + Bits lhs, rhs; + bb->bbTerm(node[0], lhs); + bb->bbTerm(node[1], rhs); + Assert(lhs.size() == rhs.size()); + + for (unsigned i = 0; i < lhs.size(); ++i) { + bits.push_back(utils::mkXor(lhs[i], rhs[i])); + } +} + +void DefaultXnorBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultXnorBB bitblasting " << node << "\n"; + + Assert(node.getNumChildren() == 2 && + node.getKind() == kind::BITVECTOR_XNOR && + bits.size() == 0); + Bits lhs, rhs; + bb->bbTerm(node[0], lhs); + bb->bbTerm(node[1], rhs); + Assert(lhs.size() == rhs.size()); + + for (unsigned i = 0; i < lhs.size(); ++i) { + bits.push_back(utils::mkNode(kind::IFF, lhs[i], rhs[i])); + } +} + + +void DefaultNandBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} +void DefaultNorBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} +void DefaultCompBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: DefaultCompBB bitblasting "<< node << "\n"; + + Assert(getSize(node) == 1 && bits.size() == 0 && node.getKind() == kind::BITVECTOR_COMP); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + std::vector<Node> bit_eqs; + NodeManager* nm = NodeManager::currentNM(); + for (unsigned i = 0; i < a.size(); ++i) { + Node eq = nm->mkNode(kind::IFF, a[i], b[i]); + bit_eqs.push_back(eq); + } + Node a_eq_b = mkAnd(bit_eqs); + bits.push_back(a_eq_b); +} + +void DefaultMultBB (TNode node, Bits& res, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: DefaultMultBB bitblasting "<< node << "\n"; + Assert(res.size() == 0 && + node.getKind() == kind::BITVECTOR_MULT); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + // constructs a simple shift and add multiplier building the result in + // in res + + for (unsigned i = 0; i < a.size(); ++i) { + res.push_back(mkNode(kind::AND, b[0], a[i])); + } + + for(unsigned k = 1; k < res.size(); ++k) { + Node carry_in = mkFalse(); + Node carry_out; + for(unsigned j = 0; j < res.size() -k; ++j) { + Node aj = mkAnd(a[j], b[k]); + carry_out = mkOr(mkAnd(res[j+k], aj), + mkAnd( mkXor(res[j+k], aj), carry_in)); + res[j+k] = mkXor(mkXor(res[j+k], aj), carry_in); + carry_in = carry_out; + } + } + Debug("bitvector-bb") << "with bits: " << toString(res) << "\n"; +} + +void DefaultPlusBB (TNode node, Bits& res, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaulPlusBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_PLUS && + res.size() == 0); + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + Assert(a.size() == b.size() && utils::getSize(node) == a.size()); + rippleCarryAdder(a, b, res, mkFalse()); +} + + +void DefaultSubBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefautSubBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_SUB && bits.size() == 0); + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + Assert(a.size() == b.size() && utils::getSize(node) == a.size()); + + // bvsub a b = adder(a, ~b, 1) + Bits not_b; + negateBits(b, not_b); + Node carry = utils::mkTrue(); + rippleCarryAdder(a, not_b, bits, mkTrue()); +} + +void DefaultNegBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefautNegBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_NEG); + + Bits a; + bb->bbTerm(node[0], a); + Assert(utils::getSize(node) == a.size()); + + // -a = add(~a, 0, 1). + Bits not_a; + negateBits(a, not_a); + Bits zero; + makeZero(zero, getSize(node)); + + rippleCarryAdder(not_a, zero, bits, mkTrue()); +} + +void uDivModRec(const Bits& a, const Bits& b, Bits& q, Bits& r, unsigned rec_width) { + Assert( q.size() == 0 && r.size() == 0); + + if(rec_width == 0 || isZero(a)) { + makeZero(q, a.size()); + makeZero(r, a.size()); + return; + } + + Bits q1, r1; + Bits a1 = a; + rshift(a1, 1); + + uDivModRec(a1, b, q1, r1, rec_width - 1); + // shift the quotient and remainder (i.e. multiply by two) and add 1 to remainder if a is odd + lshift(q1, 1); + lshift(r1, 1); + + + Node is_odd = mkNode(kind::IFF, a[0], mkTrue()); + Node one_if_odd = mkNode(kind::ITE, is_odd, mkTrue(), mkFalse()); + + Bits zero; + makeZero(zero, b.size()); + + Bits r1_shift_add; + // account for a being odd + rippleCarryAdder(r1, zero, r1_shift_add, one_if_odd); + // now check if the remainder is greater than b + Bits not_b; + negateBits(b, not_b); + Bits r_minus_b; + Node co1; + // use adder because we need r_minus_b anyway + co1 = rippleCarryAdder(r1_shift_add, not_b, r_minus_b, mkTrue()); + // sign is true if r1 < b + Node sign = mkNode(kind::NOT, co1); + + q1[0] = mkNode(kind::ITE, sign, q1[0], mkTrue()); + + // would be nice to have a high level ITE instead of bitwise + for(unsigned i = 0; i < a.size(); ++i) { + r1_shift_add[i] = mkNode(kind::ITE, sign, r1_shift_add[i], r_minus_b[i]); + } + + // check if a < b + + Bits a_minus_b; + Node co2 = rippleCarryAdder(a, not_b, a_minus_b, mkTrue()); + // Node a_lt_b = a_minus_b.back(); + Node a_lt_b = mkNode(kind::NOT, co2); + + for(unsigned i = 0; i < a.size(); ++i) { + Node qval = mkNode(kind::ITE, a_lt_b, mkFalse(), q1[i]); + Node rval = mkNode(kind::ITE, a_lt_b, a[i], r1_shift_add[i]); + q.push_back(qval); + r.push_back(rval); + } + +} + +void DefaultUdivBB (TNode node, Bits& q, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefautUdivBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_UDIV && q.size() == 0); + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + Bits r; + uDivModRec(a, b, q, r, getSize(node)); + + // cache the remainder in case we need it later + Node remainder = mkNode(kind::BITVECTOR_UREM, node[0], node[1]); + bb->cacheTermDef(remainder, r); +} + +void DefaultUremBB (TNode node, Bits& rem, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefautUremBB bitblasting " << node << "\n"; + Assert(node.getKind() == kind::BITVECTOR_UREM && rem.size() == 0); + + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + Bits q; + uDivModRec(a, b, q, rem, getSize(node)); + + // cache the quotient in case we need it later + Node quotient = mkNode(kind::BITVECTOR_UDIV, node[0], node[1]); + bb->cacheTermDef(quotient, q); +} + + +void DefaultSdivBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} +void DefaultSremBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} +void DefaultSmodBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} + +void DefaultShlBB (TNode node, Bits& res, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultShlBB bitblasting " << node << "\n"; + Assert (node.getKind() == kind::BITVECTOR_SHL && + res.size() == 0); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + res = a; + Bits prev_res; + + for(unsigned s = 0; s < b.size(); ++s) { + // barrel shift stage: at each stage you can either shift by 2^s bits + // or leave the previous stage untouched + prev_res = res; + unsigned threshold = pow(2, s); + for(unsigned i = 0; i < a.size(); ++i) { + if (i < threshold) { + // if b[s] is true then we must have shifted by at least 2^b bits so + // all bits bellow 2^s will be 0, otherwise just use previous shift value + res[i] = mkNode(kind::ITE, b[s], mkFalse(), prev_res[i]); + } else { + // if b[s]= 0, use previous value, otherwise shift by threshold bits + Assert(i >= threshold); + res[i] = mkNode(kind::ITE, mkNot(b[s]), prev_res[i], prev_res[i-threshold]); + } + } + } + Debug("bitvector-bb") << "with bits: " << toString(res) << "\n"; +} + +void DefaultLshrBB (TNode node, Bits& res, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultLshrBB bitblasting " << node << "\n"; + Assert (node.getKind() == kind::BITVECTOR_LSHR && + res.size() == 0); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + res = a; + Bits prev_res; + + for(int s = 0; s < b.size(); ++s) { + // barrel shift stage: at each stage you can either shift by 2^s bits + // or leave the previous stage untouched + prev_res = res; + int threshold = pow(2, s); + for(int i = 0; i < a.size(); ++i) { + if (i + threshold >= a.size()) { + // if b[s] is true then we must have shifted by at least 2^b bits so + // all bits above 2^s will be 0, otherwise just use previous shift value + res[i] = mkNode(kind::ITE, b[s], mkFalse(), prev_res[i]); + } else { + // if b[s]= 0, use previous value, otherwise shift by threshold bits + Assert (i+ threshold < a.size()); + res[i] = mkNode(kind::ITE, mkNot(b[s]), prev_res[i], prev_res[i+threshold]); + } + } + } + Debug("bitvector-bb") << "with bits: " << toString(res) << "\n"; +} + +void DefaultAshrBB (TNode node, Bits& res, Bitblaster* bb) { + + Debug("bitvector-bb") << "theory::bv::DefaultAshrBB bitblasting " << node << "\n"; + Assert (node.getKind() == kind::BITVECTOR_ASHR && + res.size() == 0); + Bits a, b; + bb->bbTerm(node[0], a); + bb->bbTerm(node[1], b); + + res = a; + TNode sign_bit = a.back(); + Bits prev_res; + + for(int s = 0; s < b.size(); ++s) { + // barrel shift stage: at each stage you can either shift by 2^s bits + // or leave the previous stage untouched + prev_res = res; + int threshold = pow(2, s); + for(int i = 0; i < a.size(); ++i) { + if (i + threshold >= a.size()) { + // if b[s] is true then we must have shifted by at least 2^b bits so + // all bits above 2^s will be the sign bit, otherwise just use previous shift value + res[i] = mkNode(kind::ITE, b[s], sign_bit, prev_res[i]); + } else { + // if b[s]= 0, use previous value, otherwise shift by threshold bits + Assert (i+ threshold < a.size()); + res[i] = mkNode(kind::ITE, mkNot(b[s]), prev_res[i], prev_res[i+threshold]); + } + } + } + Debug("bitvector-bb") << "with bits: " << toString(res) << "\n"; + +} + +void DefaultExtractBB (TNode node, Bits& bits, Bitblaster* bb) { + Assert (node.getKind() == kind::BITVECTOR_EXTRACT); + Assert(bits.size() == 0); + + Bits base_bits; + bb->bbTerm(node[0], base_bits); + unsigned high = utils::getExtractHigh(node); + unsigned low = utils::getExtractLow(node); + + for (unsigned i = low; i <= high; ++i) { + bits.push_back(base_bits[i]); + } + Assert (bits.size() == high - low + 1); + + Debug("bitvector-bb") << "theory::bv::DefaultExtractBB bitblasting " << node << "\n"; + Debug("bitvector-bb") << " with bits " << toString(bits); + +} + + +void DefaultRepeatBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + // this should be rewritten + Unimplemented(); +} + +void DefaultZeroExtendBB (TNode node, Bits& res_bits, Bitblaster* bb) { + + Debug("bitvector-bb") << "theory::bv::DefaultZeroExtendBB bitblasting " << node << "\n"; + + // this should be rewritten + Unimplemented(); + +} + +void DefaultSignExtendBB (TNode node, Bits& res_bits, Bitblaster* bb) { + Debug("bitvector-bb") << "theory::bv::DefaultSignExtendBB bitblasting " << node << "\n"; + + Assert (node.getKind() == kind::BITVECTOR_SIGN_EXTEND && + res_bits.size() == 0); + + Bits bits; + bb->bbTerm(node[0], bits); + + TNode sign_bit = bits.back(); + unsigned amount = node.getOperator().getConst<BitVectorSignExtend>().signExtendAmount; + + for (unsigned i = 0; i < bits.size(); ++i ) { + res_bits.push_back(bits[i]); + } + + for (unsigned i = 0 ; i < amount ; ++i ) { + res_bits.push_back(sign_bit); + } + + Assert (res_bits.size() == amount + bits.size()); +} + +void DefaultRotateRightBB (TNode node, Bits& res, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + + Unimplemented(); +} + +void DefaultRotateLeftBB (TNode node, Bits& bits, Bitblaster* bb) { + Debug("bitvector") << "theory::bv:: Unimplemented kind " + << node.getKind() << "\n"; + Unimplemented(); +} + + +} +} +} + + diff --git a/src/theory/bv/bitblast_strategies.h b/src/theory/bv/bitblast_strategies.h new file mode 100644 index 000000000..504755e6c --- /dev/null +++ b/src/theory/bv/bitblast_strategies.h @@ -0,0 +1,112 @@ +/********************* */ +/*! \file bitblast_strategies.h + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief Implementation of bitblasting functions for various operators. + ** + ** Implementation of bitblasting functions for various operators. + **/ + +#include "cvc4_private.h" + +#ifndef __CVC4__BITBLAST__STRATEGIES_H +#define __CVC4__BITBLAST__STRATEGIES_H + + +#include "expr/node.h" +#include "prop/sat_module.h" + +namespace CVC4 { + + +namespace theory { +namespace bv { + +class Bitblaster; + + +typedef std::vector<Node> Bits; + + +/** + * Default Atom Bitblasting strategies: + * + * @param node the atom to be bitblasted + * @param markerLit the marker literal corresponding to the atom + * @param bb the bitblaster + */ + +Node UndefinedAtomBBStrategy (TNode node, Bitblaster* bb); +Node DefaultEqBB(TNode node, Bitblaster* bb); + +Node DefaultUltBB(TNode node, Bitblaster* bb); +Node DefaultUleBB(TNode node, Bitblaster* bb); +Node DefaultUgtBB(TNode node, Bitblaster* bb); +Node DefaultUgeBB(TNode node, Bitblaster* bb); + +Node DefaultSltBB(TNode node, Bitblaster* bb); +Node DefaultSleBB(TNode node, Bitblaster* bb); +Node DefaultSgtBB(TNode node, Bitblaster* bb); +Node DefaultSgeBB(TNode node, Bitblaster* bb); + +/// other modes +Node AdderUltBB(TNode node, Bitblaster* bb); + + + +/** + * Default Term Bitblasting strategies + * + * @param node the term to be bitblasted + * @param bb the bitblaster in which the clauses are added + * + * @return the bits representing the new term + */ + +void UndefinedTermBBStrategy(TNode node, Bits& bits, Bitblaster* bb); + +void DefaultVarBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultConstBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultNotBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultConcatBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultAndBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultOrBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultXorBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultXnorBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultNandBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultNorBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultCompBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultMultBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultPlusBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultSubBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultNegBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultUdivBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultUremBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultSdivBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultSremBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultSmodBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultShlBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultLshrBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultAshrBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultExtractBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultRepeatBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultZeroExtendBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultSignExtendBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultRotateRightBB (TNode node, Bits& bits, Bitblaster* bb); +void DefaultRotateLeftBB (TNode node, Bits& bits, Bitblaster* bb); + + +} +} +} + +#endif diff --git a/src/theory/bv/bv_sat.cpp b/src/theory/bv/bv_sat.cpp new file mode 100644 index 000000000..22a679693 --- /dev/null +++ b/src/theory/bv/bv_sat.cpp @@ -0,0 +1,300 @@ +/********************* */ +/*! \file bv_sat.cpp + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief [[ Add one-line brief description here ]] + ** + ** [[ Add lengthier description here ]] + ** + **/ + +#include "bv_sat.h" +#include "theory_bv_utils.h" +#include "theory/rewriter.h" +#include "prop/cnf_stream.h" +#include "prop/sat_module.h" + +using namespace std; + +using namespace CVC4::theory::bv::utils; +using namespace CVC4::context; +using namespace CVC4::prop; + +namespace CVC4 { +namespace theory { +namespace bv{ + + +std::string toString(Bits& bits) { + ostringstream os; + for (int i = bits.size() - 1; i >= 0; --i) { + TNode bit = bits[i]; + if (bit.getKind() == kind::CONST_BOOLEAN) { + os << (bit.getConst<bool>() ? "1" : "0"); + } else { + os << bit<< " "; + } + } + os <<"\n"; + + return os.str(); +} +/////// Bitblaster + +Bitblaster::Bitblaster(context::Context* c) : + d_termCache(), + d_bitblastedAtoms(), + d_assertedAtoms(c), + d_statistics() + { + d_satSolver = prop::SatSolverFactory::createMinisat(); + d_cnfStream = new TseitinCnfStream(d_satSolver, new NullRegistrar()); + + // initializing the bit-blasting strategies + initAtomBBStrategies(); + initTermBBStrategies(); + } + + +/** + * Bitblasts the atom, assigns it a marker literal, adding it to the SAT solver + * NOTE: duplicate clauses are not detected because of marker literal + * @param node the atom to be bitblasted + * + */ +void Bitblaster::bbAtom(TNode node) { + if (hasBBAtom(node)) { + return; + } + + // the bitblasted definition of the atom + Node atom_bb = d_atomBBStrategies[node.getKind()](node, this); + // asserting that the atom is true iff the definition holds + Node atom_definition = mkNode(kind::IFF, node, atom_bb); + // do boolean simplifications if possible + Node rewritten = Rewriter::rewrite(atom_definition); + d_cnfStream->convertAndAssert(rewritten, true, false); + d_bitblastedAtoms.insert(node); +} + + +void Bitblaster::bbTerm(TNode node, Bits& bits) { + if (hasBBTerm(node)) { + getBBTerm(node, bits); + return; + } + + d_termBBStrategies[node.getKind()] (node, bits,this); + + Assert (bits.size() == utils::getSize(node)); + cacheTermDef(node, bits); +} + +/// Public methods + +/** + * Called from preregistration bitblasts the node + * + * @param node + * + * @return + */ +void Bitblaster::bitblast(TNode node) { + TimerStat::CodeTimer codeTimer(d_statistics.d_bitblastTimer); + + /// strip the not + if (node.getKind() == kind::NOT) { + node = node[0]; + } + + if (node.getKind() == kind::EQUAL || + node.getKind() == kind::BITVECTOR_ULT || + node.getKind() == kind::BITVECTOR_SLT || + node.getKind() == kind::BITVECTOR_ULE || + node.getKind() == kind::BITVECTOR_SLE ) + { + bbAtom(node); + } + else if (node.getKind() == kind::BITVECTOR_UGT || + node.getKind() == kind::BITVECTOR_UGE || + node.getKind() == kind::BITVECTOR_SGT || + node.getKind() == kind::BITVECTOR_SGE ) + { + Unhandled(node.getKind()); + } + else + { + Bits bits; + bbTerm(node, bits); + } +} + +/** + * Asserts the clauses corresponding to the atom to the Sat Solver + * by turning on the marker literal (i.e. setting it to false) + * @param node the atom to be aserted + * + */ + +void Bitblaster::assertToSat(TNode lit) { + // strip the not + TNode atom; + if (lit.getKind() == kind::NOT) { + atom = lit[0]; + } else { + atom = lit; + } + + Assert (hasBBAtom(atom)); + SatLiteral markerLit = d_cnfStream->getLiteral(atom); + + if(lit.getKind() == kind::NOT) { + markerLit = ~markerLit; + } + + Debug("bitvector-bb") << "TheoryBV::Bitblaster::assertToSat asserting node: " << atom <<"\n"; + Debug("bitvector-bb") << "TheoryBV::Bitblaster::assertToSat with literal: " << markerLit << "\n"; + + d_assertedAtoms.push_back(markerLit); +} + +/** + * Calls the solve method for the Sat Solver. + * passing it the marker literals to be asserted + * + * @return true for sat, and false for unsat + */ + +bool Bitblaster::solve() { + return SatValTrue == d_satSolver->solve(d_assertedAtoms); +} + +void Bitblaster::getConflict(std::vector<TNode>& conflict) { + SatClause conflictClause; + d_satSolver->getUnsatCore(conflictClause); + + for (unsigned i = 0; i < conflictClause.size(); i++) { + SatLiteral lit = conflictClause[i]; + TNode atom = d_cnfStream->getNode(lit); + Node not_atom; + if (atom.getKind() == kind::NOT) { + not_atom = atom[0]; + } else { + not_atom = NodeManager::currentNM()->mkNode(kind::NOT, atom); + } + conflict.push_back(not_atom); + } +} + + +/// Helper methods + + +void Bitblaster::initAtomBBStrategies() { + for (int i = 0 ; i < kind::LAST_KIND; ++i ) { + d_atomBBStrategies[i] = UndefinedAtomBBStrategy; + } + + /// setting default bb strategies for atoms + d_atomBBStrategies [ kind::EQUAL ] = DefaultEqBB; + d_atomBBStrategies [ kind::BITVECTOR_ULT ] = DefaultUltBB; + d_atomBBStrategies [ kind::BITVECTOR_ULE ] = DefaultUleBB; + d_atomBBStrategies [ kind::BITVECTOR_UGT ] = DefaultUgtBB; + d_atomBBStrategies [ kind::BITVECTOR_UGE ] = DefaultUgeBB; + d_atomBBStrategies [ kind::BITVECTOR_SLT ] = DefaultSltBB; + d_atomBBStrategies [ kind::BITVECTOR_SLE ] = DefaultSleBB; + d_atomBBStrategies [ kind::BITVECTOR_SGT ] = DefaultSgtBB; + d_atomBBStrategies [ kind::BITVECTOR_SGE ] = DefaultSgeBB; + +} + +void Bitblaster::initTermBBStrategies() { + for (int i = 0 ; i < kind::LAST_KIND; ++i ) { + d_termBBStrategies[i] = UndefinedTermBBStrategy; + } + + /// setting default bb strategies for terms: + d_termBBStrategies [ kind::VARIABLE ] = DefaultVarBB; + d_termBBStrategies [ kind::CONST_BITVECTOR ] = DefaultConstBB; + d_termBBStrategies [ kind::BITVECTOR_NOT ] = DefaultNotBB; + d_termBBStrategies [ kind::BITVECTOR_CONCAT ] = DefaultConcatBB; + d_termBBStrategies [ kind::BITVECTOR_AND ] = DefaultAndBB; + d_termBBStrategies [ kind::BITVECTOR_OR ] = DefaultOrBB; + d_termBBStrategies [ kind::BITVECTOR_XOR ] = DefaultXorBB; + d_termBBStrategies [ kind::BITVECTOR_XNOR ] = DefaultXnorBB; + d_termBBStrategies [ kind::BITVECTOR_NAND ] = DefaultNandBB ; + d_termBBStrategies [ kind::BITVECTOR_NOR ] = DefaultNorBB; + d_termBBStrategies [ kind::BITVECTOR_COMP ] = DefaultCompBB ; + d_termBBStrategies [ kind::BITVECTOR_MULT ] = DefaultMultBB; + d_termBBStrategies [ kind::BITVECTOR_PLUS ] = DefaultPlusBB; + d_termBBStrategies [ kind::BITVECTOR_SUB ] = DefaultSubBB; + d_termBBStrategies [ kind::BITVECTOR_NEG ] = DefaultNegBB; + d_termBBStrategies [ kind::BITVECTOR_UDIV ] = DefaultUdivBB; + d_termBBStrategies [ kind::BITVECTOR_UREM ] = DefaultUremBB; + d_termBBStrategies [ kind::BITVECTOR_SDIV ] = DefaultSdivBB; + d_termBBStrategies [ kind::BITVECTOR_SREM ] = DefaultSremBB; + d_termBBStrategies [ kind::BITVECTOR_SMOD ] = DefaultSmodBB; + d_termBBStrategies [ kind::BITVECTOR_SHL ] = DefaultShlBB; + d_termBBStrategies [ kind::BITVECTOR_LSHR ] = DefaultLshrBB; + d_termBBStrategies [ kind::BITVECTOR_ASHR ] = DefaultAshrBB; + d_termBBStrategies [ kind::BITVECTOR_EXTRACT ] = DefaultExtractBB; + d_termBBStrategies [ kind::BITVECTOR_REPEAT ] = DefaultRepeatBB; + d_termBBStrategies [ kind::BITVECTOR_ZERO_EXTEND ] = DefaultZeroExtendBB; + d_termBBStrategies [ kind::BITVECTOR_SIGN_EXTEND ] = DefaultSignExtendBB; + d_termBBStrategies [ kind::BITVECTOR_ROTATE_RIGHT ] = DefaultRotateRightBB; + d_termBBStrategies [ kind::BITVECTOR_ROTATE_LEFT ] = DefaultRotateLeftBB; + +} + +bool Bitblaster::hasBBAtom(TNode atom) { + return d_bitblastedAtoms.find(atom) != d_bitblastedAtoms.end(); +} + +void Bitblaster::cacheTermDef(TNode term, Bits def) { + Assert (d_termCache.find(term) == d_termCache.end()); + d_termCache[term] = def; +} + +bool Bitblaster::hasBBTerm(TNode node) { + return d_termCache.find(node) != d_termCache.end(); +} + +void Bitblaster::getBBTerm(TNode node, Bits& bits) { + + Assert (hasBBTerm(node)); + // copy? + bits = d_termCache[node]; +} + +Bitblaster::Statistics::Statistics() : + d_numTermClauses("theory::bv::NumberOfTermSatClauses", 0), + d_numAtomClauses("theory::bv::NumberOfAtomSatClauses", 0), + d_bitblastTimer("theory::bv::BitblastTimer") +{ + StatisticsRegistry::registerStat(&d_numTermClauses); + StatisticsRegistry::registerStat(&d_numAtomClauses); + StatisticsRegistry::registerStat(&d_bitblastTimer); +} + + +Bitblaster::Statistics::~Statistics() { + StatisticsRegistry::unregisterStat(&d_numTermClauses); + StatisticsRegistry::unregisterStat(&d_numAtomClauses); + StatisticsRegistry::unregisterStat(&d_bitblastTimer); +} + + + + +} /*bv namespace */ +} /* theory namespace */ +} /* CVC4 namespace*/ diff --git a/src/theory/bv/bv_sat.h b/src/theory/bv/bv_sat.h new file mode 100644 index 000000000..9844cd982 --- /dev/null +++ b/src/theory/bv/bv_sat.h @@ -0,0 +1,144 @@ +/********************* */ +/*! \file bv_sat.h + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief Wrapper around the SAT solver used for bitblasting + ** + ** Wrapper around the SAT solver used for bitblasting. + **/ + +#include "cvc4_private.h" + +#ifndef __CVC4__BV__SAT_H +#define __CVC4__BV__SAT_H + + +#include "expr/node.h" +#include <vector> +#include <list> +#include <iostream> +#include <math.h> +#include <ext/hash_map> + +#include "context/cdo.h" +#include "context/cdset.h" +#include "context/cdlist.h" + +#include "theory_bv_utils.h" +#include "util/stats.h" +#include "bitblast_strategies.h" + +#include "prop/sat_module.h" + +namespace CVC4 { + +// forward declarations +namespace prop { +class CnfStream; +class BVSatSolverInterface; +} + + +namespace theory { +namespace bv { + + +std::string toString (Bits& bits); + +/** + * The Bitblaster that manages the mapping between Nodes + * and their bitwise definition + * + */ + +typedef std::vector<Node> Bits; + +class Bitblaster { + + typedef __gnu_cxx::hash_map <Node, Bits, TNodeHashFunction > TermDefMap; + typedef __gnu_cxx::hash_set<TNode, TNodeHashFunction> AtomSet; + + typedef void (*TermBBStrategy) (TNode, Bits&, Bitblaster*); + typedef Node (*AtomBBStrategy) (TNode, Bitblaster*); + + // sat solver used for bitblasting and associated CnfStream + prop::BVSatSolverInterface* d_satSolver; + prop::CnfStream* d_cnfStream; + + // caches and mappings + TermDefMap d_termCache; + AtomSet d_bitblastedAtoms; + + context::CDList<prop::SatLiteral> d_assertedAtoms; /**< context dependent list storing the atoms + currently asserted by the DPLL SAT solver. */ + + /// helper methods + bool hasBBAtom(TNode node); + bool hasBBTerm(TNode node); + void getBBTerm(TNode node, Bits& bits); + + + + + /// function tables for the various bitblasting strategies indexed by node kind + TermBBStrategy d_termBBStrategies[kind::LAST_KIND]; + AtomBBStrategy d_atomBBStrategies[kind::LAST_KIND]; + + // helper methods to initialize function tables + void initAtomBBStrategies(); + void initTermBBStrategies(); + + + void bbAtom(TNode node); + // division is bitblasted in terms of constraints + // so it needs to use private bitblaster interface + void bbUdiv(TNode node, Bits& bits); + void bbUrem(TNode node, Bits& bits); +public: + void cacheTermDef(TNode node, Bits def); // public so we can cache remainder for division + void bbTerm(TNode node, Bits& bits); + +public: + Bitblaster(context::Context* c); + ~Bitblaster() { + delete d_cnfStream; + delete d_satSolver; + } + + void assertToSat(TNode node); + bool solve(); + void bitblast(TNode node); + void getConflict(std::vector<TNode>& conflict); + +private: + + + class Statistics { + public: + IntStat d_numTermClauses, d_numAtomClauses; + TimerStat d_bitblastTimer; + Statistics(); + ~Statistics(); + }; + + Statistics d_statistics; +}; + + + +} /* bv namespace */ + +} /* theory namespace */ + +} /* CVC4 namespace */ + +#endif /* __CVC4__BV__SAT_H */ diff --git a/src/theory/bv/bv_solver_types.cpp b/src/theory/bv/bv_solver_types.cpp new file mode 100644 index 000000000..2589e5712 --- /dev/null +++ b/src/theory/bv/bv_solver_types.cpp @@ -0,0 +1,78 @@ +/********************* */ +/*! \file bv_sat.cpp + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief [[ Add one-line brief description here ]] + ** + ** [[ Add lengthier description here ]] + ** + **/ + +#include "bv_solver_types.h" + +namespace CVC4 { +namespace theory { +namespace bv { + +#ifdef BV_MINISAT +using namespace BVMinisat; +SatLit neg(const SatLit& lit) { + return ~lit; +} + +SatLit mkLit(SatVar var) { + return BVMinisat::mkLit(var, false); +} + +SatVar mkVar(SatLit lit) { + return BVMinisat::var(lit); +} +bool polarity(SatLit lit) { + return !(BVMinisat::sign(lit)); +} + + +std::string toStringLit(SatLit lit) { + std::ostringstream os; + os << (polarity(lit) ? "" : "-") << var(lit) + 1; + return os.str(); +} +#endif + +#ifdef BV_PICOSAT + +SatLit mkLit(SatVar var) { + return var; +} +SatVar mkVar(SatLit lit) { + return (lit > 0 ? lit : -lit); +} +bool polarity(SatLit lit) { + return (lit > 0); +} + +SatLit neg(const SatLit& lit) { + return -lit; +} + +std::string toStringLit(SatLit lit) { + std::ostringstream os; + os << (lit < 0 ? "-" : "") << lit; + return os.str(); +} + + +#endif + +} +} +} diff --git a/src/theory/bv/bv_solver_types.h b/src/theory/bv/bv_solver_types.h new file mode 100644 index 000000000..fb99ae4c6 --- /dev/null +++ b/src/theory/bv/bv_solver_types.h @@ -0,0 +1,185 @@ +//********************* */ +/*! \file bv_solver_types.h + ** \verbatim + ** Original author: lianah + ** Major contributors: none + ** Minor contributors (to current version): none + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief Definitions of the SatSolver literal and clause types + ** + **/ + +#include "cvc4_private.h" + +#ifndef __CVC4__BV__SOLVER__TYPES_H +#define __CVC4__BV__SOLVER__TYPES_H + +#define BV_MINISAT +//#define BV_PICOSAT + +#ifdef BV_MINISAT /* BV_MINISAT if we are using the minisat solver for the theory of bitvectors*/ +#include "theory/bv/bvminisat/core/Solver.h" +#include "theory/bv/bvminisat/core/SolverTypes.h" +#include "theory/bv/bvminisat/simp/SimpSolver.h" +#endif /* BV_MINISAT */ + +#ifdef BV_PICOSAT /* BV_PICOSAT */ +#include "picosat/picosat.h" +#endif /* BV_PICOSAT */ + +#include "expr/node.h" +#include <vector> +#include <list> +#include <iostream> +#include <math.h> +#include <ext/hash_map> +#include "context/cdlist.h" +#include "util/stats.h" + + +namespace CVC4 { +namespace theory { +namespace bv { + +#endif /* BV_MINISAT */ + + + +// #ifdef BV_PICOSAT /* BV_PICOSAT */ +// /** +// * PICOSAT type-definitions +// * +// * +// */ + +// typedef int SatVar; +// typedef int SatLit; + +// std::string toStringLit(SatLit lit); + + +// SatLit neg(const SatLit& lit); + +// struct SatLitHash { +// static size_t hash (const SatLit& lit) { +// return (size_t) lit; +// } + +// }; + +// struct SatLitHashFunction { +// size_t operator()(SatLit lit) const { +// return (size_t) lit; +// } +// }; + +// struct SatLitLess{ +// static bool compare(const SatLit& x, const SatLit& y) +// { +// return x < y; +// } +// }; + +// #endif /* BV_PICOSAT */ + +// #ifdef BV_PICOSAT /* BV_PICOSAT */ + +// /** +// * Some helper functions that should be defined for each SAT solver supported +// * +// * +// * @return +// */ + +// SatLit mkLit(SatVar var); +// SatVar mkVar(SatLit lit); +// bool polarity(SatLit lit); + + +// /** +// * Wrapper to create the impression of a SatSolver class for Picosat +// * which is written in C +// */ + +// class SatSolver: public SatSolverInterface { +// int d_varCount; +// bool d_started; +// public: +// SatSolver() : +// d_varCount(0), +// d_started(false) +// { +// picosat_init(); /// call constructor +// picosat_enable_trace_generation(); // required for unsat cores +// } + +// ~SatSolver() { +// picosat_reset(); +// } + +// void addClause(const SatClause* cl) { +// Assert (cl); +// const SatClause& clause = *cl; +// for (unsigned i = 0; i < clause.size(); ++i ) { +// picosat_add(clause[i]); +// } +// picosat_add(0); // ends clause +// } + +// bool solve () { +// if(d_started) { +// picosat_remove_learned(100); +// } +// int res = picosat_sat(-1); // no decision limit +// // 0 UNKNOWN, 10 SATISFIABLE and 20 UNSATISFIABLE +// d_started = true; +// Assert (res == 10 || res == 20); +// return res == 10; +// } + +// bool solve(const context::CDList<SatLit> & assumps) { +// context::CDList<SatLit>::const_iterator it = assumps.begin(); +// for (; it!= assumps.end(); ++it) { +// picosat_assume(*it); +// } +// return solve (); +// } + +// SatVar newVar() { return ++d_varCount; } + +// void setUnremovable(SatLit lit) {}; + +// SatClause* getUnsatCore() { +// const int* failedAssumption = picosat_failed_assumptions(); +// Assert(failedAssumption); + +// SatClause* unsatCore = new SatClause(); +// while (*failedAssumption != 0) { +// SatLit lit = *failedAssumption; +// unsatCore->addLiteral(neg(lit)); +// ++failedAssumption; +// } +// unsatCore->sort(); +// return unsatCore; +// } +// }; + + +// #endif /* BV_PICOSAT */ + + + + +} /* bv namespace */ + +} /* theory namespace */ + +} /* CVC4 namespace */ + +#endif /* __CVC4__BV__SOLVER__TYPES_H */ diff --git a/src/theory/bv/equality_engine.cpp b/src/theory/bv/equality_engine.cpp deleted file mode 100644 index a4d2e6329..000000000 --- a/src/theory/bv/equality_engine.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/********************* */ -/*! \file equality_engine.cpp - ** \verbatim - ** Original author: dejan - ** Major contributors: mdeters - ** Minor contributors (to current version): none - ** This file is part of the CVC4 prototype. - ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) - ** Courant Institute of Mathematical Sciences - ** New York University - ** See the file COPYING in the top-level source directory for licensing - ** information.\endverbatim - ** - ** \brief [[ Add one-line brief description here ]] - ** - ** [[ Add lengthier description here ]] - ** \todo document this file - **/ - -#include "theory/bv/equality_engine.h" - -using namespace CVC4::theory::bv; - -const size_t BitSizeTraits::id_null = (1u << BitSizeTraits::id_bits) - 1; -const size_t BitSizeTraits::trigger_id_null = (1u << BitSizeTraits::trigger_id_bits) - 1; - - diff --git a/src/theory/bv/equality_engine.h b/src/theory/bv/equality_engine.h deleted file mode 100644 index 558fd2b7b..000000000 --- a/src/theory/bv/equality_engine.h +++ /dev/null @@ -1,844 +0,0 @@ -/********************* */ -/*! \file equality_engine.h - ** \verbatim - ** Original author: dejan - ** Major contributors: none - ** Minor contributors (to current version): mdeters - ** This file is part of the CVC4 prototype. - ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) - ** Courant Institute of Mathematical Sciences - ** New York University - ** See the file COPYING in the top-level source directory for licensing - ** information.\endverbatim - ** - ** \brief [[ Add one-line brief description here ]] - ** - ** [[ Add lengthier description here ]] - ** \todo document this file - **/ - -#include "cvc4_private.h" - -#pragma once - -#include <vector> -#include <ext/hash_map> -#include <sstream> - -#include "expr/node.h" -#include "context/cdo.h" -#include "util/output.h" -#include "util/stats.h" -#include "theory/rewriter.h" -#include "theory/bv/theory_bv_utils.h" - -namespace CVC4 { -namespace theory { -namespace bv { - -struct BitSizeTraits { - /** The null id */ - static const size_t id_null; // Defined in the cpp file (GCC bug) - /** The null trigger id */ - static const size_t trigger_id_null; - - /** Number of bits we use for the id */ - static const size_t id_bits = 24; - /** Number of bits we use for the size the equivalence class */ - static const size_t size_bits = 16; - /** Number of bits we use for the trigger id */ - static const size_t trigger_id_bits = 24; -}; - -class EqualityNode { - -public: - - /** The size of this equivalence class (if it's a representative) */ - size_t d_size : BitSizeTraits::size_bits; - - /** The id (in the eq-manager) of the representative equality node */ - size_t d_findId : BitSizeTraits::id_bits; - - /** The next equality node in this class */ - size_t d_nextId : BitSizeTraits::id_bits; - -public: - - /** - * Creates a new node, which is in a list of it's own. - */ - EqualityNode(size_t nodeId = BitSizeTraits::id_null) - : d_size(1), d_findId(nodeId), d_nextId(nodeId) {} - - /** Initialize the equality node */ - inline void init(size_t nodeId) { - d_size = 1; - d_findId = d_nextId = nodeId; - } - - /** - * Returns the next node in the class circular list. - */ - inline size_t getNext() const { - return d_nextId; - } - - /** - * Returns the size of this equivalence class (only valid if this is the representative). - */ - inline size_t getSize() const { - return d_size; - } - - /** - * Merges the two lists. If add size is true the size of this node is increased by the size of - * the other node, otherwise the size is decreased by the size of the other node. - */ - template<bool addSize> - inline void merge(EqualityNode& other) { - size_t tmp = d_nextId; d_nextId = other.d_nextId; other.d_nextId = tmp; - if (addSize) { - d_size += other.d_size; - } else { - d_size -= other.d_size; - } - } - - /** - * Returns the class representative. - */ - inline size_t getFind() const { return d_findId; } - - /** - * Set the class representative. - */ - inline void setFind(size_t findId) { d_findId = findId; } -}; - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -class EqualityEngine { - -public: - - /** Statistics about the equality engine instance */ - struct Statistics { - /** Total number of merges */ - IntStat mergesCount; - /** Number of terms managed by the system */ - IntStat termsCount; - /** Number of function terms managed by the system */ - IntStat functionTermsCount; - /** Number of times we performed a backtrack */ - IntStat backtracksCount; - - Statistics(std::string name) - : mergesCount(name + "::mergesCount", 0), - termsCount(name + "::termsCount", 0), - functionTermsCount(name + "functionTermsCoutn", 0), - backtracksCount(name + "::backtracksCount", 0) - { - StatisticsRegistry::registerStat(&mergesCount); - StatisticsRegistry::registerStat(&termsCount); - StatisticsRegistry::registerStat(&functionTermsCount); - StatisticsRegistry::registerStat(&backtracksCount); - } - - ~Statistics() { - StatisticsRegistry::unregisterStat(&mergesCount); - StatisticsRegistry::unregisterStat(&termsCount); - StatisticsRegistry::unregisterStat(&functionTermsCount); - StatisticsRegistry::unregisterStat(&backtracksCount); - } - }; - -private: - - /** The class to notify when a representative changes for a term */ - NotifyClass d_notify; - - /** Map from nodes to their ids */ - __gnu_cxx::hash_map<TNode, size_t, TNodeHashFunction> d_nodeIds; - - /** Map from ids to the nodes */ - std::vector<Node> d_nodes; - - /** Map from ids to the equality nodes */ - std::vector<EqualityNode> d_equalityNodes; - - /** Number of asserted equalities we have so far */ - context::CDO<size_t> d_assertedEqualitiesCount; - - /** - * We keep a list of asserted equalities. Not among original terms, but - * among the class representatives. - */ - struct Equality { - /** Left hand side of the equality */ - size_t lhs : BitSizeTraits::id_bits; - /** Right hand side of the equality */ - size_t rhs : BitSizeTraits::id_bits; - /** Equality constructor */ - Equality(size_t lhs = BitSizeTraits::id_null, size_t rhs = BitSizeTraits::id_null) - : lhs(lhs), rhs(rhs) {} - }; - - /** The ids of the classes we have merged */ - std::vector<Equality> d_assertedEqualities; - - /** The reasons for the equalities */ - - /** - * An edge in the equality graph. This graph is an undirected graph (both edges added) - * containing the actual asserted equalities. - */ - class EqualityEdge { - - // The id of the RHS of this equality - size_t d_nodeId : BitSizeTraits::id_bits; - // The next edge - size_t d_nextId : BitSizeTraits::id_bits; - - public: - - EqualityEdge(size_t nodeId = BitSizeTraits::id_null, size_t nextId = BitSizeTraits::id_null) - : d_nodeId(nodeId), d_nextId(nextId) {} - - /** Returns the id of the next edge */ - inline size_t getNext() const { return d_nextId; } - - /** Returns the id of the target edge node */ - inline size_t getNodeId() const { return d_nodeId; } - }; - - /** - * All the equality edges (twice as many as the number of asserted equalities. If an equality - * t1 = t2 is asserted, the edges added are -> t2, -> t1 (in this order). Hance, having the index - * of one of the edges you can reconstruct the original equality. - */ - std::vector<EqualityEdge> d_equalityEdges; - - /** - * Returns the string representation of the edges. - */ - std::string edgesToString(size_t edgeId) const; - - /** - * Reasons for equalities. - */ - std::vector<Node> d_equalityReasons; - - /** - * Map from a node to it's first edge in the equality graph. Edges are added to the front of the - * list which makes the insertion/backtracking easy. - */ - std::vector<size_t> d_equalityGraph; - - /** Add an edge to the equality graph */ - inline void addGraphEdge(size_t t1, size_t t2, Node reason); - - /** Returns the equality node of the given node */ - inline EqualityNode& getEqualityNode(TNode node); - - /** Returns the equality node of the given node */ - inline EqualityNode& getEqualityNode(size_t nodeId); - - /** Returns the id of the node */ - inline size_t getNodeId(TNode node) const; - - /** Merge the class2 into class1 */ - void merge(EqualityNode& class1, EqualityNode& class2, std::vector<size_t>& triggers); - - /** Undo the mereg of class2 into class1 */ - void undoMerge(EqualityNode& class1, EqualityNode& class2, size_t class2Id); - - /** Backtrack the information if necessary */ - void backtrack(); - - /** - * Data used in the BFS search through the equality graph. - */ - struct BfsData { - // The current node - size_t nodeId : BitSizeTraits::id_bits; - // The index of the edge we traversed - size_t edgeId : BitSizeTraits::id_bits; - // Index in the queue of the previous node. Shouldn't be too much of them, at most the size - // of the biggest equivalence class - size_t previousIndex : BitSizeTraits::size_bits; - - BfsData(size_t nodeId = BitSizeTraits::id_null, size_t edgeId = BitSizeTraits::id_null, size_t prev = 0) - : nodeId(nodeId), edgeId(edgeId), previousIndex(prev) {} - }; - - /** - * Trigger that will be updated - */ - struct Trigger { - /** The current class id of the LHS of the trigger */ - size_t classId : BitSizeTraits::id_bits; - /** Next trigger for class 1 */ - size_t nextTrigger : BitSizeTraits::id_bits; - - Trigger(size_t classId, size_t nextTrigger) - : classId(classId), nextTrigger(nextTrigger) {} - }; - - /** - * Vector of triggers (persistent and not-backtrackable). Triggers come in pairs for an - * equality trigger (t1, t2): one at position 2k for t1, and one at position 2k + 1 for t2. When - * updating triggers we always know where the other one is (^1). - */ - std::vector<Trigger> d_equalityTriggers; - - /** - * Trigger lists per node. The begin id changes as we merge, but the end always points to - * the actual end of the triggers for this node. - */ - std::vector<size_t> d_nodeTriggers; - - /** - * Adds the trigger with triggerId to the beginning of the trigger list of the node with id nodeId. - */ - inline void addTriggerToList(size_t nodeId, size_t triggerId); - - /** Statistics */ - Statistics d_stats; - -public: - - /** - * Initialize the equality engine, given the owning class. This will initialize the notifier with - * the owner information. - */ - EqualityEngine(OwnerClass& owner, context::Context* context, std::string name) - : d_notify(owner), d_assertedEqualitiesCount(context, 0), d_stats(name) { - BVDebug("equality") << "EqualityEdge::EqualityEdge(): id_null = " << BitSizeTraits::id_null << - ", trigger_id_null = " << BitSizeTraits::trigger_id_null << std::endl; - } - - /** - * Adds a term to the term database. Returns the internal id of the term. - */ - size_t addTerm(TNode t); - - /** - * Check whether the node is already in the database. - */ - inline bool hasTerm(TNode t) const; - - /** - * Adds an equality t1 = t2 to the database. Returns false if any of the triggers failed, or a - * conflict was introduced. - */ - bool addEquality(TNode t1, TNode t2, Node reason); - - /** - * Returns the representative of the term t. - */ - inline TNode getRepresentative(TNode t) const; - - /** - * Returns true if the two nodes are in the same class. - */ - inline bool areEqual(TNode t1, TNode t2) const; - - /** - * Get an explanation of the equality t1 = t2. Returns the asserted equalities that - * imply t1 = t2. Returns TNodes as the assertion equalities should be hashed somewhere - * else. TODO: mark the phantom equalities (skolems). - */ - void getExplanation(TNode t1, TNode t2, std::vector<TNode>& equalities) const; - - /** - * Adds a notify trigger for equality t1 = t2, i.e. when t1 = t2 the notify will be called with - * (t1, t2). - */ - size_t addTrigger(TNode t1, TNode t2); - - /** - * Normalizes a term by finding the representative. If the representative can be decomposed (using - * UnionFindPreferences) it will try and recursively find the representatives, and substitute. - * Assumptions used in normalization are retruned in the set. - */ - Node normalize(TNode node, std::set<TNode>& assumptions); - -private: - - /** Hash of normalizations to avioid cycles */ - typedef __gnu_cxx::hash_map<TNode, Node, TNodeHashFunction> normalization_cache; - normalization_cache d_normalizationCache; - - /** - * Same as above, but does cahcing to avoid loops. - */ - Node normalizeWithCache(TNode node, std::set<TNode>& assumptions); - -}; - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -size_t EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::addTerm(TNode t) { - - BVDebug("equality") << "EqualityEngine::addTerm(" << t << ")" << std::endl; - - // If term already added, retrurn it's id - if (hasTerm(t)) return getNodeId(t); - - ++ d_stats.termsCount; - - // Register the new id of the term - size_t newId = d_nodes.size(); - d_nodeIds[t] = newId; - // Add the node to it's position - d_nodes.push_back(t); - // Add the trigger list for this node - d_nodeTriggers.push_back(BitSizeTraits::trigger_id_null); - // Add it to the equality graph - d_equalityGraph.push_back(BitSizeTraits::id_null); - // Add the equality node to the nodes - if (d_equalityNodes.size() <= newId) { - d_equalityNodes.resize(newId + 100); - } - d_equalityNodes[newId].init(newId); - // Return the id of the term - return newId; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -bool EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::hasTerm(TNode t) const { - return d_nodeIds.find(t) != d_nodeIds.end(); -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -size_t EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::getNodeId(TNode node) const { - Assert(hasTerm(node), node.toString().c_str()); - return (*d_nodeIds.find(node)).second; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -EqualityNode& EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::getEqualityNode(TNode t) { - return getEqualityNode(getNodeId(t)); -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -EqualityNode& EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::getEqualityNode(size_t nodeId) { - Assert(nodeId < d_equalityNodes.size()); - return d_equalityNodes[nodeId]; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -bool EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::addEquality(TNode t1, TNode t2, Node reason) { - - BVDebug("equality") << "EqualityEngine::addEquality(" << t1 << "," << t2 << ")" << std::endl; - - // Backtrack if necessary - backtrack(); - - // Add the terms if they are not already in the database - size_t t1Id = getNodeId(t1); - size_t t2Id = getNodeId(t2); - - // Get the representatives - size_t t1classId = getEqualityNode(t1Id).getFind(); - size_t t2classId = getEqualityNode(t2Id).getFind(); - - // If already the same, we're done - if (t1classId == t2classId) return true; - - // Check for constants - if (d_nodes[t1classId].getMetaKind() == kind::metakind::CONSTANT && - d_nodes[t2classId].getMetaKind() == kind::metakind::CONSTANT) { - std::vector<TNode> reasons; - getExplanation(t1, d_nodes[t1classId], reasons); - getExplanation(t2, d_nodes[t2classId], reasons); - reasons.push_back(reason); - d_notify.conflict(utils::mkAnd(reasons)); - return false; - } - - // Get the nodes of the representatives - EqualityNode& node1 = getEqualityNode(t1classId); - EqualityNode& node2 = getEqualityNode(t2classId); - - Assert(node1.getFind() == t1classId); - Assert(node2.getFind() == t2classId); - - // Depending on the merge preference (such as size), merge them - std::vector<size_t> triggers; - if (UnionFindPreferences::mergePreference(d_nodes[t2classId], node2.getSize(), d_nodes[t1classId], node1.getSize())) { - BVDebug("equality") << "EqualityEngine::addEquality(" << t1 << "," << t2 << "): merging " << t1 << " into " << t2 << std::endl; - merge(node2, node1, triggers); - d_assertedEqualities.push_back(Equality(t2classId, t1classId)); - } else { - BVDebug("equality") << "EqualityEngine::addEquality(" << t1 << "," << t2 << "): merging " << t2 << " into " << t1 << std::endl; - merge(node1, node2, triggers); - d_assertedEqualities.push_back(Equality(t1classId, t2classId)); - } - - // Add the actuall equality to the equality graph - addGraphEdge(t1Id, t2Id, reason); - - // One more equality added - d_assertedEqualitiesCount = d_assertedEqualitiesCount + 1; - - Assert(2*d_assertedEqualities.size() == d_equalityEdges.size()); - Assert(d_assertedEqualities.size() == d_assertedEqualitiesCount); - - // Notify the triggers - for (size_t i = 0, i_end = triggers.size(); i < i_end; ++ i) { - // Notify the trigger and exit if it fails - if (!d_notify(triggers[i])) return false; - } - - return true; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -TNode EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::getRepresentative(TNode t) const { - - BVDebug("equality") << "EqualityEngine::getRepresentative(" << t << ")" << std::endl; - - Assert(hasTerm(t)); - - // Both following commands are semantically const - const_cast<EqualityEngine*>(this)->backtrack(); - size_t representativeId = const_cast<EqualityEngine*>(this)->getEqualityNode(t).getFind(); - - BVDebug("equality") << "EqualityEngine::getRepresentative(" << t << ") => " << d_nodes[representativeId] << std::endl; - - return d_nodes[representativeId]; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -bool EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::areEqual(TNode t1, TNode t2) const { - BVDebug("equality") << "EqualityEngine::areEqual(" << t1 << "," << t2 << ")" << std::endl; - - Assert(hasTerm(t1)); - Assert(hasTerm(t2)); - - // Both following commands are semantically const - const_cast<EqualityEngine*>(this)->backtrack(); - size_t rep1 = const_cast<EqualityEngine*>(this)->getEqualityNode(t1).getFind(); - size_t rep2 = const_cast<EqualityEngine*>(this)->getEqualityNode(t2).getFind(); - - BVDebug("equality") << "EqualityEngine::areEqual(" << t1 << "," << t2 << ") => " << (rep1 == rep2 ? "true" : "false") << std::endl; - - return rep1 == rep2; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -void EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::merge(EqualityNode& class1, EqualityNode& class2, std::vector<size_t>& triggers) { - - BVDebug("equality") << "EqualityEngine::merge(" << class1.getFind() << "," << class2.getFind() << ")" << std::endl; - - Assert(triggers.empty()); - - ++ d_stats.mergesCount; - - size_t class1Id = class1.getFind(); - size_t class2Id = class2.getFind(); - - // Update class2 representative information - size_t currentId = class2Id; - do { - // Get the current node - EqualityNode& currentNode = getEqualityNode(currentId); - - // Update it's find to class1 id - currentNode.setFind(class1Id); - - // Go through the triggers and inform if necessary - size_t currentTrigger = d_nodeTriggers[currentId]; - while (currentTrigger != BitSizeTraits::trigger_id_null) { - Trigger& trigger = d_equalityTriggers[currentTrigger]; - Trigger& otherTrigger = d_equalityTriggers[currentTrigger ^ 1]; - - // If the two are not already in the same class - if (otherTrigger.classId != trigger.classId) { - trigger.classId = class1Id; - // If they became the same, call the trigger - if (otherTrigger.classId == class1Id) { - // Id of the real trigger is half the internal one - triggers.push_back(currentTrigger >> 1); - } - } - - // Go to the next trigger - currentTrigger = trigger.nextTrigger; - } - - // Move to the next node - currentId = currentNode.getNext(); - - } while (currentId != class2Id); - - // Now merge the lists - class1.merge<true>(class2); -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -void EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::undoMerge(EqualityNode& class1, EqualityNode& class2, size_t class2Id) { - - BVDebug("equality") << "EqualityEngine::undoMerge(" << class1.getFind() << "," << class2Id << ")" << std::endl; - - // Now unmerge the lists (same as merge) - class1.merge<false>(class2); - - // Update class2 representative information - size_t currentId = class2Id; - do { - // Get the current node - EqualityNode& currentNode = getEqualityNode(currentId); - - // Update it's find to class1 id - currentNode.setFind(class2Id); - - // Go through the trigger list (if any) and undo the class - size_t currentTrigger = d_nodeTriggers[currentId]; - while (currentTrigger != BitSizeTraits::trigger_id_null) { - Trigger& trigger = d_equalityTriggers[currentTrigger]; - trigger.classId = class2Id; - currentTrigger = trigger.nextTrigger; - } - - // Move to the next node - currentId = currentNode.getNext(); - - } while (currentId != class2Id); - -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -void EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::backtrack() { - - // If we need to backtrack then do it - if (d_assertedEqualitiesCount < d_assertedEqualities.size()) { - - ++ d_stats.backtracksCount; - - BVDebug("equality") << "EqualityEngine::backtrack(): nodes" << std::endl; - - for (int i = (int)d_assertedEqualities.size() - 1, i_end = (int)d_assertedEqualitiesCount; i >= i_end; --i) { - // Get the ids of the merged classes - Equality& eq = d_assertedEqualities[i]; - // Undo the merge - undoMerge(d_equalityNodes[eq.lhs], d_equalityNodes[eq.rhs], eq.rhs); - } - - d_assertedEqualities.resize(d_assertedEqualitiesCount); - - BVDebug("equality") << "EqualityEngine::backtrack(): edges" << std::endl; - - for (int i = (int)d_equalityEdges.size() - 2, i_end = (int)(2*d_assertedEqualitiesCount); i >= i_end; i -= 2) { - EqualityEdge& edge1 = d_equalityEdges[i]; - EqualityEdge& edge2 = d_equalityEdges[i | 1]; - d_equalityGraph[edge2.getNodeId()] = edge1.getNext(); - d_equalityGraph[edge1.getNodeId()] = edge2.getNext(); - } - - d_equalityEdges.resize(2 * d_assertedEqualitiesCount); - d_equalityReasons.resize(d_assertedEqualitiesCount); - } - -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -void EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::addGraphEdge(size_t t1, size_t t2, Node reason) { - BVDebug("equality") << "EqualityEngine::addGraphEdge(" << d_nodes[t1] << "," << d_nodes[t2] << ")" << std::endl; - size_t edge = d_equalityEdges.size(); - d_equalityEdges.push_back(EqualityEdge(t2, d_equalityGraph[t1])); - d_equalityEdges.push_back(EqualityEdge(t1, d_equalityGraph[t2])); - d_equalityGraph[t1] = edge; - d_equalityGraph[t2] = edge | 1; - d_equalityReasons.push_back(reason); -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -std::string EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::edgesToString(size_t edgeId) const { - std::stringstream out; - bool first = true; - while (edgeId != BitSizeTraits::id_null) { - const EqualityEdge& edge = d_equalityEdges[edgeId]; - if (!first) out << ","; - out << d_nodes[edge.getNodeId()]; - edgeId = edge.getNext(); - first = false; - } - return out.str(); -} - - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -void EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::getExplanation(TNode t1, TNode t2, std::vector<TNode>& equalities) const { - Assert(getRepresentative(t1) == getRepresentative(t2)); - - BVDebug("equality") << "EqualityEngine::getExplanation(" << t1 << "," << t2 << ")" << std::endl; - - // If the nodes are the same, we're done - if (t1 == t2) return; - - const_cast<EqualityEngine*>(this)->backtrack(); - - // Queue for the BFS containing nodes - std::vector<BfsData> bfsQueue; - - // The id's of the nodes - size_t t1Id = getNodeId(t1); - size_t t2Id = getNodeId(t2); - - // Find a path from t1 to t2 in the graph (BFS) - bfsQueue.push_back(BfsData(t1Id, BitSizeTraits::id_null, 0)); - size_t currentIndex = 0; - while (true) { - // There should always be a path, and every node can be visited only once (tree) - Assert(currentIndex < bfsQueue.size()); - - // The next node to visit - BfsData current = bfsQueue[currentIndex]; - size_t currentNode = current.nodeId; - - BVDebug("equality") << "EqualityEngine::getExplanation(): currentNode = " << d_nodes[currentNode] << std::endl; - - // Go through the equality edges of this node - size_t currentEdge = d_equalityGraph[currentNode]; - - BVDebug("equality") << "EqualityEngine::getExplanation(): edges = " << edgesToString(currentEdge) << std::endl; - - while (currentEdge != BitSizeTraits::id_null) { - // Get the edge - const EqualityEdge& edge = d_equalityEdges[currentEdge]; - - // If not just the backwards edge - if ((currentEdge | 1u) != (current.edgeId | 1u)) { - - BVDebug("equality") << "EqualityEngine::getExplanation(): currentEdge = (" << d_nodes[currentNode] << "," << d_nodes[edge.getNodeId()] << ")" << std::endl; - - // Did we find the path - if (edge.getNodeId() == t2Id) { - - BVDebug("equality") << "EqualityEngine::getExplanation(): path found: " << std::endl; - - // Reconstruct the path - do { - // Add the actual equality to the vector - equalities.push_back(d_equalityReasons[currentEdge >> 1]); - BVDebug("equality") << "EqualityEngine::getExplanation(): adding: " << d_equalityReasons[currentEdge >> 1] << std::endl; - - // Go to the previous - currentEdge = bfsQueue[currentIndex].edgeId; - currentIndex = bfsQueue[currentIndex].previousIndex; - } while (currentEdge != BitSizeTraits::id_null); - - // Done - return; - } - - // Push to the visitation queue if it's not the backward edge - bfsQueue.push_back(BfsData(edge.getNodeId(), currentEdge, currentIndex)); - } - - // Go to the next edge - currentEdge = edge.getNext(); - } - - // Go to the next node to visit - ++ currentIndex; - } -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -size_t EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::addTrigger(TNode t1, TNode t2) { - - BVDebug("equality") << "EqualityEngine::addTrigger(" << t1 << "," << t2 << ")" << std::endl; - - Assert(hasTerm(t1)); - Assert(hasTerm(t2)); - - // Get the information about t1 - size_t t1Id = getNodeId(t1); - size_t t1TriggerId = d_nodeTriggers[t1Id]; - size_t t1classId = getEqualityNode(t1Id).getFind(); - - // Get the information about t2 - size_t t2Id = getNodeId(t2); - size_t t2TriggerId = d_nodeTriggers[t2Id]; - size_t t2classId = getEqualityNode(t2Id).getFind(); - - // Create the triggers - size_t t1NewTriggerId = d_equalityTriggers.size(); - size_t t2NewTriggerId = t1NewTriggerId | 1; - d_equalityTriggers.push_back(Trigger(t1classId, t1TriggerId)); - d_equalityTriggers.push_back(Trigger(t2classId, t2TriggerId)); - - // Add the trigger to the trigger graph - d_nodeTriggers[t1Id] = t1NewTriggerId; - d_nodeTriggers[t2Id] = t2NewTriggerId; - - BVDebug("equality") << "EqualityEngine::addTrigger(" << t1 << "," << t2 << ") => " << t1NewTriggerId / 2 << std::endl; - - // Return the global id of the trigger - return t1NewTriggerId / 2; -} - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -Node EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::normalize(TNode node, std::set<TNode>& assumptions) { - d_normalizationCache.clear(); - Node result = Rewriter::rewrite(normalizeWithCache(node, assumptions)); - d_normalizationCache.clear(); - return result; -} - - -template <typename OwnerClass, typename NotifyClass, typename UnionFindPreferences> -Node EqualityEngine<OwnerClass, NotifyClass, UnionFindPreferences>::normalizeWithCache(TNode node, std::set<TNode>& assumptions) { - - BVDebug("equality") << "EqualityEngine::normalize(" << node << ")" << push << std::endl; - - normalization_cache::iterator find = d_normalizationCache.find(node); - if (find != d_normalizationCache.end()) { - if (find->second.isNull()) { - // We are in a cycle - return node; - } else { - // Not in a cycle, return it - return find->second; - } - } else { - d_normalizationCache[node] = Node(); - } - - // Get the representative - Node result = hasTerm(node) ? getRepresentative(node) : node; - if (node != result) { - std::vector<TNode> equalities; - getExplanation(result, node, equalities); - utils::getConjuncts(equalities, assumptions); - } - - // If asked, substitute the children with their representatives - if (UnionFindPreferences::descend(result)) { - // Make the builder for substitution - NodeBuilder<> builder; - builder << result.getKind(); - kind::MetaKind metaKind = result.getMetaKind(); - if (metaKind == kind::metakind::PARAMETERIZED) { - builder << result.getOperator(); - } - for (unsigned i = 0; i < result.getNumChildren(); ++ i) { - builder << normalizeWithCache(result[i], assumptions); - } - result = builder; - } - - BVDebug("equality") << "EqualityEngine::normalize(" << node << ") => " << result << pop << std::endl; - - // Cache the result for real now - d_normalizationCache[node] = result; - - return result; -} - -} // Namespace bv -} // Namespace theory -} // Namespace CVC4 - diff --git a/src/theory/bv/kinds b/src/theory/bv/kinds index d502c5ecb..36d25de2a 100644 --- a/src/theory/bv/kinds +++ b/src/theory/bv/kinds @@ -57,6 +57,12 @@ operator BITVECTOR_SLE 2 "bit-vector signed less than or equal" operator BITVECTOR_SGT 2 "bit-vector signed greater than" operator BITVECTOR_SGE 2 "signed greater than or equal" +constant BITVECTOR_BITOF_OP \ + ::CVC4::BitVectorBitOf \ + ::CVC4::BitVectorBitOfHashStrategy \ + "util/bitvector.h" \ + "operator for the bit-vector boolean bit extract" + constant BITVECTOR_EXTRACT_OP \ ::CVC4::BitVectorExtract \ ::CVC4::BitVectorExtractHashStrategy \ @@ -93,6 +99,7 @@ constant BITVECTOR_ROTATE_RIGHT_OP \ "util/bitvector.h" \ "operator for the bit-vector rotate right" +parameterized BITVECTOR_BITOF BITVECTOR_BITOF_OP 1 "bit-vector boolean bit extract" parameterized BITVECTOR_EXTRACT BITVECTOR_EXTRACT_OP 1 "bit-vector extract" parameterized BITVECTOR_REPEAT BITVECTOR_REPEAT_OP 1 "bit-vector repeat" parameterized BITVECTOR_ZERO_EXTEND BITVECTOR_ZERO_EXTEND_OP 1 "bit-vector zero-extend" @@ -138,6 +145,7 @@ typerule BITVECTOR_SGT ::CVC4::theory::bv::BitVectorPredicateTypeRule typerule BITVECTOR_SGE ::CVC4::theory::bv::BitVectorPredicateTypeRule typerule BITVECTOR_EXTRACT ::CVC4::theory::bv::BitVectorExtractTypeRule +typerule BITVECTOR_BITOF ::CVC4::theory::bv::BitVectorBitOfTypeRule typerule BITVECTOR_CONCAT ::CVC4::theory::bv::BitVectorConcatRule typerule BITVECTOR_REPEAT ::CVC4::theory::bv::BitVectorRepeatTypeRule typerule BITVECTOR_ZERO_EXTEND ::CVC4::theory::bv::BitVectorExtendTypeRule diff --git a/src/theory/bv/slice_manager.h b/src/theory/bv/slice_manager.h deleted file mode 100644 index 80ac98001..000000000 --- a/src/theory/bv/slice_manager.h +++ /dev/null @@ -1,677 +0,0 @@ -/********************* */ -/*! \file slice_manager.h - ** \verbatim - ** Original author: dejan - ** Major contributors: none - ** Minor contributors (to current version): none - ** This file is part of the CVC4 prototype. - ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) - ** Courant Institute of Mathematical Sciences - ** New York University - ** See the file COPYING in the top-level source directory for licensing - ** information.\endverbatim - ** - ** \brief [[ Add one-line brief description here ]] - ** - ** [[ Add lengthier description here ]] - ** \todo document this file - **/ - -/* - * slice_manager.h - * - * Created on: Feb 16, 2011 - * Author: dejan - */ - -#include "cvc4_private.h" - -#pragma once - -#include "context/cdo.h" -#include "theory/bv/theory_bv_utils.h" -#include "theory/bv/equality_engine.h" -#include "theory/bv/cd_set_collection.h" - -#include <map> -#include <set> -#include <vector> - -namespace CVC4 { -namespace theory { -namespace bv { - -/** - * Representation of the slice points in tree. - */ -class slice_point -{ -public: - - /** Number of bits we use for the index of the slice */ - static const size_t s_slice_index_bits = 31; - /** Number of bits we use for the index of the slice_point in the slice memory (reference) */ - static const size_t s_slice_point_reference_bits = 32; - /** The null reference (maximal number in the given bits) */ - static const size_t null = (1llu << s_slice_point_reference_bits) - 1; - - /** Type of the reference for the outside world */ - typedef size_t reference_type; - - /** Type of the value for the outside world */ - typedef size_t value_type; - -private: - - /** The value of the slice point (bit index) */ - size_t d_value : s_slice_index_bits; - /** Is this the left child */ - size_t d_isLeftChild : 1; - /** Reference to the left in the tree */ - size_t d_left : s_slice_point_reference_bits; - /** Reference to the right of the tree */ - size_t d_right : s_slice_point_reference_bits; - /** Reference to the parent */ - size_t d_parent : s_slice_point_reference_bits; - -public: - - slice_point(size_t value, size_t left, size_t right, size_t parent, bool isLeftChild) - : d_value(value), d_isLeftChild(isLeftChild ? 1 : 0), d_left(left), d_right(right), d_parent(parent) {} - - bool isLeft() const { return d_isLeftChild == 1; } - bool isRight() const { return d_isLeftChild == 0; } - - bool hasLeft() const { return d_left != null; } - bool hasRight() const { return d_right != null; } - bool hasParent() const { return d_parent != null; } - - reference_type getLeft() const { return d_left; } - reference_type getRight() const { return d_right; } - reference_type getParent() const { return d_parent; } - - void removeLeft() { Assert(d_left != null); d_left = null; } - void removeRight() { Assert(d_right != null); d_right = null; } - - void setLeft(reference_type left) { Assert(d_left == null && left != null); d_left = left; } - void setRight(reference_type right) { Assert(d_right == null && right != null); d_right = right; } - - value_type getValue() const { return d_value; } -}; - -/** - * Slice manager should keep the database of slices for the core theory leaf terms, for example - * - * term core leaf terms - * ---------------------------------------------- - * (x + y)[31:0] x + y - * a[10:0]@a[11:10]@(b + c)[1:0] a, b, (b + c) - * (a << 5)[10] (a << 5) - * - * If an (dis-)equality is added to the system, we refine the slicing in order to align the extracts, for example - * - * equality slicing - * ---------------------------------------------- - * x = y x[32,0], y[32,0] - * x@y = z x[32,0], y[32,0], z[64,32,0] - * x@y = z, x[31:16] = y[15:0] x[32,16,0], y[32,16,0], z[64,48,32,16,0] - * - * As a result of the slicing the slicing equalities are added to the equality engine, using the (associative) - * concat function that is generated for the equality manager, for example - * - * equality added equalities - * ---------------------------------------------- - * x = y none - * x@y = z z = concat(z[63:32],z[31:0]) - * x@y = z, x[31:16] = y[15:0] z = concat(z[63:32],z[31:0]), - * z[63:32] = concat(z[63:48], z[47:32]), - * z[31:0] = concat(z[31:16], z[15:0]) - * - * In the last example, since concat is associative, the equality engine will know that z = concat(z[63:48], z[47:32], - * z[31:16], z[15:0]). - * - */ -template <class TheoryBitvector> -class SliceManager { - -public: - - /** The references to backtrackable sets */ - typedef slice_point::reference_type set_reference; - - /** The set collection we'll be using */ - typedef context::BacktrackableSetCollection<std::vector<slice_point>, slice_point, set_reference> set_collection; - - /** The map type from nodes to their references */ - typedef context::CDMap<Node, set_reference, NodeHashFunction> slicing_map; - - /** The equality engine theory of bit-vectors is using */ - typedef typename TheoryBitvector::BvEqualityEngine EqualityEngine; - -private: - - /** The theory of bitvectors */ - TheoryBitvector& d_theoryBitvector; - - /** The equality engine */ - EqualityEngine& d_equalityEngine; - - /** The collection of backtrackable sets */ - set_collection d_setCollection; - - /** - * A map from base nodes to slice points. For each node, the slice points are - * 0 = i_1 < i_2 < ... < i_n = size, and the slices are - * x[i_n-1:i_{n-1}]@x[i_{n-1}-1:i_{n-2}]@...@x[i_2-1:i_1] - * Each time we add a slict t = t1@t2@...@tn of a term (or a slice), we also notify the equality engine with an - * extra assertion. Since the equality engine is backtrackable, we will need to backtrack the slices accordingly. - */ - slicing_map d_nodeSlicing; - -public: - - SliceManager(TheoryBitvector& theoryBitvector, context::Context* context) - : d_theoryBitvector(theoryBitvector), - d_equalityEngine(theoryBitvector.getEqualityEngine()), - d_setCollection(context), - d_nodeSlicing(context) - { - } - - /** - * Adds the equality (lhs = rhs) to the slice manager. The equality is first normalized according to the equality - * manager, i.e. each base term is taken from the equality manager, replaced in, and then the whole concatenation - * normalized and sliced wrt the current slicing. The method will not add the equalities to the equality manager, - * but instead will slice the equality according to the current slicing in order to align all the slices. - * - * The terms that get sliced get sent to the theory engine as equalities, i.e if we slice x[10:0] into x[10:5]@x[4:0] - * equality engine gets the assertion x[10:0] = concat(x[10:5], x[4:0]). - * - * input output slicing - * -------------------------------------------------------------------------------------------------------------- - * x@y = y@x x = y, y = x empty - * x[31:0]@x[64:32] = x x = x[31:0]@x[63:32] x:{64,32,0} - * x@y = 0000@x@0000 x = 0000@x[7:4], y = x[3:0]@0000 x:{8,4,0} - * - */ - inline bool solveEquality(TNode lhs, TNode rhs); - -private: - - inline bool solveEquality(TNode lhs, TNode rhs, const std::set<TNode>& assumptions); - - /** - * Slices up lhs and rhs and returns the slices in lhsSlices and rhsSlices. The slices are not atomic, - * they are sliced in order to make one of lhs or rhs atomic, the other one can be a concatenation. - */ - inline bool sliceAndSolve(std::vector<Node>& lhs, std::vector<Node>& rhs, const std::set<TNode>& assumptions); - - /** - * Returns true if the term is already sliced wrt the current slicing. Note that, for example, even though - * the slicing is empty, x[i:j] is considered sliced. Sliced means that there is no slice points between i and j. - */ - inline bool isSliced(TNode node) const; - - /** - * Slices the term wrt the current slicing. When done, isSliced returns true - */ - inline bool slice(TNode node, std::vector<Node>& sliced); - - /** - * Returns the base term in the core theory of the given term, i.e. - * x => x - * x[i:j] => x - * (x + y) => x+y - * (x + y)[i:j] => x+y - */ - static inline TNode baseTerm(TNode node); - - /** - * Adds a new slice to the slice set of the given term. - */ - inline bool addSlice(Node term, unsigned slicePoint); -}; - -template <class TheoryBitvector> -bool SliceManager<TheoryBitvector>::solveEquality(TNode lhs, TNode rhs) { - std::set<TNode> assumptions; - assumptions.insert(lhs.eqNode(rhs)); - bool ok = solveEquality(lhs, rhs, assumptions); - return ok; -} - -template <class TheoryBitvector> -bool SliceManager<TheoryBitvector>::solveEquality(TNode lhs, TNode rhs, const std::set<TNode>& assumptions) { - - BVDebug("slicing") << "SliceMagager::solveEquality(" << lhs << "," << rhs << "," << utils::setToString(assumptions) << ")" << push << std::endl; - - bool ok; - - // The concatenations on the left-hand side (reverse order, first is on top) - std::vector<Node> lhsTerms; - if (lhs.getKind() == kind::BITVECTOR_CONCAT) { - for (int i = (int) lhs.getNumChildren() - 1; i >= 0; -- i) { - lhsTerms.push_back(lhs[i]); - } - } else { - lhsTerms.push_back(lhs); - } - - // The concatenations on the right-hand side (reverse order, first is on top) - std::vector<Node> rhsTerms; - if (rhs.getKind() == kind::BITVECTOR_CONCAT) { - for (int i = (int) rhs.getNumChildren() - 1; i >= 0; --i) { - rhsTerms.push_back(rhs[i]); - } - } else { - rhsTerms.push_back(rhs); - } - - // Slice the individual terms to align them - ok = sliceAndSolve(lhsTerms, rhsTerms, assumptions); - - BVDebug("slicing") << "SliceMagager::solveEquality(" << lhs << "," << rhs << "," << utils::setToString(assumptions) << ")" << pop << std::endl; - - return ok; -} - - -template <class TheoryBitvector> -bool SliceManager<TheoryBitvector>::sliceAndSolve(std::vector<Node>& lhs, std::vector<Node>& rhs, const std::set<TNode>& assumptions) -{ - - BVDebug("slicing") << "SliceManager::sliceAndSolve()" << std::endl; - - // Go through the work-list, solve and align - while (!lhs.empty()) { - - Assert(!rhs.empty()); - - BVDebug("slicing") << "SliceManager::sliceAndSolve(): lhs " << utils::vectorToString(lhs) << std::endl; - BVDebug("slicing") << "SliceManager::sliceAndSolve(): rhs " << utils::vectorToString(rhs) << std::endl; - - // The terms that we need to slice - Node lhsTerm = lhs.back(); - Node rhsTerm = rhs.back(); - - BVDebug("slicing") << "SliceManager::sliceAndSolve(): " << lhsTerm << " : " << rhsTerm << std::endl; - - // If the terms are not sliced wrt the current slicing, we have them sliced - lhs.pop_back(); - if (!isSliced(lhsTerm)) { - if (!slice(lhsTerm, lhs)) return false; - BVDebug("slicing") << "SliceManager::sliceAndSolve(): lhs sliced" << std::endl; - continue; - } - rhs.pop_back(); - if (!isSliced(rhsTerm)) { - if (!slice(rhsTerm, rhs)) return false; - // We also need to put lhs back - lhs.push_back(lhsTerm); - BVDebug("slicing") << "SliceManager::sliceAndSolve(): rhs sliced" << std::endl; - continue; - } - - BVDebug("slicing") << "SliceManager::sliceAndSolve(): both lhs and rhs sliced already" << std::endl; - - // The solving concatenation - std::vector<Node> concatTerms; - - // If the slices are of the same size we do the additional work - int sizeDifference = utils::getSize(lhsTerm) - utils::getSize(rhsTerm); - - // We slice constants immediately - if (sizeDifference > 0 && lhsTerm.getKind() == kind::CONST_BITVECTOR) { - Node low = utils::mkConst(lhsTerm.getConst<BitVector>().extract(sizeDifference - 1, 0)); - Node high = utils::mkConst(lhsTerm.getConst<BitVector>().extract(utils::getSize(lhsTerm) - 1, sizeDifference)); - d_equalityEngine.addTerm(low); d_equalityEngine.addTerm(high); - lhs.push_back(low); - lhs.push_back(high); - rhs.push_back(rhsTerm); - continue; - } - if (sizeDifference < 0 && rhsTerm.getKind() == kind::CONST_BITVECTOR) { - Node low = utils::mkConst(rhsTerm.getConst<BitVector>().extract(-sizeDifference - 1, 0)); - Node high = utils::mkConst(rhsTerm.getConst<BitVector>().extract(utils::getSize(rhsTerm) - 1, -sizeDifference)); - d_equalityEngine.addTerm(low); d_equalityEngine.addTerm(high); - rhs.push_back(low); - rhs.push_back(high); - lhs.push_back(lhsTerm); - continue; - } - - enum SolvingFor { - SOLVING_FOR_LHS, - SOLVING_FOR_RHS - } solvingFor = sizeDifference < 0 || lhsTerm.getKind() == kind::CONST_BITVECTOR ? SOLVING_FOR_RHS : SOLVING_FOR_LHS; - - BVDebug("slicing") << "SliceManager::sliceAndSolve(): " << (solvingFor == SOLVING_FOR_LHS ? "solving for LHS" : "solving for RHS") << std::endl; - - // When we slice in order to align, we might have to reslice the one we are solving for - bool reslice = false; - - switch (solvingFor) { - case SOLVING_FOR_RHS: { - concatTerms.push_back(lhsTerm); - // Maybe we need to add more lhs to make them equal - while (sizeDifference < 0 && !reslice) { - Assert(lhs.size() > 0); - // Get the next part for lhs - lhsTerm = lhs.back(); - lhs.pop_back(); - // Slice if necessary - if (!isSliced(lhsTerm)) { - if (!slice(lhsTerm, lhs)) return false; - continue; - } - // If we go above 0, we need to cut it - if (sizeDifference + (int)utils::getSize(lhsTerm) > 0) { - // Slice it so it fits - addSlice(lhsTerm, (int)utils::getSize(lhsTerm) + sizeDifference); - if (!slice(lhsTerm, lhs)) return false; - if (!isSliced(rhsTerm)) { - if (!slice(rhsTerm, rhs)) return false; - while(!concatTerms.empty()) { - lhs.push_back(concatTerms.back()); - concatTerms.pop_back(); - } - reslice = true; - } - continue; - } - concatTerms.push_back(lhsTerm); - sizeDifference += utils::getSize(lhsTerm); - } - break; - } - case SOLVING_FOR_LHS: { - concatTerms.push_back(rhsTerm); - // Maybe we need to add more rhs to make them equal - while (sizeDifference > 0 && !reslice) { - Assert(rhs.size() > 0); - // Get the next part for lhs - rhsTerm = rhs.back(); - rhs.pop_back(); - // Slice if necessary - if (!isSliced(rhsTerm)) { - if (!slice(rhsTerm, rhs)) return false; - continue; - } - // If we go below 0, we need to cut it - if (sizeDifference - (int)utils::getSize(rhsTerm) < 0) { - // Slice it so it fits - addSlice(rhsTerm, (int)utils::getSize(rhsTerm) - sizeDifference); - if (!slice(rhsTerm, rhs)) return false; - if (!isSliced(lhsTerm)) { - if (!slice(lhsTerm, lhs)) return false; - while(!concatTerms.empty()) { - rhs.push_back(concatTerms.back()); - concatTerms.pop_back(); - } - reslice = true; - } - continue; - } - concatTerms.push_back(rhsTerm); - sizeDifference -= utils::getSize(rhsTerm); - } - break; - } - } - - // If we need to reslice - if (reslice) { - continue; - } - - Assert(sizeDifference == 0); - - Node concat = utils::mkConcat(concatTerms); - BVDebug("slicing") << "SliceManager::sliceAndSolve(): concatenation " << concat << std::endl; - - // We have them equal size now. If the base term of the one we are solving is solved into a - // non-trivial concatenation already, we have to normalize. A concatenation is non-trivial if - // it is not a direct slicing, i.e it is a concat, and normalize(x) != x - switch (solvingFor) { - case SOLVING_FOR_LHS: { - TNode lhsTermRepresentative = d_equalityEngine.getRepresentative(lhsTerm); - if (lhsTermRepresentative != lhsTerm && - (lhsTermRepresentative.getKind() == kind::BITVECTOR_CONCAT || lhsTermRepresentative.getKind() == kind::CONST_BITVECTOR)) { - // We need to normalize and solve the normalized equations - std::vector<TNode> explanation; - d_equalityEngine.getExplanation(lhsTerm, lhsTermRepresentative, explanation); - std::set<TNode> additionalAssumptions(assumptions); - utils::getConjuncts(explanation, additionalAssumptions); - bool ok = solveEquality(lhsTermRepresentative, concat, additionalAssumptions); - if (!ok) return false; - } else { - // We're fine, just add the equality - BVDebug("slicing") << "SliceManager::sliceAndSolve(): adding " << lhsTerm << " = " << concat << " " << utils::setToString(assumptions) << std::endl; - d_equalityEngine.addTerm(concat); - bool ok = d_equalityEngine.addEquality(lhsTerm, concat, utils::mkConjunction(assumptions)); - if (!ok) return false; - } - break; - } - case SOLVING_FOR_RHS: { - TNode rhsTermRepresentative = d_equalityEngine.getRepresentative(rhsTerm); - if (rhsTermRepresentative != rhsTerm && - (rhsTermRepresentative.getKind() == kind::BITVECTOR_CONCAT || rhsTermRepresentative.getKind() == kind::CONST_BITVECTOR)) { - // We need to normalize and solve the normalized equations - std::vector<TNode> explanation; - d_equalityEngine.getExplanation(rhsTerm, rhsTermRepresentative, explanation); - std::set<TNode> additionalAssumptions(assumptions); - utils::getConjuncts(explanation, additionalAssumptions); - bool ok = solveEquality(rhsTermRepresentative, concat, additionalAssumptions); - if (!ok) return false; - } else { - // We're fine, just add the equality - BVDebug("slicing") << "SliceManager::sliceAndSolve(): adding " << rhsTerm << " = " << concat << utils::setToString(assumptions) << std::endl; - d_equalityEngine.addTerm(concat); - bool ok = d_equalityEngine.addEquality(rhsTerm, concat, utils::mkConjunction(assumptions)); - if (!ok) return false; - } - break; - } - } - } - - return true; -} - -template <class TheoryBitvector> -bool SliceManager<TheoryBitvector>::isSliced(TNode node) const { - - BVDebug("slicing") << "SliceManager::isSliced(" << node << ")" << std::endl; - - bool result = false; - - // Constants are always sliced - if (node.getKind() == kind::CONST_BITVECTOR) { - result = true; - } else { - // The indices of the beginning and end - Kind nodeKind = node.getKind(); - unsigned high = nodeKind == kind::BITVECTOR_EXTRACT ? utils::getExtractHigh(node) : utils::getSize(node) - 1; - unsigned low = nodeKind == kind::BITVECTOR_EXTRACT ? utils::getExtractLow(node) : 0; - - // Get the base term - TNode nodeBase = baseTerm(node); - Assert(nodeBase.getKind() != kind::BITVECTOR_CONCAT); - Assert(nodeBase.getKind() != kind::CONST_BITVECTOR); - - // Get the base term slice set - slicing_map::const_iterator find = d_nodeSlicing.find(nodeBase); - // If no slices, it's just a term, so we are done, UNLESS it's an extract - if (find == d_nodeSlicing.end()) { - result = nodeKind != kind::BITVECTOR_EXTRACT; - } else { - set_reference sliceSet = (*find).second; - Assert(d_setCollection.size(sliceSet) >= 2); - // The term is not sliced if one of the borders is not in the slice set or - // there is a point between the borders - result = - d_setCollection.contains(sliceSet, low) && d_setCollection.contains(sliceSet, high + 1) && - (low == high || d_setCollection.count(sliceSet, low + 1, high) == 0); - } - } - - BVDebug("slicing") << "SliceManager::isSliced(" << node << ") => " << (result ? "true" : "false") << std::endl; - return result; -} - -template <class TheoryBitvector> -bool SliceManager<TheoryBitvector>::addSlice(Node node, unsigned slicePoint) { - BVDebug("slicing") << "SliceMagager::addSlice(" << node << "," << slicePoint << ")" << std::endl; - - bool ok = true; - - int low = node.getKind() == kind::BITVECTOR_EXTRACT ? utils::getExtractLow(node) : 0; - int high = node.getKind() == kind::BITVECTOR_EXTRACT ? utils::getExtractHigh(node) + 1: utils::getSize(node); - slicePoint += low; - - TNode nodeBase = baseTerm(node); - - Assert(nodeBase.getKind() != kind::CONST_BITVECTOR); - - set_reference sliceSet; - slicing_map::iterator find = d_nodeSlicing.find(nodeBase); - if (find == d_nodeSlicing.end()) { - d_nodeSlicing[nodeBase] = sliceSet = d_setCollection.newSet(0); - d_setCollection.insert(sliceSet, utils::getSize(nodeBase)); - } else { - sliceSet = (*find).second; - } - - Assert(d_setCollection.size(sliceSet) >= 2); - - // What are the points surrounding the new slice point - int prev = d_setCollection.prev(sliceSet, slicePoint); - int next = d_setCollection.next(sliceSet, slicePoint); - - // Add the slice to the set - d_setCollection.insert(sliceSet, slicePoint); - BVDebug("slicing") << "SliceMagager::addSlice(" << node << "," << slicePoint << "): current set " << d_setCollection.toString(sliceSet) << std::endl; - - // Add the terms and the equality to the equality engine - Node t1 = utils::mkExtract(nodeBase, next - 1, slicePoint); - Node t2 = utils::mkExtract(nodeBase, slicePoint - 1, prev); - Node nodeSlice = (next == high && prev == low) ? node : utils::mkExtract(nodeBase, next - 1, prev); - Node concat = utils::mkConcat(t1, t2); - - d_equalityEngine.addTerm(t1); - d_equalityEngine.addTerm(t2); - d_equalityEngine.addTerm(nodeSlice); - d_equalityEngine.addTerm(concat); - - // We are free to add this slice, unless the slice has a representative that's already a concat - TNode nodeSliceRepresentative = d_equalityEngine.getRepresentative(nodeSlice); - if (nodeSliceRepresentative.getKind() != kind::BITVECTOR_CONCAT) { - // Add the slice to the equality engine - ok = d_equalityEngine.addEquality(nodeSlice, concat, utils::mkTrue()); - } else { - // If the representative is a concat, we must solve it - // There is no need do add nodeSlice = concat as we will solve the representative of nodeSlice - std::set<TNode> assumptions; - std::vector<TNode> equalities; - d_equalityEngine.getExplanation(nodeSlice, nodeSliceRepresentative, equalities); - utils::getConjuncts(equalities, assumptions); - ok = solveEquality(nodeSliceRepresentative, concat, assumptions); - } - - BVDebug("slicing") << "SliceMagager::addSlice(" << node << "," << slicePoint << ") => " << d_setCollection.toString(d_nodeSlicing[nodeBase]) << std::endl; - - return ok; -} - -template <class TheoryBitvector> -inline bool SliceManager<TheoryBitvector>::slice(TNode node, std::vector<Node>& sliced) { - - BVDebug("slicing") << "SliceManager::slice(" << node << ")" << std::endl; - - Assert(!isSliced(node)); - - // The indices of the beginning and (one past) end - unsigned high = node.getKind() == kind::BITVECTOR_EXTRACT ? utils::getExtractHigh(node) + 1 : utils::getSize(node); - unsigned low = node.getKind() == kind::BITVECTOR_EXTRACT ? utils::getExtractLow(node) : 0; - BVDebug("slicing") << "SliceManager::slice(" << node << "): low: " << low << std::endl; - BVDebug("slicing") << "SliceManager::slice(" << node << "): high: " << high << std::endl; - - // Get the base term - TNode nodeBase = baseTerm(node); - Assert(nodeBase.getKind() != kind::BITVECTOR_CONCAT); - Assert(nodeBase.getKind() != kind::CONST_BITVECTOR); - - // The nodes slice set - set_reference nodeSliceSet; - - // Find the current one or construct it - slicing_map::iterator findSliceSet = d_nodeSlicing.find(nodeBase); - if (findSliceSet == d_nodeSlicing.end()) { - d_nodeSlicing[nodeBase] = nodeSliceSet = d_setCollection.newSet(0); - d_setCollection.insert(nodeSliceSet, utils::getSize(nodeBase)); - } else { - nodeSliceSet = d_nodeSlicing[nodeBase]; - } - - Assert(d_setCollection.size(nodeSliceSet) >= 2); - - BVDebug("slicing") << "SliceManager::slice(" << node << "): current: " << d_setCollection.toString(nodeSliceSet) << std::endl; - - // Go through all the points i_0 <= low < i_1 < ... < i_{n-1} < high <= i_n from the slice set - // and generate the slices [i_0:low-1][low:i_1-1] [i_1:i2] ... [i_{n-1}:high-1][high:i_n-1]. They are in reverse order, - // as they should be - - // The high bound already in the slicing - size_t i_n = high == utils::getSize(nodeBase) ? high: d_setCollection.next(nodeSliceSet, high - 1); - BVDebug("slicing") << "SliceManager::slice(" << node << "): i_n: " << i_n << std::endl; - // Add the new point to the slice set (they might be there already) - if (high < i_n) { - if (!addSlice(nodeBase, high)) return false; - } - // The low bound already in the slicing (slicing might have changed after adding high) - size_t i_0 = low == 0 ? 0 : d_setCollection.prev(nodeSliceSet, low + 1); - BVDebug("slicing") << "SliceManager::slice(" << node << "): i_0: " << i_0 << std::endl; - // Add the new points to the slice set (they might be there already) - if (i_0 < low) { - if (!addSlice(nodeBase, low)) return false; - } - - // Get the slice points - std::vector<size_t> slicePoints; - if (low + 1 < high) { - d_setCollection.getElements(nodeSliceSet, low + 1, high - 1, slicePoints); - } - - // Construct the actuall slicing - if (slicePoints.size() > 0) { - BVDebug("slicing") << "SliceManager::slice(" << node << "): adding" << utils::mkExtract(nodeBase, slicePoints[0] - 1, low) << std::endl; - sliced.push_back(utils::mkExtract(nodeBase, slicePoints[0] - 1, low)); - for (unsigned i = 1; i < slicePoints.size(); ++ i) { - BVDebug("slicing") << "SliceManager::slice(" << node << "): adding" << utils::mkExtract(nodeBase, slicePoints[i] - 1, slicePoints[i-1])<< std::endl; - sliced.push_back(utils::mkExtract(nodeBase, slicePoints[i] - 1, slicePoints[i-1])); - } - BVDebug("slicing") << "SliceManager::slice(" << node << "): adding" << utils::mkExtract(nodeBase, high-1, slicePoints.back()) << std::endl; - sliced.push_back(utils::mkExtract(nodeBase, high-1, slicePoints.back())); - } else { - sliced.push_back(utils::mkExtract(nodeBase, high - 1, low)); - } - - return true; -} - -template <class TheoryBitvector> -TNode SliceManager<TheoryBitvector>::baseTerm(TNode node) { - if (node.getKind() == kind::BITVECTOR_EXTRACT) { - Assert(node[0].getKind() != kind::BITVECTOR_EXTRACT); - Assert(node[0].getKind() != kind::CONST_BITVECTOR); - return node[0]; - } else { - Assert(node.getKind() != kind::BITVECTOR_CONCAT); - return node; - } -} - -} // Namespace bv -} // Namespace theory -} // Namespace CVC4 diff --git a/src/theory/bv/theory_bv.cpp b/src/theory/bv/theory_bv.cpp index c977435ec..79c065d7e 100644 --- a/src/theory/bv/theory_bv.cpp +++ b/src/theory/bv/theory_bv.cpp @@ -19,196 +19,82 @@ #include "theory/bv/theory_bv.h" #include "theory/bv/theory_bv_utils.h" - #include "theory/valuation.h" +#include "theory/bv/bv_sat.h" + using namespace CVC4; using namespace CVC4::theory; using namespace CVC4::theory::bv; -using namespace CVC4::theory::bv::utils; +using namespace CVC4::context; using namespace std; +using namespace CVC4::theory::bv::utils; -void TheoryBV::preRegisterTerm(TNode node) { +TheoryBV::TheoryBV(context::Context* c, context::UserContext* u, OutputChannel& out, Valuation valuation) + : Theory(THEORY_BV, c, u, out, valuation), + d_context(c), + d_assertions(c), + d_bitblaster(new Bitblaster(c) ), + d_statistics() + { + d_true = utils::mkTrue(); + } +TheoryBV::~TheoryBV() { + delete d_bitblaster; +} +TheoryBV::Statistics::Statistics(): + d_avgConflictSize("theory::bv::AvgBVConflictSize"), + d_solveSubstitutions("theory::bv::NumberOfSolveSubstitutions", 0) +{ + StatisticsRegistry::registerStat(&d_avgConflictSize); + StatisticsRegistry::registerStat(&d_solveSubstitutions); +} - BVDebug("bitvector") << "TheoryBV::preRegister(" << node << ")" << std::endl; +TheoryBV::Statistics::~Statistics() { + StatisticsRegistry::unregisterStat(&d_avgConflictSize); + StatisticsRegistry::unregisterStat(&d_solveSubstitutions); +} - if (node.getKind() == kind::EQUAL) { - d_eqEngine.addTerm(node[0]); - if (node[0].getKind() == kind::BITVECTOR_CONCAT) { - for (unsigned i = 0, i_end = node[0].getNumChildren(); i < i_end; ++ i) { - d_eqEngine.addTerm(node[0][i]); - } - } - d_eqEngine.addTerm(node[1]); - if (node[1].getKind() == kind::BITVECTOR_CONCAT) { - for (unsigned i = 0, i_end = node[1].getNumChildren(); i < i_end; ++ i) { - d_eqEngine.addTerm(node[1][i]); - } - } +void TheoryBV::preRegisterTerm(TNode node) { - d_normalization[node] = new Normalization(d_context, node); - } + BVDebug("bitvector-preregister") << "TheoryBV::preRegister(" << node << ")" << std::endl; + //marker literal: bitblast all terms before we start + d_bitblaster->bitblast(node); } void TheoryBV::check(Effort e) { - BVDebug("bitvector") << "TheoryBV::check(" << e << ")" << std::endl; - - // Normalization iterators - NormalizationMap::iterator it = d_normalization.begin(); - NormalizationMap::iterator it_end = d_normalization.end(); - - // Get all the assertions - std::vector<TNode> assertionsList; - while (!done()) { - // Get the assertion - TNode assertion = get(); - d_assertions.insert(assertion); - assertionsList.push_back(assertion); - } - - bool normalizeEqualities = false; - - for (unsigned i = 0; i < assertionsList.size(); ++ i) { - - TNode assertion = assertionsList[i]; - - BVDebug("bitvector") << "TheoryBV::check(" << e << "): asserting: " << assertion << std::endl; - - // Do the right stuff - switch (assertion.getKind()) { - case kind::EQUAL: { - // Slice and solve the equality - bool ok = d_sliceManager.solveEquality(assertion[0], assertion[1]); - if (!ok) return; - // Normalize all equalities - normalizeEqualities = true; - it = d_normalization.begin(); - it = d_normalization.end(); - break; + if (fullEffort(e)) { + std::vector<TNode> assertions; + while (!done()) { + TNode assertion = get(); + Debug("bitvector") << "assertion " << assertion << "\n"; + assertions.push_back(assertion); + d_bitblaster->bitblast(assertion); } - case kind::NOT: { - if (!normalizeEqualities) { - // We still need to check this dis-equality, as it might have been pre-registered just now - // so we didn't have a chance to propagate - it = d_normalization.find(assertion[0]); - if (it->second->assumptions.size() == 1) { - // Just normalize this equality - normalizeEqualities = true; - it_end = it; - it_end ++; - } - } - break; + + std::vector<TNode>::const_iterator it = assertions.begin(); + for (; it != assertions.end(); ++it) { + d_bitblaster->assertToSat(*it); } - default: - Unhandled(assertion.getKind()); - } - } - - if (normalizeEqualities) { + bool res = d_bitblaster->solve(); + if (res == false) { + std::vector<TNode> conflictAtoms; + d_bitblaster->getConflict(conflictAtoms); - BVDebug("bitvector") << "Checking for propagations" << std::endl; - - NormalizationMap::iterator it = d_normalization.begin(); - NormalizationMap::iterator it_end = d_normalization.end(); - for(; it != it_end; ++ it) { - - TNode equality = it->first; - BVDebug("bitvector") << "Checking " << equality << std::endl; - Normalization& normalization = *it->second; + d_statistics.d_avgConflictSize.addEntry(conflictAtoms.size()); - // If asserted, we don't care - if (d_assertions.find(equality) != d_assertions.end()) continue; - - // Assumptions - std::set<TNode> assumptions; - TNode lhs = normalization.equalities.back()[0]; - TNode rhs = normalization.equalities.back()[1]; - // If already satisfied, do nothing - if (lhs == rhs) continue; - - Node lhsNormalized = d_eqEngine.normalize(lhs, assumptions); - Node rhsNormalized = d_eqEngine.normalize(rhs, assumptions); - - if (lhsNormalized == lhs && rhsNormalized == rhs) continue; - - normalization.equalities.push_back(lhsNormalized.eqNode(rhsNormalized)); - normalization.assumptions.push_back(assumptions); - - BVDebug("bitvector") << "Adding normalization " << lhsNormalized.eqNode(rhsNormalized) << std::endl; - BVDebug("bitvector") << " assumptions " << utils::setToString(assumptions) << std::endl; - - - BVDebug("bitvector") << "TheoryBV::check(" << e << "): normalizes to " << lhsNormalized << " = " << rhsNormalized << std::endl; - - // If both are equal we can propagate - bool propagate = lhsNormalized == rhsNormalized; - // otherwise if both are constants, we propagate negation (if not already there) - bool propagateNegation = !propagate && - lhsNormalized.getKind() == kind::CONST_BITVECTOR && rhsNormalized.getKind() == kind::CONST_BITVECTOR - && d_assertions.find(equality.notNode()) == d_assertions.end(); - ; - if (propagate || propagateNegation) { - Node implied = propagate ? Node(equality) : equality.notNode() ; - Node impliedNegated = propagate ? equality.notNode() : Node(equality) ; - // If the negation of what's implied has been asserted, we are in conflict - if (d_assertions.find(impliedNegated) != d_assertions.end()) { - BVDebug("bitvector") << "TheoryBV::check(" << e << "): conflict with " << utils::setToString(assumptions) << std::endl; - // Construct the assumptions - for (unsigned i = 0; i < normalization.assumptions.size(); ++ i) { - assumptions.insert(normalization.assumptions[i].begin(), normalization.assumptions[i].end()); - } - // Make the conflict - assumptions.insert(impliedNegated); - d_out->conflict(mkConjunction(assumptions)); - return; - } - // Otherwise we propagate the implication - else { - BVDebug("bitvector") << "TheoryBV::check(" << e << "): propagating " << implied << std::endl; - d_out->propagate(implied); - d_assertions.insert(implied); - } - } + Node conflict = mkConjunction(conflictAtoms); + d_out->conflict(conflict); + return; } } } -bool TheoryBV::triggerEquality(size_t triggerId) { - BVDebug("bitvector") << "TheoryBV::triggerEquality(" << triggerId << ")" << std::endl; - Assert(triggerId < d_triggers.size()); - BVDebug("bitvector") << "TheoryBV::triggerEquality(" << triggerId << "): " << d_triggers[triggerId] << std::endl; - - return true; - - TNode equality = d_triggers[triggerId]; - - // If we have just asserted this equality ignore it - if (d_assertions.contains(equality)) return true; - - // If we have a negation asserted, we have a confict - if (d_assertions.contains(equality.notNode())) { - - std::vector<TNode> explanation; - d_eqEngine.getExplanation(equality[0], equality[1], explanation); - std::set<TNode> assumptions; - assumptions.insert(equality.notNode()); - utils::getConjuncts(explanation, assumptions); - d_out->conflict(utils::mkConjunction(assumptions)); - - return false; - } - - // Otherwise we propagate this equality - d_out->propagate(equality); - - return true; -} Node TheoryBV::getValue(TNode n) { - NodeManager* nodeManager = NodeManager::currentNM(); + //NodeManager* nodeManager = NodeManager::currentNM(); switch(n.getKind()) { @@ -216,8 +102,7 @@ Node TheoryBV::getValue(TNode n) { Unhandled(kind::VARIABLE); case kind::EQUAL: // 2 args - return nodeManager-> - mkConst( d_valuation.getValue(n[0]) == d_valuation.getValue(n[1]) ); + Unhandled(kind::VARIABLE); default: Unhandled(n.getKind()); @@ -229,13 +114,37 @@ Node TheoryBV::explain(TNode node) { TNode equality = node.getKind() == kind::NOT ? node[0] : node; Assert(equality.getKind() == kind::EQUAL); + Assert(0); + return node; + +} - context::CDList< set<TNode> >& vec = d_normalization[equality]->assumptions; - std::set<TNode> assumptions; - for (unsigned i = 0; i < vec.size(); ++ i) { - BVDebug("bitvector") << "Adding normalization " << d_normalization[equality]->equalities[i] << std::endl; - BVDebug("bitvector") << " assumptions " << utils::setToString(d_normalization[equality]->assumptions[i]) << std::endl; - assumptions.insert(vec[i].begin(), vec[i].end()); +// Node TheoryBV::preprocessTerm(TNode term) { +// return term; //d_staticEqManager.find(term); +// } + +Theory::PPAssertStatus TheoryBV::ppAssert(TNode in, SubstitutionMap& outSubstitutions) { + switch(in.getKind()) { + case kind::EQUAL: + + if (in[0].getMetaKind() == kind::metakind::VARIABLE && !in[1].hasSubterm(in[0])) { + ++(d_statistics.d_solveSubstitutions); + outSubstitutions.addSubstitution(in[0], in[1]); + return PP_ASSERT_STATUS_SOLVED; + } + if (in[1].getMetaKind() == kind::metakind::VARIABLE && !in[0].hasSubterm(in[1])) { + ++(d_statistics.d_solveSubstitutions); + outSubstitutions.addSubstitution(in[1], in[0]); + return PP_ASSERT_STATUS_SOLVED; + } + // to do constant propagations + + break; + case kind::NOT: + break; + default: + // TODO other predicates + break; } - return utils::mkConjunction(assumptions); + return PP_ASSERT_STATUS_UNSOLVED; } diff --git a/src/theory/bv/theory_bv.h b/src/theory/bv/theory_bv.h index 11ddceaae..5303b6595 100644 --- a/src/theory/bv/theory_bv.h +++ b/src/theory/bv/theory_bv.h @@ -23,119 +23,42 @@ #include "theory/theory.h" #include "context/context.h" -#include "context/cdset.h" #include "context/cdlist.h" -#include "theory/bv/equality_engine.h" -#include "theory/bv/slice_manager.h" +#include "theory/bv/theory_bv_utils.h" +#include "util/stats.h" + +namespace BVMinisat { +class SimpSolver; +} + namespace CVC4 { namespace theory { namespace bv { +/// forward declarations +class Bitblaster; + class TheoryBV : public Theory { public: - class EqualityNotify { - TheoryBV& d_theoryBV; - public: - EqualityNotify(TheoryBV& theoryBV) - : d_theoryBV(theoryBV) {} - - bool operator () (size_t triggerId) { - return d_theoryBV.triggerEquality(triggerId); - } - void conflict(Node explanation) { - std::set<TNode> assumptions; - utils::getConjuncts(explanation, assumptions); - d_theoryBV.d_out->conflict(utils::mkConjunction(assumptions)); - } - }; - - struct BVEqualitySettings { - static inline bool descend(TNode node) { - return node.getKind() == kind::BITVECTOR_CONCAT || node.getKind() == kind::BITVECTOR_EXTRACT; - } - - /** Returns true if node1 has preference to node2 as a representative, otherwise node2 is used */ - static inline bool mergePreference(TNode node1, unsigned node1size, TNode node2, unsigned node2size) { - if (node1.getKind() == kind::CONST_BITVECTOR) { - Assert(node2.getKind() != kind::CONST_BITVECTOR); - return true; - } - if (node2.getKind() == kind::CONST_BITVECTOR) { - Assert(node1.getKind() != kind::CONST_BITVECTOR); - return false; - } - if (node1.getKind() == kind::BITVECTOR_CONCAT) { - Assert(node2.getKind() != kind::BITVECTOR_CONCAT); - return true; - } - if (node2.getKind() == kind::BITVECTOR_CONCAT) { - Assert(node1.getKind() != kind::BITVECTOR_CONCAT); - return false; - } - return node2size < node1size; - } - }; - - typedef EqualityEngine<TheoryBV, EqualityNotify, BVEqualitySettings> BvEqualityEngine; - private: - /** Equality reasoning engine */ - BvEqualityEngine d_eqEngine; - - /** Slice manager */ - SliceManager<TheoryBV> d_sliceManager; - - /** Equality triggers indexed by ids from the equality manager */ - std::vector<Node> d_triggers; - /** The context we are using */ context::Context* d_context; /** The asserted stuff */ - context::CDSet<TNode, TNodeHashFunction> d_assertions; - - /** Asserted dis-equalities */ - context::CDList<TNode> d_disequalities; - - struct Normalization { - context::CDList<Node> equalities; - context::CDList< std::set<TNode> > assumptions; - Normalization(context::Context* c, TNode eq) - : equalities(c), assumptions(c) { - equalities.push_back(eq); - assumptions.push_back(std::set<TNode>()); - } - }; - - /** Map from equalities to their noramlization information */ - typedef __gnu_cxx::hash_map<TNode, Normalization*, TNodeHashFunction> NormalizationMap; - NormalizationMap d_normalization; - - /** Called by the equality managere on triggers */ - bool triggerEquality(size_t triggerId); - + context::CDList<TNode> d_assertions; + + /** Bitblaster */ + Bitblaster* d_bitblaster; Node d_true; - + public: - TheoryBV(context::Context* c, context::UserContext* u, OutputChannel& out, Valuation valuation) - : Theory(THEORY_BV, c, u, out, valuation), - d_eqEngine(*this, c, "theory::bv::EqualityEngine"), - d_sliceManager(*this, c), - d_context(c), - d_assertions(c), - d_disequalities(c) - { - d_true = utils::mkTrue(); - } - - BvEqualityEngine& getEqualityEngine() { - return d_eqEngine; - } + TheoryBV(context::Context* c, context::UserContext* u, OutputChannel& out, Valuation valuation); + ~TheoryBV(); void preRegisterTerm(TNode n); @@ -150,6 +73,21 @@ public: Node getValue(TNode n); std::string identify() const { return std::string("TheoryBV"); } + + //Node preprocessTerm(TNode term); + PPAssertStatus ppAssert(TNode in, SubstitutionMap& outSubstitutions); +private: + + class Statistics { + public: + AverageStat d_avgConflictSize; + IntStat d_solveSubstitutions; + Statistics(); + ~Statistics(); + }; + + Statistics d_statistics; + };/* class TheoryBV */ }/* CVC4::theory::bv namespace */ diff --git a/src/theory/bv/theory_bv_rewrite_rules.h b/src/theory/bv/theory_bv_rewrite_rules.h index 32bbf973f..2e2347d3c 100644 --- a/src/theory/bv/theory_bv_rewrite_rules.h +++ b/src/theory/bv/theory_bv_rewrite_rules.h @@ -31,6 +31,7 @@ namespace theory { namespace bv { enum RewriteRuleId { + /// core rewrite rules EmptyRule, ConcatFlatten, ConcatExtractMerge, @@ -42,7 +43,24 @@ enum RewriteRuleId { FailEq, SimplifyEq, ReflexivityEq, -}; + /// operator elimination rules + UgtToUlt, + UgeToUle, + SgeToSle, + SgtToSlt, + RepeatEliminate, + RotateLeftEliminate, + RotateRightEliminate, + NandEliminate, + NorEliminate, + SdivEliminate, + UdivEliminate, + SmodEliminate, + SremEliminate, + ZeroExtendEliminate, + // division by zero guards: rewrite a / b as b!=0 => a/b = ... + DivZeroGuard + }; inline std::ostream& operator << (std::ostream& out, RewriteRuleId ruleId) { switch (ruleId) { @@ -57,6 +75,20 @@ inline std::ostream& operator << (std::ostream& out, RewriteRuleId ruleId) { case FailEq: out << "FailEq"; return out; case SimplifyEq: out << "SimplifyEq"; return out; case ReflexivityEq: out << "ReflexivityEq"; return out; + case UgtToUlt: out << "UgtToUlt"; return out; + case SgtToSlt: out << "SgtToSlt"; return out; + case UgeToUle: out << "UgeToUle"; return out; + case SgeToSle: out << "SgeToSle"; return out; + case RepeatEliminate: out << "RepeatEliminate"; return out; + case RotateLeftEliminate: out << "RotateLeftEliminate"; return out; + case RotateRightEliminate:out << "RotateRightEliminate";return out; + case NandEliminate: out << "NandEliminate"; return out; + case NorEliminate : out << "NorEliminate"; return out; + case SdivEliminate : out << "SdivEliminate"; return out; + case SremEliminate : out << "SremEliminate"; return out; + case SmodEliminate : out << "SmodEliminate"; return out; + case ZeroExtendEliminate :out << "ZeroExtendEliminate"; return out; + case DivZeroGuard : out << "DivZeroGuard"; return out; default: Unreachable(); } @@ -147,6 +179,7 @@ typename RewriteRule<rule>::RuleStatistics* RewriteRule<rule>::s_statistics = NU /** Have to list all the rewrite rules to get the statistics out */ struct AllRewriteRules { + RewriteRule<EmptyRule> rule00; RewriteRule<ConcatFlatten> rule01; RewriteRule<ConcatExtractMerge> rule02; @@ -158,6 +191,20 @@ struct AllRewriteRules { RewriteRule<FailEq> rule08; RewriteRule<SimplifyEq> rule09; RewriteRule<ReflexivityEq> rule10; + RewriteRule<UgtToUlt> rule11; + RewriteRule<SgtToSlt> rule12; + RewriteRule<UgeToUle> rule13; + RewriteRule<SgeToSle> rule14; + RewriteRule<RepeatEliminate> rule17; + RewriteRule<RotateLeftEliminate> rule18; + RewriteRule<RotateRightEliminate> rule19; + RewriteRule<NandEliminate> rule20; + RewriteRule<NorEliminate> rule21; + RewriteRule<SdivEliminate> rule22; + RewriteRule<SremEliminate> rule23; + RewriteRule<SmodEliminate> rule24; + RewriteRule<DivZeroGuard> rule25; + }; template<> @@ -202,7 +249,7 @@ struct ApplyRuleToChildren { template < typename R1, - typename R2, + typename R2 = RewriteRule<EmptyRule>, typename R3 = RewriteRule<EmptyRule>, typename R4 = RewriteRule<EmptyRule>, typename R5 = RewriteRule<EmptyRule>, diff --git a/src/theory/bv/theory_bv_rewrite_rules_arith.h b/src/theory/bv/theory_bv_rewrite_rules_arith.h new file mode 100644 index 000000000..08a571db3 --- /dev/null +++ b/src/theory/bv/theory_bv_rewrite_rules_arith.h @@ -0,0 +1,321 @@ +/********************* */ +/*! \file theory_bv_rewrite_rules_core.h + ** \verbatim + ** Original author: dejan + ** Major contributors: none + ** Minor contributors (to current version): mdeters + ** This file is part of the CVC4 prototype. + ** Copyright (c) 2009, 2010, 2011 The Analysis of Computer Systems Group (ACSys) + ** Courant Institute of Mathematical Sciences + ** New York University + ** See the file COPYING in the top-level source directory for licensing + ** information.\endverbatim + ** + ** \brief [[ Add one-line brief description here ]] + ** + ** [[ Add lengthier description here ]] + ** \todo document this file + **/ + +#include "cvc4_private.h" + +#pragma once + +#include "theory/bv/theory_bv_rewrite_rules.h" +#include "theory/bv/theory_bv_utils.h" + +namespace CVC4 { +namespace theory { +namespace bv { + +template<> +bool RewriteRule<UgtToUlt>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_UGT); +} + +template<> +Node RewriteRule<UgtToUlt>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<UgtToUlt>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node result = utils::mkNode(kind::BITVECTOR_ULT, b, a); + return result; +} + + +template<> +bool RewriteRule<UgeToUle>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_UGE); +} + +template<> +Node RewriteRule<UgeToUle>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<UgeToUle>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node result = utils::mkNode(kind::BITVECTOR_ULE, b, a); + return result; +} + + +template<> +bool RewriteRule<SgtToSlt>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_SGT); +} + +template<> +Node RewriteRule<SgtToSlt>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<UgtToUlt>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node result = utils::mkNode(kind::BITVECTOR_SLT, b, a); + return result; +} + + +template<> +bool RewriteRule<SgeToSle>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_SGE); +} + +template<> +Node RewriteRule<SgeToSle>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<SgeToSle>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node result = utils::mkNode(kind::BITVECTOR_SLE, b, a); + return result; +} + +template<> +bool RewriteRule<RepeatEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_REPEAT); +} + +template<> +Node RewriteRule<RepeatEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<RepeatEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + unsigned amount = node.getOperator().getConst<BitVectorRepeat>().repeatAmount; + Assert(amount >= 1); + if(amount == 1) { + return a; + } + NodeBuilder<> result(kind::BITVECTOR_CONCAT); + for(unsigned i = 0; i < amount; ++i) { + result << node[0]; + } + Node resultNode = result; + return resultNode; +} + +template<> +bool RewriteRule<RotateLeftEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_ROTATE_LEFT); +} + +template<> +Node RewriteRule<RotateLeftEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<RotateLeftEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + unsigned amount = node.getOperator().getConst<BitVectorRotateLeft>().rotateLeftAmount; + amount = amount % utils::getSize(a); + if (amount == 0) { + return a; + } + + Node left = utils::mkExtract(a, utils::getSize(a)-1 - amount, 0); + Node right = utils::mkExtract(a, utils::getSize(a) -1, utils::getSize(a) - amount); + Node result = utils::mkConcat(left, right); + + return result; +} + +template<> +bool RewriteRule<RotateRightEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_ROTATE_RIGHT); +} + +template<> +Node RewriteRule<RotateRightEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<RotateRightEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + unsigned amount = node.getOperator().getConst<BitVectorRotateRight>().rotateRightAmount; + amount = amount % utils::getSize(a); + if (amount == 0) { + return a; + } + + Node left = utils::mkExtract(a, amount - 1, 0); + Node right = utils::mkExtract(a, utils::getSize(a)-1, amount); + Node result = utils::mkConcat(left, right); + + return result; +} + +template<> +bool RewriteRule<NandEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_NAND); +} + +template<> +Node RewriteRule<NandEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<NandEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node andNode = utils::mkNode(kind::BITVECTOR_AND, a, b); + Node result = utils::mkNode(kind::BITVECTOR_NOT, andNode); + return result; +} + +template<> +bool RewriteRule<NorEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_NOR); +} + +template<> +Node RewriteRule<NorEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<NorEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + Node orNode = utils::mkNode(kind::BITVECTOR_OR, a, b); + Node result = utils::mkNode(kind::BITVECTOR_NOT, orNode); + return result; +} + +template<> +bool RewriteRule<SdivEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_SDIV); +} + +template<> +Node RewriteRule<SdivEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<SdivEliminate>(" << node << ")" << std::endl; + + TNode a = node[0]; + TNode b = node[1]; + unsigned size = utils::getSize(a); + + Node one = utils::mkConst(1, 1); + Node a_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(a, size-1, size-1), one); + Node b_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(b, size-1, size-1), one); + Node abs_a = utils::mkNode(kind::ITE, a_lt_0, utils::mkNode(kind::BITVECTOR_NEG, a), a); + Node abs_b = utils::mkNode(kind::ITE, b_lt_0, utils::mkNode(kind::BITVECTOR_NEG, b), b); + + Node a_udiv_b = utils::mkNode(kind::BITVECTOR_UDIV, abs_a, abs_b); + Node neg_result = utils::mkNode(kind::BITVECTOR_NEG, a_udiv_b); + + Node condition = utils::mkNode(kind::XOR, a_lt_0, b_lt_0); + Node result = utils::mkNode(kind::ITE, condition, neg_result, a_udiv_b); + + return result; +} + + +template<> +bool RewriteRule<SremEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_SREM); +} + +template<> +Node RewriteRule<SremEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<SremEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + unsigned size = utils::getSize(a); + + Node one = utils::mkConst(1, 1); + Node a_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(a, size-1, size-1), one); + Node b_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(b, size-1, size-1), one); + Node abs_a = utils::mkNode(kind::ITE, a_lt_0, utils::mkNode(kind::BITVECTOR_NEG, a), a); + Node abs_b = utils::mkNode(kind::ITE, b_lt_0, utils::mkNode(kind::BITVECTOR_NEG, b), b); + + Node a_urem_b = utils::mkNode(kind::BITVECTOR_UREM, abs_a, abs_b); + Node neg_result = utils::mkNode(kind::BITVECTOR_NEG, a_urem_b); + + Node result = utils::mkNode(kind::ITE, a_lt_0, neg_result, a_urem_b); + + return result; +} + +template<> +bool RewriteRule<SmodEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_SMOD); +} + +template<> +Node RewriteRule<SmodEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<SmodEliminate>(" << node << ")" << std::endl; + TNode a = node[0]; + TNode b = node[1]; + unsigned size = utils::getSize(a); + + Node one = utils::mkConst(1, 1); + Node zero = utils::mkConst(1, 0); + Node a_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(a, size-1, size-1), one); + Node b_lt_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(b, size-1, size-1), one); + + Node a_gte_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(a, size-1, size-1), zero); + Node b_gte_0 = utils::mkNode(kind::EQUAL, utils::mkExtract(b, size-1, size-1), zero); + + Node abs_a = utils::mkNode(kind::ITE, a_lt_0, utils::mkNode(kind::BITVECTOR_NEG, a), a); + Node abs_b = utils::mkNode(kind::ITE, b_lt_0, utils::mkNode(kind::BITVECTOR_NEG, b), b); + + Node a_urem_b = utils::mkNode(kind::BITVECTOR_UREM, abs_a, abs_b); + Node neg_rem = utils::mkNode(kind::BITVECTOR_NEG, a_urem_b); + + + Node aneg_bpos = utils::mkNode(kind::AND, a_lt_0, b_gte_0); + Node apos_bneg = utils::mkNode(kind::AND, a_gte_0, b_lt_0); + Node aneg_bneg = utils::mkNode(kind::AND, a_lt_0, b_lt_0); + + Node result = utils::mkNode(kind::ITE, aneg_bpos, utils::mkNode(kind::BITVECTOR_PLUS, neg_rem, b), + utils::mkNode(kind::ITE, apos_bneg, utils::mkNode(kind::BITVECTOR_PLUS, a_urem_b, b), + utils::mkNode(kind::ITE, aneg_bneg, neg_rem, + a_urem_b))); + return result; +} + + +template<> +bool RewriteRule<ZeroExtendEliminate>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_ZERO_EXTEND); +} + +template<> +Node RewriteRule<ZeroExtendEliminate>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<ZeroExtendEliminate>(" << node << ")" << std::endl; + + TNode bv = node[0]; + unsigned amount = node.getOperator().getConst<BitVectorZeroExtend>().zeroExtendAmount; + + Node zero = utils::mkConst(amount, 0); + Node result = utils::mkConcat(zero, node[0]); + + return result; +} + + +template<> +bool RewriteRule<DivZeroGuard>::applies(Node node) { + return (node.getKind() == kind::BITVECTOR_UDIV || + node.getKind() == kind::BITVECTOR_UREM || + node.getKind() == kind::BITVECTOR_SDIV || + node.getKind() == kind::BITVECTOR_SREM || + node.getKind() == kind::BITVECTOR_SMOD); +} + +template<> +Node RewriteRule<DivZeroGuard>::apply(Node node) { + BVDebug("bv-rewrite") << "RewriteRule<DivZeroGuard>(" << node << ")" << std::endl; + + Unimplemented(); + +} + + + + +} +} +} diff --git a/src/theory/bv/theory_bv_rewriter.cpp b/src/theory/bv/theory_bv_rewriter.cpp index 566bf3a68..2f3538837 100644 --- a/src/theory/bv/theory_bv_rewriter.cpp +++ b/src/theory/bv/theory_bv_rewriter.cpp @@ -21,17 +21,17 @@ #include "theory/bv/theory_bv_rewriter.h" #include "theory/bv/theory_bv_rewrite_rules.h" #include "theory/bv/theory_bv_rewrite_rules_core.h" +#include "theory/bv/theory_bv_rewrite_rules_arith.h" using namespace CVC4; using namespace CVC4::theory; using namespace CVC4::theory::bv; RewriteResponse TheoryBVRewriter::postRewrite(TNode node) { - + BVDebug("bitvector") << "TheoryBV::postRewrite(" << node << ")" << std::endl; - - Node result; - + + Node result = node; if (node.getKind() == kind::CONST_BITVECTOR || (node.getKind() != kind::EQUAL && Theory::isLeafOf(node, THEORY_BV))) { result = node; } else { @@ -67,10 +67,78 @@ RewriteResponse TheoryBVRewriter::postRewrite(TNode node) { RewriteRule<FailEq>, // If both sides are equal equality is true RewriteRule<SimplifyEq>, - // Normalize the equalities + // Eliminate the equalities RewriteRule<ReflexivityEq> >::apply(node); break; + case kind::BITVECTOR_UGT: + result = LinearRewriteStrategy < + RewriteRule<UgtToUlt> + >::apply(node); + break; + + case kind::BITVECTOR_UGE: + result = LinearRewriteStrategy < + RewriteRule<UgeToUle> + >::apply(node); + break; + case kind::BITVECTOR_SGT: + result = LinearRewriteStrategy < + RewriteRule<SgtToSlt> + >::apply(node); + break; + case kind::BITVECTOR_SGE: + result = LinearRewriteStrategy < + RewriteRule<SgeToSle> + >::apply(node); + break; + case kind::BITVECTOR_REPEAT: + result = LinearRewriteStrategy < + RewriteRule<RepeatEliminate> + >::apply(node); + break; + case kind::BITVECTOR_ROTATE_RIGHT: + result = LinearRewriteStrategy < + RewriteRule<RotateRightEliminate> + >::apply(node); + break; + case kind::BITVECTOR_ROTATE_LEFT: + result = LinearRewriteStrategy < + RewriteRule<RotateLeftEliminate> + >::apply(node); + break; + case kind::BITVECTOR_NAND: + result = LinearRewriteStrategy < + RewriteRule<NandEliminate> + >::apply(node); + break; + case kind::BITVECTOR_NOR: + result = LinearRewriteStrategy < + RewriteRule<NorEliminate> + >::apply(node); + break; + + case kind::BITVECTOR_SDIV: + result = LinearRewriteStrategy < + RewriteRule<SdivEliminate> + >::apply(node); + break; + case kind::BITVECTOR_SREM: + result = LinearRewriteStrategy < + RewriteRule<SremEliminate> + >::apply(node); + break; + case kind::BITVECTOR_SMOD: + result = LinearRewriteStrategy < + RewriteRule<SmodEliminate> + >::apply(node); + break; + case kind::BITVECTOR_ZERO_EXTEND: + result = LinearRewriteStrategy < + RewriteRule<ZeroExtendEliminate> + >::apply(node); + break; + default: // TODO: figure out when this is an operator result = node; diff --git a/src/theory/bv/theory_bv_rewriter.h b/src/theory/bv/theory_bv_rewriter.h index f0eb621ca..1893977a8 100644 --- a/src/theory/bv/theory_bv_rewriter.h +++ b/src/theory/bv/theory_bv_rewriter.h @@ -39,7 +39,7 @@ public: static RewriteResponse postRewrite(TNode node); static inline RewriteResponse preRewrite(TNode node) { - return RewriteResponse(REWRITE_DONE, node); + return postRewrite(node); } static inline Node rewriteEquality(TNode node) { diff --git a/src/theory/bv/theory_bv_type_rules.h b/src/theory/bv/theory_bv_type_rules.h index 192295bc0..91b3a0e5d 100644 --- a/src/theory/bv/theory_bv_type_rules.h +++ b/src/theory/bv/theory_bv_type_rules.h @@ -35,6 +35,28 @@ public: } }; + +class BitVectorBitOfTypeRule { +public: + inline static TypeNode computeType(NodeManager* nodeManager, TNode n, bool check) + throw (TypeCheckingExceptionPrivate) { + + if(check) { + BitVectorBitOf info = n.getOperator().getConst<BitVectorBitOf>(); + TypeNode t = n[0].getType(check); + + if (!t.isBitVector()) { + throw TypeCheckingExceptionPrivate(n, "expecting bit-vector term"); + } + if (info.bitIndex >= t.getBitVectorSize()) { + throw TypeCheckingExceptionPrivate(n, "extract index is larger than the bitvector size"); + } + } + return nodeManager->booleanType(); + } +}; + + class BitVectorCompRule { public: inline static TypeNode computeType(NodeManager* nodeManager, TNode n, bool check) diff --git a/src/theory/bv/theory_bv_utils.h b/src/theory/bv/theory_bv_utils.h index 80c5ca7f7..6bd7368c9 100644 --- a/src/theory/bv/theory_bv_utils.h +++ b/src/theory/bv/theory_bv_utils.h @@ -49,6 +49,13 @@ inline unsigned getSize(TNode node) { return node.getType().getBitVectorSize(); } +// this seems to behave strangely +inline const Integer& getBit(TNode node, unsigned i) { + Assert (0); + Assert (node.getKind() == kind::CONST_BITVECTOR); + return node.getConst<BitVector>().extract(i, i).getValue(); +} + inline Node mkTrue() { return NodeManager::currentNM()->mkConst<bool>(true); } @@ -57,6 +64,11 @@ inline Node mkFalse() { return NodeManager::currentNM()->mkConst<bool>(false); } +inline Node mkVar(unsigned size) { + NodeManager* nm = NodeManager::currentNM(); + return nm->mkVar(nm->mkBitVectorType(size)); +} + inline Node mkAnd(std::vector<TNode>& children) { if (children.size() > 1) { return NodeManager::currentNM()->mkNode(kind::AND, children); @@ -65,8 +77,43 @@ inline Node mkAnd(std::vector<TNode>& children) { } } + +inline Node mkNode(Kind kind, TNode child) { + return NodeManager::currentNM()->mkNode(kind, child); +} + +inline Node mkNode(Kind kind, TNode child1, TNode child2) { + return NodeManager::currentNM()->mkNode(kind, child1, child2); +} + +inline Node mkNode(Kind kind, TNode child1, TNode child2, TNode child3) { + return NodeManager::currentNM()->mkNode(kind, child1, child2, child3); +} + + +inline Node mkNot(Node child) { + return NodeManager::currentNM()->mkNode(kind::NOT, child); +} + +inline Node mkAnd(TNode node1, TNode node2) { + return NodeManager::currentNM()->mkNode(kind::AND, node1, node2); +} + +inline Node mkOr(TNode node1, TNode node2) { + return NodeManager::currentNM()->mkNode(kind::OR, node1, node2); +} + +inline Node mkXor(TNode node1, TNode node2) { + return NodeManager::currentNM()->mkNode(kind::XOR, node1, node2); +} + + inline Node mkAnd(std::vector<Node>& children) { - return NodeManager::currentNM()->mkNode(kind::AND, children); + if(children.size() > 1) { + return NodeManager::currentNM()->mkNode(kind::AND, children); + } else { + return children[0]; + } } inline Node mkExtract(TNode node, unsigned high, unsigned low) { @@ -76,6 +123,12 @@ inline Node mkExtract(TNode node, unsigned high, unsigned low) { return NodeManager::currentNM()->mkNode(extractOp, children); } +inline Node mkBitOf(TNode node, unsigned index) { + Node bitOfOp = NodeManager::currentNM()->mkConst<BitVectorBitOf>(BitVectorBitOf(index)); + return NodeManager::currentNM()->mkNode(bitOfOp, node); + +} + inline Node mkConcat(std::vector<Node>& children) { if (children.size() > 1) return NodeManager::currentNM()->mkNode(kind::BITVECTOR_CONCAT, children); @@ -88,6 +141,11 @@ inline Node mkConcat(TNode t1, TNode t2) { } +inline Node mkConst(unsigned size, unsigned int value) { + BitVector val(size, value); + return NodeManager::currentNM()->mkConst<BitVector>(val); +} + inline Node mkConst(const BitVector& value) { return NodeManager::currentNM()->mkConst<BitVector>(value); } @@ -139,6 +197,66 @@ inline Node mkConjunction(const std::set<TNode> nodes) { return conjunction; } +inline bool isBVPredicate(TNode node) { + if (node.getKind() == kind::EQUAL || + node.getKind() == kind::BITVECTOR_ULT || + node.getKind() == kind::BITVECTOR_SLT || + node.getKind() == kind::BITVECTOR_UGT || + node.getKind() == kind::BITVECTOR_UGE || + node.getKind() == kind::BITVECTOR_SGT || + node.getKind() == kind::BITVECTOR_SGE || + node.getKind() == kind::BITVECTOR_ULE || + node.getKind() == kind::BITVECTOR_SLE || + ( node.getKind() == kind::NOT && (node[0].getKind() == kind::EQUAL || + node[0].getKind() == kind::BITVECTOR_ULT || + node[0].getKind() == kind::BITVECTOR_SLT || + node[0].getKind() == kind::BITVECTOR_UGT || + node[0].getKind() == kind::BITVECTOR_UGE || + node[0].getKind() == kind::BITVECTOR_SGT || + node[0].getKind() == kind::BITVECTOR_SGE || + node[0].getKind() == kind::BITVECTOR_ULE || + node[0].getKind() == kind::BITVECTOR_SLE))) + { + return true; + } + else + { + return false; + } +} + +inline Node mkConjunction(const std::vector<TNode>& nodes) { + std::vector<TNode> expandedNodes; + + std::vector<TNode>::const_iterator it = nodes.begin(); + std::vector<TNode>::const_iterator it_end = nodes.end(); + while (it != it_end) { + TNode current = *it; + if (current != mkTrue()) { + Assert(isBVPredicate(current)); + expandedNodes.push_back(current); + } + ++ it; + } + + Assert(expandedNodes.size() > 0); + if (expandedNodes.size() == 1) { + return *expandedNodes.begin(); + } + + NodeBuilder<> conjunction(kind::AND); + + it = expandedNodes.begin(); + it_end = expandedNodes.end(); + while (it != it_end) { + conjunction << *it; + ++ it; + } + + return conjunction; +} + + // Turn a set into a string inline std::string setToString(const std::set<TNode>& nodeSet) { std::stringstream out; diff --git a/src/theory/registrar.h b/src/theory/theory_registrar.h index 19315827e..810ef1f67 100644 --- a/src/theory/registrar.h +++ b/src/theory/theory_registrar.h @@ -22,29 +22,30 @@ #include "cvc4_private.h" -#ifndef __CVC4__THEORY__REGISTRAR_H -#define __CVC4__THEORY__REGISTRAR_H +#ifndef __CVC4__THEORY__THEORY_REGISTRAR_H +#define __CVC4__THEORY__THEORY_REGISTRAR_H +#include "prop/registrar.h" #include "theory/theory_engine.h" namespace CVC4 { namespace theory { -class Registrar { +class TheoryRegistrar: public prop::Registrar { private: TheoryEngine* d_theoryEngine; public: - Registrar(TheoryEngine* te) : d_theoryEngine(te) { } + TheoryRegistrar(TheoryEngine* te) : d_theoryEngine(te) { } void preRegister(Node n) { d_theoryEngine->preRegister(n); } -};/* class Registrar */ +};/* class TheoryRegistrar */ }/* CVC4::theory namespace */ }/* CVC4 namespace */ -#endif /* __CVC4__THEORY__REGISTRAR_H */ +#endif /* __CVC4__THEORY__THEORY_REGISTRAR_H */ diff --git a/src/util/bitvector.h b/src/util/bitvector.h index d7f0e13a5..8adb466cf 100644 --- a/src/util/bitvector.h +++ b/src/util/bitvector.h @@ -203,6 +203,33 @@ public: } };/* class BitVectorExtractHashStrategy */ + +/** + * The structure representing the extraction of one Boolean bit. + */ +struct CVC4_PUBLIC BitVectorBitOf { + /** The index of the bit */ + unsigned bitIndex; + BitVectorBitOf(unsigned i) + : bitIndex(i) {} + + bool operator == (const BitVectorBitOf& other) const { + return bitIndex == other.bitIndex; + } +};/* struct BitVectorBitOf */ + +/** + * Hash function for the BitVectorBitOf objects. + */ +class CVC4_PUBLIC BitVectorBitOfHashStrategy { +public: + static size_t hash(const BitVectorBitOf& b) { + return b.bitIndex; + } +};/* class BitVectorBitOfHashStrategy */ + + + struct CVC4_PUBLIC BitVectorSize { unsigned size; BitVectorSize(unsigned size) @@ -262,6 +289,13 @@ inline std::ostream& operator <<(std::ostream& os, const BitVectorExtract& bv) { return os << "[" << bv.high << ":" << bv.low << "]"; } +inline std::ostream& operator <<(std::ostream& os, const BitVectorBitOf& bv) CVC4_PUBLIC; +inline std::ostream& operator <<(std::ostream& os, const BitVectorBitOf& bv) { + return os << "[" << bv.bitIndex << "]"; +} + + + }/* CVC4 namespace */ #endif /* __CVC4__BITVECTOR_H */ |