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