Split ext theory to own file and document (#1809)
[cvc5.git] / src / theory / bv / theory_bv.cpp
1 /********************* */
2 /*! \file theory_bv.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Liana Hadarean, Andrew Reynolds, Aina Niemetz
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** [[ Add lengthier description here ]]
13 ** \todo document this file
14 **/
15
16 #include "theory/bv/theory_bv.h"
17
18 #include "options/bv_options.h"
19 #include "options/smt_options.h"
20 #include "proof/proof_manager.h"
21 #include "proof/theory_proof.h"
22 #include "smt/smt_statistics_registry.h"
23 #include "theory/bv/abstraction.h"
24 #include "theory/bv/bv_eager_solver.h"
25 #include "theory/bv/bv_subtheory_algebraic.h"
26 #include "theory/bv/bv_subtheory_bitblast.h"
27 #include "theory/bv/bv_subtheory_core.h"
28 #include "theory/bv/bv_subtheory_inequality.h"
29 #include "theory/bv/slicer.h"
30 #include "theory/bv/theory_bv_rewrite_rules_normalization.h"
31 #include "theory/bv/theory_bv_rewrite_rules_simplification.h"
32 #include "theory/bv/theory_bv_rewriter.h"
33 #include "theory/bv/theory_bv_utils.h"
34 #include "theory/ext_theory.h"
35 #include "theory/theory_model.h"
36 #include "theory/valuation.h"
37
38 using namespace CVC4::context;
39 using namespace CVC4::theory::bv::utils;
40 using namespace std;
41
42 namespace CVC4 {
43 namespace theory {
44 namespace bv {
45
46 TheoryBV::TheoryBV(context::Context* c, context::UserContext* u,
47 OutputChannel& out, Valuation valuation,
48 const LogicInfo& logicInfo, std::string name)
49 : Theory(THEORY_BV, c, u, out, valuation, logicInfo, name),
50 d_context(c),
51 d_alreadyPropagatedSet(c),
52 d_sharedTermsSet(c),
53 d_subtheories(),
54 d_subtheoryMap(),
55 d_statistics(),
56 d_staticLearnCache(),
57 d_BVDivByZero(),
58 d_BVRemByZero(),
59 d_lemmasAdded(c, false),
60 d_conflict(c, false),
61 d_invalidateModelCache(c, true),
62 d_literalsToPropagate(c),
63 d_literalsToPropagateIndex(c, 0),
64 d_propagatedBy(c),
65 d_eagerSolver(NULL),
66 d_abstractionModule(new AbstractionModule(getStatsPrefix(THEORY_BV))),
67 d_isCoreTheory(false),
68 d_calledPreregister(false),
69 d_needsLastCallCheck(false),
70 d_extf_range_infer(u),
71 d_extf_collapse_infer(u)
72 {
73 setupExtTheory();
74 getExtTheory()->addFunctionKind(kind::BITVECTOR_TO_NAT);
75 getExtTheory()->addFunctionKind(kind::INT_TO_BITVECTOR);
76 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
77 d_eagerSolver = new EagerBitblastSolver(this);
78 return;
79 }
80
81 if (options::bitvectorEqualitySolver() && !options::proof())
82 {
83 SubtheorySolver* core_solver = new CoreSolver(c, this);
84 d_subtheories.push_back(core_solver);
85 d_subtheoryMap[SUB_CORE] = core_solver;
86 }
87
88 if (options::bitvectorInequalitySolver() && !options::proof())
89 {
90 SubtheorySolver* ineq_solver = new InequalitySolver(c, u, this);
91 d_subtheories.push_back(ineq_solver);
92 d_subtheoryMap[SUB_INEQUALITY] = ineq_solver;
93 }
94
95 if (options::bitvectorAlgebraicSolver() && !options::proof())
96 {
97 SubtheorySolver* alg_solver = new AlgebraicSolver(c, this);
98 d_subtheories.push_back(alg_solver);
99 d_subtheoryMap[SUB_ALGEBRAIC] = alg_solver;
100 }
101
102 BitblastSolver* bb_solver = new BitblastSolver(c, this);
103 if (options::bvAbstraction()) {
104 bb_solver->setAbstraction(d_abstractionModule);
105 }
106 d_subtheories.push_back(bb_solver);
107 d_subtheoryMap[SUB_BITBLAST] = bb_solver;
108 }
109
110 TheoryBV::~TheoryBV() {
111 if (d_eagerSolver) {
112 delete d_eagerSolver;
113 }
114 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
115 delete d_subtheories[i];
116 }
117 delete d_abstractionModule;
118 }
119
120 void TheoryBV::setMasterEqualityEngine(eq::EqualityEngine* eq) {
121 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
122 return;
123 }
124 if (options::bitvectorEqualitySolver()) {
125 dynamic_cast<CoreSolver*>(d_subtheoryMap[SUB_CORE])->setMasterEqualityEngine(eq);
126 }
127 }
128
129 void TheoryBV::spendResource(unsigned amount)
130 {
131 getOutputChannel().spendResource(amount);
132 }
133
134 TheoryBV::Statistics::Statistics():
135 d_avgConflictSize("theory::bv::AvgBVConflictSize"),
136 d_solveSubstitutions("theory::bv::NumSolveSubstitutions", 0),
137 d_solveTimer("theory::bv::solveTimer"),
138 d_numCallsToCheckFullEffort("theory::bv::NumFullCheckCalls", 0),
139 d_numCallsToCheckStandardEffort("theory::bv::NumStandardCheckCalls", 0),
140 d_weightComputationTimer("theory::bv::weightComputationTimer"),
141 d_numMultSlice("theory::bv::NumMultSliceApplied", 0)
142 {
143 smtStatisticsRegistry()->registerStat(&d_avgConflictSize);
144 smtStatisticsRegistry()->registerStat(&d_solveSubstitutions);
145 smtStatisticsRegistry()->registerStat(&d_solveTimer);
146 smtStatisticsRegistry()->registerStat(&d_numCallsToCheckFullEffort);
147 smtStatisticsRegistry()->registerStat(&d_numCallsToCheckStandardEffort);
148 smtStatisticsRegistry()->registerStat(&d_weightComputationTimer);
149 smtStatisticsRegistry()->registerStat(&d_numMultSlice);
150 }
151
152 TheoryBV::Statistics::~Statistics() {
153 smtStatisticsRegistry()->unregisterStat(&d_avgConflictSize);
154 smtStatisticsRegistry()->unregisterStat(&d_solveSubstitutions);
155 smtStatisticsRegistry()->unregisterStat(&d_solveTimer);
156 smtStatisticsRegistry()->unregisterStat(&d_numCallsToCheckFullEffort);
157 smtStatisticsRegistry()->unregisterStat(&d_numCallsToCheckStandardEffort);
158 smtStatisticsRegistry()->unregisterStat(&d_weightComputationTimer);
159 smtStatisticsRegistry()->unregisterStat(&d_numMultSlice);
160 }
161
162 Node TheoryBV::getBVDivByZero(Kind k, unsigned width) {
163 NodeManager* nm = NodeManager::currentNM();
164 if (k == kind::BITVECTOR_UDIV) {
165 if (d_BVDivByZero.find(width) == d_BVDivByZero.end()) {
166 // lazily create the function symbols
167 ostringstream os;
168 os << "BVUDivByZero_" << width;
169 Node divByZero = nm->mkSkolem(os.str(),
170 nm->mkFunctionType(nm->mkBitVectorType(width), nm->mkBitVectorType(width)),
171 "partial bvudiv", NodeManager::SKOLEM_EXACT_NAME);
172 d_BVDivByZero[width] = divByZero;
173 }
174 return d_BVDivByZero[width];
175 }
176 else if (k == kind::BITVECTOR_UREM) {
177 if (d_BVRemByZero.find(width) == d_BVRemByZero.end()) {
178 ostringstream os;
179 os << "BVURemByZero_" << width;
180 Node divByZero = nm->mkSkolem(os.str(),
181 nm->mkFunctionType(nm->mkBitVectorType(width), nm->mkBitVectorType(width)),
182 "partial bvurem", NodeManager::SKOLEM_EXACT_NAME);
183 d_BVRemByZero[width] = divByZero;
184 }
185 return d_BVRemByZero[width];
186 }
187
188 Unreachable();
189 }
190
191 void TheoryBV::finishInit()
192 {
193 // these kinds are semi-evaluated in getModelValue (applications of this
194 // kind are treated as variables)
195 TheoryModel* tm = d_valuation.getModel();
196 Assert(tm != nullptr);
197 tm->setSemiEvaluatedKind(kind::BITVECTOR_ACKERMANNIZE_UDIV);
198 tm->setSemiEvaluatedKind(kind::BITVECTOR_ACKERMANNIZE_UREM);
199 }
200
201 Node TheoryBV::expandDefinition(LogicRequest &logicRequest, Node node) {
202 Debug("bitvector-expandDefinition") << "TheoryBV::expandDefinition(" << node << ")" << std::endl;
203
204 switch (node.getKind()) {
205 case kind::BITVECTOR_SDIV:
206 case kind::BITVECTOR_SREM:
207 case kind::BITVECTOR_SMOD:
208 return TheoryBVRewriter::eliminateBVSDiv(node);
209 break;
210
211 case kind::BITVECTOR_UDIV:
212 case kind::BITVECTOR_UREM: {
213 NodeManager* nm = NodeManager::currentNM();
214 unsigned width = node.getType().getBitVectorSize();
215
216 if (options::bitvectorDivByZeroConst()) {
217 Kind kind = node.getKind() == kind::BITVECTOR_UDIV ? kind::BITVECTOR_UDIV_TOTAL : kind::BITVECTOR_UREM_TOTAL;
218 return nm->mkNode(kind, node[0], node[1]);
219 }
220
221 TNode num = node[0], den = node[1];
222 Node den_eq_0 = nm->mkNode(kind::EQUAL, den, utils::mkZero(width));
223 Node divTotalNumDen = nm->mkNode(node.getKind() == kind::BITVECTOR_UDIV ? kind::BITVECTOR_UDIV_TOTAL :
224 kind::BITVECTOR_UREM_TOTAL, num, den);
225 Node divByZero = getBVDivByZero(node.getKind(), width);
226 Node divByZeroNum = nm->mkNode(kind::APPLY_UF, divByZero, num);
227 node = nm->mkNode(kind::ITE, den_eq_0, divByZeroNum, divTotalNumDen);
228 logicRequest.widenLogic(THEORY_UF);
229 return node;
230 }
231 break;
232
233 default:
234 return node;
235 break;
236 }
237
238 Unreachable();
239 }
240
241
242 void TheoryBV::preRegisterTerm(TNode node) {
243 d_calledPreregister = true;
244 Debug("bitvector-preregister") << "TheoryBV::preRegister(" << node << ")" << std::endl;
245
246 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
247 // the aig bit-blaster option is set heuristically
248 // if bv abstraction is not used
249 if (!d_eagerSolver->isInitialized()) {
250 d_eagerSolver->initialize();
251 }
252
253 if (node.getKind() == kind::BITVECTOR_EAGER_ATOM) {
254 Node formula = node[0];
255 d_eagerSolver->assertFormula(formula);
256 }
257 // nothing to do for the other terms
258 return;
259 }
260
261 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
262 d_subtheories[i]->preRegister(node);
263 }
264
265 // AJR : equality solver currently registers all terms to ExtTheory, if we want a lazy reduction without the bv equality solver, need to call this
266 //getExtTheory()->registerTermRec( node );
267 }
268
269 void TheoryBV::sendConflict() {
270 Assert(d_conflict);
271 if (d_conflictNode.isNull()) {
272 return;
273 } else {
274 Debug("bitvector") << indent() << "TheoryBV::check(): conflict " << d_conflictNode << std::endl;
275 d_out->conflict(d_conflictNode);
276 d_statistics.d_avgConflictSize.addEntry(d_conflictNode.getNumChildren());
277 d_conflictNode = Node::null();
278 }
279 }
280
281 void TheoryBV::checkForLemma(TNode fact)
282 {
283 if (fact.getKind() == kind::EQUAL)
284 {
285 NodeManager* nm = NodeManager::currentNM();
286 if (fact[0].getKind() == kind::BITVECTOR_UREM_TOTAL)
287 {
288 TNode urem = fact[0];
289 TNode result = fact[1];
290 TNode divisor = urem[1];
291 Node result_ult_div = nm->mkNode(kind::BITVECTOR_ULT, result, divisor);
292 Node divisor_eq_0 =
293 nm->mkNode(kind::EQUAL, divisor, mkZero(getSize(divisor)));
294 Node split = nm->mkNode(
295 kind::OR, divisor_eq_0, nm->mkNode(kind::NOT, fact), result_ult_div);
296 lemma(split);
297 }
298 if (fact[1].getKind() == kind::BITVECTOR_UREM_TOTAL)
299 {
300 TNode urem = fact[1];
301 TNode result = fact[0];
302 TNode divisor = urem[1];
303 Node result_ult_div = nm->mkNode(kind::BITVECTOR_ULT, result, divisor);
304 Node divisor_eq_0 =
305 nm->mkNode(kind::EQUAL, divisor, mkZero(getSize(divisor)));
306 Node split = nm->mkNode(
307 kind::OR, divisor_eq_0, nm->mkNode(kind::NOT, fact), result_ult_div);
308 lemma(split);
309 }
310 }
311 }
312
313 void TheoryBV::check(Effort e)
314 {
315 if (done() && e<Theory::EFFORT_FULL) {
316 return;
317 }
318
319 //last call : do reductions on extended bitvector functions
320 if (e == Theory::EFFORT_LAST_CALL) {
321 std::vector<Node> nred = getExtTheory()->getActive();
322 doExtfReductions(nred);
323 return;
324 }
325
326 TimerStat::CodeTimer checkTimer(d_checkTime);
327 Debug("bitvector") << "TheoryBV::check(" << e << ")" << std::endl;
328 TimerStat::CodeTimer codeTimer(d_statistics.d_solveTimer);
329 // we may be getting new assertions so the model cache may not be sound
330 d_invalidateModelCache.set(true);
331 // if we are using the eager solver
332 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
333 // this can only happen on an empty benchmark
334 if (!d_eagerSolver->isInitialized()) {
335 d_eagerSolver->initialize();
336 }
337 if (!Theory::fullEffort(e))
338 return;
339
340 std::vector<TNode> assertions;
341 while (!done()) {
342 TNode fact = get().assertion;
343 Assert (fact.getKind() == kind::BITVECTOR_EAGER_ATOM);
344 assertions.push_back(fact);
345 }
346 Assert (d_eagerSolver->hasAssertions(assertions));
347
348 bool ok = d_eagerSolver->checkSat();
349 if (!ok) {
350 if (assertions.size() == 1) {
351 d_out->conflict(assertions[0]);
352 return;
353 }
354 Node conflict = utils::mkAnd(assertions);
355 d_out->conflict(conflict);
356 return;
357 }
358 return;
359 }
360
361
362 if (Theory::fullEffort(e)) {
363 ++(d_statistics.d_numCallsToCheckFullEffort);
364 } else {
365 ++(d_statistics.d_numCallsToCheckStandardEffort);
366 }
367 // if we are already in conflict just return the conflict
368 if (inConflict()) {
369 sendConflict();
370 return;
371 }
372
373 while (!done()) {
374 TNode fact = get().assertion;
375
376 checkForLemma(fact);
377
378 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
379 d_subtheories[i]->assertFact(fact);
380 }
381 }
382
383 bool ok = true;
384 bool complete = false;
385 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
386 Assert (!inConflict());
387 ok = d_subtheories[i]->check(e);
388 complete = d_subtheories[i]->isComplete();
389
390 if (!ok) {
391 // if we are in a conflict no need to check with other theories
392 Assert (inConflict());
393 sendConflict();
394 return;
395 }
396 if (complete) {
397 // if the last subtheory was complete we stop
398 break;
399 }
400 }
401
402 //check extended functions
403 if (Theory::fullEffort(e)) {
404 //do inferences (adds external lemmas) TODO: this can be improved to add internal inferences
405 std::vector< Node > nred;
406 if( getExtTheory()->doInferences( 0, nred ) ){
407 return;
408 }
409 d_needsLastCallCheck = false;
410 if( !nred.empty() ){
411 //other inferences involving bv2nat, int2bv
412 if( options::bvAlgExtf() ){
413 if( doExtfInferences( nred ) ){
414 return;
415 }
416 }
417 if( !options::bvLazyReduceExtf() ){
418 if( doExtfReductions( nred ) ){
419 return;
420 }
421 }else{
422 d_needsLastCallCheck = true;
423 }
424 }
425 }
426 }
427
428 bool TheoryBV::doExtfInferences(std::vector<Node>& terms)
429 {
430 NodeManager* nm = NodeManager::currentNM();
431 bool sentLemma = false;
432 eq::EqualityEngine* ee = getEqualityEngine();
433 std::map<Node, Node> op_map;
434 for (unsigned j = 0; j < terms.size(); j++)
435 {
436 TNode n = terms[j];
437 Assert(n.getKind() == kind::BITVECTOR_TO_NAT
438 || n.getKind() == kind::INT_TO_BITVECTOR);
439 if (n.getKind() == kind::BITVECTOR_TO_NAT)
440 {
441 // range lemmas
442 if (d_extf_range_infer.find(n) == d_extf_range_infer.end())
443 {
444 d_extf_range_infer.insert(n);
445 unsigned bvs = n[0].getType().getBitVectorSize();
446 Node min = nm->mkConst(Rational(0));
447 Node max = nm->mkConst(Rational(Integer(1).multiplyByPow2(bvs)));
448 Node lem = nm->mkNode(kind::AND,
449 nm->mkNode(kind::GEQ, n, min),
450 nm->mkNode(kind::LT, n, max));
451 Trace("bv-extf-lemma")
452 << "BV extf lemma (range) : " << lem << std::endl;
453 d_out->lemma(lem);
454 sentLemma = true;
455 }
456 }
457 Node r = (ee && ee->hasTerm(n[0])) ? ee->getRepresentative(n[0]) : n[0];
458 op_map[r] = n;
459 }
460 for (unsigned j = 0; j < terms.size(); j++)
461 {
462 TNode n = terms[j];
463 Node r = (ee && ee->hasTerm(n[0])) ? ee->getRepresentative(n) : n;
464 std::map<Node, Node>::iterator it = op_map.find(r);
465 if (it != op_map.end())
466 {
467 Node parent = it->second;
468 // Node cterm = parent[0]==n ? parent : nm->mkNode( parent.getOperator(),
469 // n );
470 Node cterm = parent[0].eqNode(n);
471 Trace("bv-extf-lemma-debug")
472 << "BV extf collapse based on : " << cterm << std::endl;
473 if (d_extf_collapse_infer.find(cterm) == d_extf_collapse_infer.end())
474 {
475 d_extf_collapse_infer.insert(cterm);
476
477 Node t = n[0];
478 if (n.getKind() == kind::INT_TO_BITVECTOR)
479 {
480 Assert(t.getType().isInteger());
481 // congruent modulo 2^( bv width )
482 unsigned bvs = n.getType().getBitVectorSize();
483 Node coeff = nm->mkConst(Rational(Integer(1).multiplyByPow2(bvs)));
484 Node k = nm->mkSkolem(
485 "int_bv_cong", t.getType(), "for int2bv/bv2nat congruence");
486 t = nm->mkNode(kind::PLUS, t, nm->mkNode(kind::MULT, coeff, k));
487 }
488 Node lem = parent.eqNode(t);
489
490 if (parent[0] != n)
491 {
492 Assert(ee->areEqual(parent[0], n));
493 lem = nm->mkNode(kind::IMPLIES, parent[0].eqNode(n), lem);
494 }
495 Trace("bv-extf-lemma")
496 << "BV extf lemma (collapse) : " << lem << std::endl;
497 d_out->lemma(lem);
498 sentLemma = true;
499 }
500 }
501 }
502 return sentLemma;
503 }
504
505 bool TheoryBV::doExtfReductions( std::vector< Node >& terms ) {
506 std::vector< Node > nredr;
507 if( getExtTheory()->doReductions( 0, terms, nredr ) ){
508 return true;
509 }
510 Assert( nredr.empty() );
511 return false;
512 }
513
514 bool TheoryBV::needsCheckLastEffort() {
515 return d_needsLastCallCheck;
516 }
517 bool TheoryBV::collectModelInfo(TheoryModel* m)
518 {
519 Assert(!inConflict());
520 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
521 if (!d_eagerSolver->collectModelInfo(m, true))
522 {
523 return false;
524 }
525 }
526 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
527 if (d_subtheories[i]->isComplete()) {
528 return d_subtheories[i]->collectModelInfo(m, true);
529 }
530 }
531 return true;
532 }
533
534 Node TheoryBV::getModelValue(TNode var) {
535 Assert(!inConflict());
536 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
537 if (d_subtheories[i]->isComplete()) {
538 return d_subtheories[i]->getModelValue(var);
539 }
540 }
541 Unreachable();
542 }
543
544 void TheoryBV::propagate(Effort e) {
545 Debug("bitvector") << indent() << "TheoryBV::propagate()" << std::endl;
546 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
547 return;
548 }
549
550 if (inConflict()) {
551 return;
552 }
553
554 // go through stored propagations
555 bool ok = true;
556 for (; d_literalsToPropagateIndex < d_literalsToPropagate.size() && ok; d_literalsToPropagateIndex = d_literalsToPropagateIndex + 1) {
557 TNode literal = d_literalsToPropagate[d_literalsToPropagateIndex];
558 // temporary fix for incremental bit-blasting
559 if (d_valuation.isSatLiteral(literal)) {
560 Debug("bitvector::propagate") << "TheoryBV:: propagating " << literal <<"\n";
561 ok = d_out->propagate(literal);
562 }
563 }
564
565 if (!ok) {
566 Debug("bitvector::propagate") << indent() << "TheoryBV::propagate(): conflict from theory engine" << std::endl;
567 setConflict();
568 }
569 }
570
571
572 eq::EqualityEngine * TheoryBV::getEqualityEngine() {
573 CoreSolver* core = (CoreSolver*)d_subtheoryMap[SUB_CORE];
574 if( core ){
575 return core->getEqualityEngine();
576 }else{
577 return NULL;
578 }
579 }
580
581 bool TheoryBV::getCurrentSubstitution( int effort, std::vector< Node >& vars, std::vector< Node >& subs, std::map< Node, std::vector< Node > >& exp ) {
582 eq::EqualityEngine * ee = getEqualityEngine();
583 if( ee ){
584 //get the constant equivalence classes
585 bool retVal = false;
586 for( unsigned i=0; i<vars.size(); i++ ){
587 Node n = vars[i];
588 if( ee->hasTerm( n ) ){
589 Node nr = ee->getRepresentative( n );
590 if( nr.isConst() ){
591 subs.push_back( nr );
592 exp[n].push_back( n.eqNode( nr ) );
593 retVal = true;
594 }else{
595 subs.push_back( n );
596 }
597 }else{
598 subs.push_back( n );
599 }
600 }
601 //return true if the substitution is non-trivial
602 return retVal;
603 }
604 return false;
605 }
606
607 int TheoryBV::getReduction(int effort, Node n, Node& nr)
608 {
609 Trace("bv-ext") << "TheoryBV::checkExt : non-reduced : " << n << std::endl;
610 NodeManager* const nm = NodeManager::currentNM();
611 if (n.getKind() == kind::BITVECTOR_TO_NAT)
612 {
613 // taken from rewrite code
614 const unsigned size = utils::getSize(n[0]);
615 const Node z = nm->mkConst(Rational(0));
616 const Node bvone = utils::mkOne(1);
617 NodeBuilder<> result(kind::PLUS);
618 Integer i = 1;
619 for (unsigned bit = 0; bit < size; ++bit, i *= 2)
620 {
621 Node cond =
622 nm->mkNode(kind::EQUAL,
623 nm->mkNode(nm->mkConst(BitVectorExtract(bit, bit)), n[0]),
624 bvone);
625 result << nm->mkNode(kind::ITE, cond, nm->mkConst(Rational(i)), z);
626 }
627 nr = Node(result);
628 return -1;
629 }
630 else if (n.getKind() == kind::INT_TO_BITVECTOR)
631 {
632 // taken from rewrite code
633 const unsigned size = n.getOperator().getConst<IntToBitVector>().size;
634 const Node bvzero = utils::mkZero(1);
635 const Node bvone = utils::mkOne(1);
636 std::vector<Node> v;
637 Integer i = 2;
638 while (v.size() < size)
639 {
640 Node cond = nm->mkNode(
641 kind::GEQ,
642 nm->mkNode(kind::INTS_MODULUS_TOTAL, n[0], nm->mkConst(Rational(i))),
643 nm->mkConst(Rational(i, 2)));
644 cond = Rewriter::rewrite(cond);
645 v.push_back(nm->mkNode(kind::ITE, cond, bvone, bvzero));
646 i *= 2;
647 }
648 NodeBuilder<> result(kind::BITVECTOR_CONCAT);
649 result.append(v.rbegin(), v.rend());
650 nr = Node(result);
651 return -1;
652 }
653 return 0;
654 }
655
656 Theory::PPAssertStatus TheoryBV::ppAssert(TNode in,
657 SubstitutionMap& outSubstitutions)
658 {
659 switch (in.getKind())
660 {
661 case kind::EQUAL:
662 {
663 if (in[0].isVar() && !in[1].hasSubterm(in[0]))
664 {
665 ++(d_statistics.d_solveSubstitutions);
666 outSubstitutions.addSubstitution(in[0], in[1]);
667 return PP_ASSERT_STATUS_SOLVED;
668 }
669 if (in[1].isVar() && !in[0].hasSubterm(in[1]))
670 {
671 ++(d_statistics.d_solveSubstitutions);
672 outSubstitutions.addSubstitution(in[1], in[0]);
673 return PP_ASSERT_STATUS_SOLVED;
674 }
675 Node node = Rewriter::rewrite(in);
676 if ((node[0].getKind() == kind::BITVECTOR_EXTRACT && node[1].isConst())
677 || (node[1].getKind() == kind::BITVECTOR_EXTRACT
678 && node[0].isConst()))
679 {
680 Node extract = node[0].isConst() ? node[1] : node[0];
681 if (extract[0].getKind() == kind::VARIABLE)
682 {
683 Node c = node[0].isConst() ? node[0] : node[1];
684
685 unsigned high = utils::getExtractHigh(extract);
686 unsigned low = utils::getExtractLow(extract);
687 unsigned var_bitwidth = utils::getSize(extract[0]);
688 std::vector<Node> children;
689
690 if (low == 0)
691 {
692 Assert(high != var_bitwidth - 1);
693 unsigned skolem_size = var_bitwidth - high - 1;
694 Node skolem = utils::mkVar(skolem_size);
695 children.push_back(skolem);
696 children.push_back(c);
697 }
698 else if (high == var_bitwidth - 1)
699 {
700 unsigned skolem_size = low;
701 Node skolem = utils::mkVar(skolem_size);
702 children.push_back(c);
703 children.push_back(skolem);
704 }
705 else
706 {
707 unsigned skolem1_size = low;
708 unsigned skolem2_size = var_bitwidth - high - 1;
709 Node skolem1 = utils::mkVar(skolem1_size);
710 Node skolem2 = utils::mkVar(skolem2_size);
711 children.push_back(skolem2);
712 children.push_back(c);
713 children.push_back(skolem1);
714 }
715 Node concat = utils::mkConcat(children);
716 Assert(utils::getSize(concat) == utils::getSize(extract[0]));
717 outSubstitutions.addSubstitution(extract[0], concat);
718 return PP_ASSERT_STATUS_SOLVED;
719 }
720 }
721 }
722 break;
723 case kind::BITVECTOR_ULT:
724 case kind::BITVECTOR_SLT:
725 case kind::BITVECTOR_ULE:
726 case kind::BITVECTOR_SLE:
727
728 default:
729 // TODO other predicates
730 break;
731 }
732 return PP_ASSERT_STATUS_UNSOLVED;
733 }
734
735 Node TheoryBV::ppRewrite(TNode t)
736 {
737 Debug("bv-pp-rewrite") << "TheoryBV::ppRewrite " << t << "\n";
738 Node res = t;
739 if (RewriteRule<BitwiseEq>::applies(t)) {
740 Node result = RewriteRule<BitwiseEq>::run<false>(t);
741 res = Rewriter::rewrite(result);
742 } else if (d_isCoreTheory && t.getKind() == kind::EQUAL) {
743 std::vector<Node> equalities;
744 Slicer::splitEqualities(t, equalities);
745 res = utils::mkAnd(equalities);
746 } else if (RewriteRule<UltPlusOne>::applies(t)) {
747 Node result = RewriteRule<UltPlusOne>::run<false>(t);
748 res = Rewriter::rewrite(result);
749 } else if( res.getKind() == kind::EQUAL &&
750 ((res[0].getKind() == kind::BITVECTOR_PLUS &&
751 RewriteRule<ConcatToMult>::applies(res[1])) ||
752 (res[1].getKind() == kind::BITVECTOR_PLUS &&
753 RewriteRule<ConcatToMult>::applies(res[0])))) {
754 Node mult = RewriteRule<ConcatToMult>::applies(res[0])?
755 RewriteRule<ConcatToMult>::run<false>(res[0]) :
756 RewriteRule<ConcatToMult>::run<true>(res[1]);
757 Node factor = mult[0];
758 Node sum = RewriteRule<ConcatToMult>::applies(res[0])? res[1] : res[0];
759 Node new_eq = NodeManager::currentNM()->mkNode(kind::EQUAL, sum, mult);
760 Node rewr_eq = RewriteRule<SolveEq>::run<true>(new_eq);
761 if (rewr_eq[0].isVar() || rewr_eq[1].isVar()){
762 res = Rewriter::rewrite(rewr_eq);
763 } else {
764 res = t;
765 }
766 } else if (RewriteRule<SignExtendEqConst>::applies(t)) {
767 res = RewriteRule<SignExtendEqConst>::run<false>(t);
768 } else if (RewriteRule<ZeroExtendEqConst>::applies(t)) {
769 res = RewriteRule<ZeroExtendEqConst>::run<false>(t);
770 }
771 else if (RewriteRule<NormalizeEqPlusNeg>::applies(t))
772 {
773 res = RewriteRule<NormalizeEqPlusNeg>::run<false>(t);
774 }
775
776 // if(t.getKind() == kind::EQUAL &&
777 // ((t[0].getKind() == kind::BITVECTOR_MULT && t[1].getKind() ==
778 // kind::BITVECTOR_PLUS) ||
779 // (t[1].getKind() == kind::BITVECTOR_MULT && t[0].getKind() ==
780 // kind::BITVECTOR_PLUS))) {
781 // // if we have an equality between a multiplication and addition
782 // // try to express multiplication in terms of addition
783 // Node mult = t[0].getKind() == kind::BITVECTOR_MULT? t[0] : t[1];
784 // Node add = t[0].getKind() == kind::BITVECTOR_PLUS? t[0] : t[1];
785 // if (RewriteRule<MultSlice>::applies(mult)) {
786 // Node new_mult = RewriteRule<MultSlice>::run<false>(mult);
787 // Node new_eq =
788 // Rewriter::rewrite(NodeManager::currentNM()->mkNode(kind::EQUAL,
789 // new_mult, add));
790
791 // // the simplification can cause the formula to blow up
792 // // only apply if formula reduced
793 // if (d_subtheoryMap.find(SUB_BITBLAST) != d_subtheoryMap.end()) {
794 // BitblastSolver* bv = (BitblastSolver*)d_subtheoryMap[SUB_BITBLAST];
795 // uint64_t old_size = bv->computeAtomWeight(t);
796 // Assert (old_size);
797 // uint64_t new_size = bv->computeAtomWeight(new_eq);
798 // double ratio = ((double)new_size)/old_size;
799 // if (ratio <= 0.4) {
800 // ++(d_statistics.d_numMultSlice);
801 // return new_eq;
802 // }
803 // }
804
805 // if (new_eq.getKind() == kind::CONST_BOOLEAN) {
806 // ++(d_statistics.d_numMultSlice);
807 // return new_eq;
808 // }
809 // }
810 // }
811
812 if (options::bvAbstraction() && t.getType().isBoolean()) {
813 d_abstractionModule->addInputAtom(res);
814 }
815 Debug("bv-pp-rewrite") << "to " << res << "\n";
816 return res;
817 }
818
819 void TheoryBV::presolve() {
820 Debug("bitvector") << "TheoryBV::presolve" << endl;
821 }
822
823 static int prop_count = 0;
824
825 bool TheoryBV::storePropagation(TNode literal, SubTheory subtheory)
826 {
827 Debug("bitvector::propagate") << indent() << getSatContext()->getLevel() << " " << "TheoryBV::storePropagation(" << literal << ", " << subtheory << ")" << std::endl;
828 prop_count++;
829
830 // If already in conflict, no more propagation
831 if (d_conflict) {
832 Debug("bitvector::propagate") << indent() << "TheoryBV::storePropagation(" << literal << ", " << subtheory << "): already in conflict" << std::endl;
833 return false;
834 }
835
836 // If propagated already, just skip
837 PropagatedMap::const_iterator find = d_propagatedBy.find(literal);
838 if (find != d_propagatedBy.end()) {
839 return true;
840 } else {
841 bool polarity = literal.getKind() != kind::NOT;
842 Node negatedLiteral = polarity ? literal.notNode() : (Node) literal[0];
843 find = d_propagatedBy.find(negatedLiteral);
844 if (find != d_propagatedBy.end() && (*find).second != subtheory) {
845 // Safe to ignore this one, subtheory should produce a conflict
846 return true;
847 }
848
849 d_propagatedBy[literal] = subtheory;
850 }
851
852 // Propagate differs depending on the subtheory
853 // * bitblaster needs to be left alone until it's done, otherwise it doesn't know how to explain
854 // * equality engine can propagate eagerly
855 bool ok = true;
856 if (subtheory == SUB_CORE) {
857 d_out->propagate(literal);
858 if (!ok) {
859 setConflict();
860 }
861 } else {
862 d_literalsToPropagate.push_back(literal);
863 }
864 return ok;
865
866 }/* TheoryBV::propagate(TNode) */
867
868
869 void TheoryBV::explain(TNode literal, std::vector<TNode>& assumptions) {
870 Assert (wasPropagatedBySubtheory(literal));
871 SubTheory sub = getPropagatingSubtheory(literal);
872 d_subtheoryMap[sub]->explain(literal, assumptions);
873 }
874
875
876 Node TheoryBV::explain(TNode node) {
877 Debug("bitvector::explain") << "TheoryBV::explain(" << node << ")" << std::endl;
878 std::vector<TNode> assumptions;
879
880 // Ask for the explanation
881 explain(node, assumptions);
882 // this means that it is something true at level 0
883 if (assumptions.size() == 0) {
884 return utils::mkTrue();
885 }
886 // return the explanation
887 Node explanation = utils::mkAnd(assumptions);
888 Debug("bitvector::explain") << "TheoryBV::explain(" << node << ") => " << explanation << std::endl;
889 Debug("bitvector::explain") << "TheoryBV::explain done. \n";
890 return explanation;
891 }
892
893
894 void TheoryBV::addSharedTerm(TNode t) {
895 Debug("bitvector::sharing") << indent() << "TheoryBV::addSharedTerm(" << t << ")" << std::endl;
896 d_sharedTermsSet.insert(t);
897 if (options::bitvectorEqualitySolver()) {
898 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
899 d_subtheories[i]->addSharedTerm(t);
900 }
901 }
902 }
903
904
905 EqualityStatus TheoryBV::getEqualityStatus(TNode a, TNode b)
906 {
907 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER)
908 return EQUALITY_UNKNOWN;
909 Assert (options::bitblastMode() == theory::bv::BITBLAST_MODE_LAZY);
910 for (unsigned i = 0; i < d_subtheories.size(); ++i) {
911 EqualityStatus status = d_subtheories[i]->getEqualityStatus(a, b);
912 if (status != EQUALITY_UNKNOWN) {
913 return status;
914 }
915 }
916 return EQUALITY_UNKNOWN; ;
917 }
918
919
920 void TheoryBV::enableCoreTheorySlicer() {
921 Assert (!d_calledPreregister);
922 d_isCoreTheory = true;
923 if (d_subtheoryMap.find(SUB_CORE) != d_subtheoryMap.end()) {
924 CoreSolver* core = (CoreSolver*)d_subtheoryMap[SUB_CORE];
925 core->enableSlicer();
926 }
927 }
928
929
930 void TheoryBV::ppStaticLearn(TNode in, NodeBuilder<>& learned) {
931 if(d_staticLearnCache.find(in) != d_staticLearnCache.end()){
932 return;
933 }
934 d_staticLearnCache.insert(in);
935
936 if (in.getKind() == kind::EQUAL) {
937 if((in[0].getKind() == kind::BITVECTOR_PLUS && in[1].getKind() == kind::BITVECTOR_SHL) ||
938 (in[1].getKind() == kind::BITVECTOR_PLUS && in[0].getKind() == kind::BITVECTOR_SHL)) {
939 TNode p = in[0].getKind() == kind::BITVECTOR_PLUS ? in[0] : in[1];
940 TNode s = in[0].getKind() == kind::BITVECTOR_PLUS ? in[1] : in[0];
941
942 if(p.getNumChildren() == 2
943 && p[0].getKind() == kind::BITVECTOR_SHL
944 && p[1].getKind() == kind::BITVECTOR_SHL ){
945 unsigned size = utils::getSize(s);
946 Node one = utils::mkConst(size, 1u);
947 if(s[0] == one && p[0][0] == one && p[1][0] == one){
948 Node zero = utils::mkConst(size, 0u);
949 TNode b = p[0];
950 TNode c = p[1];
951 // (s : 1 << S) = (b : 1 << B) + (c : 1 << C)
952 Node b_eq_0 = b.eqNode(zero);
953 Node c_eq_0 = c.eqNode(zero);
954 Node b_eq_c = b.eqNode(c);
955
956 Node dis = NodeManager::currentNM()->mkNode(
957 kind::OR, b_eq_0, c_eq_0, b_eq_c);
958 Node imp = in.impNode(dis);
959 learned << imp;
960 }
961 }
962 }
963 }else if(in.getKind() == kind::AND){
964 for(size_t i = 0, N = in.getNumChildren(); i < N; ++i){
965 ppStaticLearn(in[i], learned);
966 }
967 }
968 }
969
970 bool TheoryBV::applyAbstraction(const std::vector<Node>& assertions, std::vector<Node>& new_assertions) {
971 bool changed = d_abstractionModule->applyAbstraction(assertions, new_assertions);
972 if (changed &&
973 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
974 options::bitvectorAig()) {
975 // disable AIG mode
976 AlwaysAssert (!d_eagerSolver->isInitialized());
977 d_eagerSolver->turnOffAig();
978 d_eagerSolver->initialize();
979 }
980 return changed;
981 }
982
983 void TheoryBV::setProofLog( BitVectorProof * bvp ) {
984 if( options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER ){
985 d_eagerSolver->setProofLog( bvp );
986 }else{
987 for( unsigned i=0; i< d_subtheories.size(); i++ ){
988 d_subtheories[i]->setProofLog( bvp );
989 }
990 }
991 }
992
993 void TheoryBV::setConflict(Node conflict)
994 {
995 if (options::bvAbstraction())
996 {
997 NodeManager* const nm = NodeManager::currentNM();
998 Node new_conflict = d_abstractionModule->simplifyConflict(conflict);
999
1000 std::vector<Node> lemmas;
1001 lemmas.push_back(new_conflict);
1002 d_abstractionModule->generalizeConflict(new_conflict, lemmas);
1003 for (unsigned i = 0; i < lemmas.size(); ++i)
1004 {
1005 lemma(nm->mkNode(kind::NOT, lemmas[i]));
1006 }
1007 }
1008 d_conflict = true;
1009 d_conflictNode = conflict;
1010 }
1011
1012 } /* namespace CVC4::theory::bv */
1013 } /* namespace CVC4::theory */
1014 } /* namespace CVC4 */