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