summaryrefslogtreecommitdiff
path: root/src/theory/bv/bitblast/lazy_bitblaster.cpp
blob: 93c91719b7c332c4217ef0437fa72b725958c951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/*********************                                                        */
/*! \file lazy_bitblaster.cpp
 ** \verbatim
 ** Top contributors (to current version):
 **   Liana Hadarean, Aina Niemetz, Mathias Preiner
 ** This file is part of the CVC4 project.
 ** Copyright (c) 2009-2020 by the authors listed in the file AUTHORS
 ** in the top-level source directory) and their institutional affiliations.
 ** All rights reserved.  See the file COPYING in the top-level source
 ** directory for licensing information.\endverbatim
 **
 ** \brief Bitblaster for the lazy bv solver.
 **
 ** Bitblaster for the lazy bv solver.
 **/

#include "theory/bv/bitblast/lazy_bitblaster.h"

#include "cvc4_private.h"
#include "options/bv_options.h"
#include "prop/cnf_stream.h"
#include "prop/sat_solver.h"
#include "prop/sat_solver_factory.h"
#include "smt/smt_engine.h"
#include "smt/smt_statistics_registry.h"
#include "theory/bv/abstraction.h"
#include "theory/bv/bv_solver_lazy.h"
#include "theory/bv/theory_bv.h"
#include "theory/bv/theory_bv_utils.h"
#include "theory/rewriter.h"
#include "theory/theory_model.h"

namespace CVC4 {
namespace theory {
namespace bv {

namespace {

/* Determine the number of uncached nodes that a given node consists of.  */
uint64_t numNodes(TNode node, utils::NodeSet& seen)
{
  std::vector<TNode> stack;
  uint64_t res = 0;

  stack.push_back(node);
  while (!stack.empty())
  {
    Node n = stack.back();
    stack.pop_back();

    if (seen.find(n) != seen.end()) continue;

    res += 1;
    seen.insert(n);
    stack.insert(stack.end(), n.begin(), n.end());
  }
  return res;
}
}

TLazyBitblaster::TLazyBitblaster(context::Context* c,
                                 bv::BVSolverLazy* bv,
                                 const std::string name,
                                 bool emptyNotify)
    : TBitblaster<Node>(),
      d_bv(bv),
      d_ctx(c),
      d_nullRegistrar(new prop::NullRegistrar()),
      d_assertedAtoms(new (true) context::CDList<prop::SatLiteral>(c)),
      d_explanations(new (true) ExplanationMap(c)),
      d_variables(),
      d_bbAtoms(),
      d_abstraction(NULL),
      d_emptyNotify(emptyNotify),
      d_fullModelAssertionLevel(c, 0),
      d_name(name),
      d_statistics(name)
{
  d_satSolver.reset(
      prop::SatSolverFactory::createMinisat(c, smtStatisticsRegistry(), name));

  ResourceManager* rm = smt::currentResourceManager();
  d_cnfStream.reset(new prop::TseitinCnfStream(d_satSolver.get(),
                                               d_nullRegistrar.get(),
                                               d_nullContext.get(),
                                               nullptr,
                                               rm,
                                               false,
                                               "LazyBitblaster"));

  d_satSolverNotify.reset(
      d_emptyNotify
          ? (prop::BVSatSolverNotify*)new MinisatEmptyNotify()
          : (prop::BVSatSolverNotify*)new MinisatNotify(
                d_cnfStream.get(), bv, this));

  d_satSolver->setNotify(d_satSolverNotify.get());
}

void TLazyBitblaster::setAbstraction(AbstractionModule* abs) {
  d_abstraction = abs;
}

TLazyBitblaster::~TLazyBitblaster()
{
  d_assertedAtoms->deleteSelf();
  d_explanations->deleteSelf();
}


/**
 * Bitblasts the atom, assigns it a marker literal, adding it to the SAT solver
 * NOTE: duplicate clauses are not detected because of marker literal
 * @param node the atom to be bitblasted
 *
 */
void TLazyBitblaster::bbAtom(TNode node)
{
  NodeManager* nm = NodeManager::currentNM();
  node = node.getKind() == kind::NOT ? node[0] : node;

  if (hasBBAtom(node))
  {
    return;
  }

  // make sure it is marked as an atom
  addAtom(node);

  Debug("bitvector-bitblast") << "Bitblasting node " << node << "\n";
  ++d_statistics.d_numAtoms;

  /// if we are using bit-vector abstraction bit-blast the original
  /// interpretation
  if (options::bvAbstraction() && d_abstraction != NULL
      && d_abstraction->isAbstraction(node))
  {
    // node must be of the form P(args) = bv1
    Node expansion = Rewriter::rewrite(d_abstraction->getInterpretation(node));

    Node atom_bb;
    if (expansion.getKind() == kind::CONST_BOOLEAN)
    {
      atom_bb = expansion;
    }
    else
    {
      Assert(expansion.getKind() == kind::AND);
      std::vector<Node> atoms;
      for (unsigned i = 0; i < expansion.getNumChildren(); ++i)
      {
        Node normalized_i = Rewriter::rewrite(expansion[i]);
        Node atom_i =
            normalized_i.getKind() != kind::CONST_BOOLEAN
                ? Rewriter::rewrite(d_atomBBStrategies[normalized_i.getKind()](
                      normalized_i, this))
                : normalized_i;
        atoms.push_back(atom_i);
      }
      atom_bb = utils::mkAnd(atoms);
    }
    Assert(!atom_bb.isNull());
    Node atom_definition = nm->mkNode(kind::EQUAL, node, atom_bb);
    storeBBAtom(node, atom_bb);
    d_cnfStream->convertAndAssert(atom_definition, false, false);
    return;
  }

  // the bitblasted definition of the atom
  Node normalized = Rewriter::rewrite(node);
  Node atom_bb =
      normalized.getKind() != kind::CONST_BOOLEAN
          ? d_atomBBStrategies[normalized.getKind()](normalized, this)
          : normalized;

  atom_bb = Rewriter::rewrite(atom_bb);

  // asserting that the atom is true iff the definition holds
  Node atom_definition = nm->mkNode(kind::EQUAL, node, atom_bb);
  storeBBAtom(node, atom_bb);
  d_cnfStream->convertAndAssert(atom_definition, false, false);
}

void TLazyBitblaster::storeBBAtom(TNode atom, Node atom_bb) {
  d_bbAtoms.insert(atom);
}

void TLazyBitblaster::storeBBTerm(TNode node, const Bits& bits) {
  d_termCache.insert(std::make_pair(node, bits));
}


bool TLazyBitblaster::hasBBAtom(TNode atom) const {
  return d_bbAtoms.find(atom) != d_bbAtoms.end();
}


void TLazyBitblaster::makeVariable(TNode var, Bits& bits) {
  Assert(bits.size() == 0);
  for (unsigned i = 0; i < utils::getSize(var); ++i) {
    bits.push_back(utils::mkBitOf(var, i));
  }
  d_variables.insert(var);
}

uint64_t TLazyBitblaster::computeAtomWeight(TNode node, NodeSet& seen)
{
  node = node.getKind() == kind::NOT ? node[0] : node;
  if (!utils::isBitblastAtom(node)) { return 0; }
  Node atom_bb =
      Rewriter::rewrite(d_atomBBStrategies[node.getKind()](node, this));
  uint64_t size = numNodes(atom_bb, seen);
  return size;
}

// cnf conversion ensures the atom represents itself
Node TLazyBitblaster::getBBAtom(TNode node) const {
  return node;
}

void TLazyBitblaster::bbTerm(TNode node, Bits& bits) {

  if (hasBBTerm(node)) {
    getBBTerm(node, bits);
    return;
  }
  Assert(node.getType().isBitVector());

  d_bv->spendResource(ResourceManager::Resource::BitblastStep);
  Debug("bitvector-bitblast") << "Bitblasting term " << node <<"\n";
  ++d_statistics.d_numTerms;

  d_termBBStrategies[node.getKind()] (node, bits,this);

  Assert(bits.size() == utils::getSize(node));

  storeBBTerm(node, bits);
}
/// Public methods

void TLazyBitblaster::addAtom(TNode atom) {
  d_cnfStream->ensureLiteral(atom);
  prop::SatLiteral lit = d_cnfStream->getLiteral(atom);
  d_satSolver->addMarkerLiteral(lit);
}

void TLazyBitblaster::explain(TNode atom, std::vector<TNode>& explanation) {
  prop::SatLiteral lit = d_cnfStream->getLiteral(atom);

  ++(d_statistics.d_numExplainedPropagations);
  if (options::bvEagerExplanations()) {
    Assert(d_explanations->find(lit) != d_explanations->end());
    const std::vector<prop::SatLiteral>& literal_explanation = (*d_explanations)[lit].get();
    for (unsigned i = 0; i < literal_explanation.size(); ++i) {
      explanation.push_back(d_cnfStream->getNode(literal_explanation[i]));
    }
    return;
  }

  std::vector<prop::SatLiteral> literal_explanation;
  d_satSolver->explain(lit, literal_explanation);
  for (unsigned i = 0; i < literal_explanation.size(); ++i) {
    explanation.push_back(d_cnfStream->getNode(literal_explanation[i]));
  }
}


/*
 * Asserts the clauses corresponding to the atom to the Sat Solver
 * by turning on the marker literal (i.e. setting it to false)
 * @param node the atom to be asserted
 *
 */

bool TLazyBitblaster::propagate() {
  return d_satSolver->propagate() == prop::SAT_VALUE_TRUE;
}

bool TLazyBitblaster::assertToSat(TNode lit, bool propagate) {
  // strip the not
  TNode atom;
  if (lit.getKind() == kind::NOT) {
    atom = lit[0];
  } else {
    atom = lit;
  }
  Assert(utils::isBitblastAtom(atom));

  Assert(hasBBAtom(atom));

  prop::SatLiteral markerLit = d_cnfStream->getLiteral(atom);

  if(lit.getKind() == kind::NOT) {
    markerLit = ~markerLit;
  }

  Debug("bitvector-bb")
      << "BVSolverLazy::TLazyBitblaster::assertToSat asserting node: " << atom
      << "\n";
  Debug("bitvector-bb")
      << "BVSolverLazy::TLazyBitblaster::assertToSat with literal:   "
      << markerLit << "\n";

  prop::SatValue ret = d_satSolver->assertAssumption(markerLit, propagate);

  d_assertedAtoms->push_back(markerLit);

  return ret == prop::SAT_VALUE_TRUE || ret == prop::SAT_VALUE_UNKNOWN;
}

/**
 * Calls the solve method for the Sat Solver.
 * passing it the marker literals to be asserted
 *
 * @return true for sat, and false for unsat
 */

bool TLazyBitblaster::solve() {
  if (Trace.isOn("bitvector")) {
    Trace("bitvector") << "TLazyBitblaster::solve() asserted atoms ";
    context::CDList<prop::SatLiteral>::const_iterator it = d_assertedAtoms->begin();
    for (; it != d_assertedAtoms->end(); ++it) {
      Trace("bitvector") << "     " << d_cnfStream->getNode(*it) << "\n";
    }
  }
  Debug("bitvector") << "TLazyBitblaster::solve() asserted atoms " << d_assertedAtoms->size() <<"\n";
  d_fullModelAssertionLevel.set(d_bv->numAssertions());
  return prop::SAT_VALUE_TRUE == d_satSolver->solve();
}

prop::SatValue TLazyBitblaster::solveWithBudget(unsigned long budget) {
  if (Trace.isOn("bitvector")) {
    Trace("bitvector") << "TLazyBitblaster::solveWithBudget() asserted atoms ";
    context::CDList<prop::SatLiteral>::const_iterator it = d_assertedAtoms->begin();
    for (; it != d_assertedAtoms->end(); ++it) {
      Trace("bitvector") << "     " << d_cnfStream->getNode(*it) << "\n";
    }
  }
  Debug("bitvector") << "TLazyBitblaster::solveWithBudget() asserted atoms " << d_assertedAtoms->size() <<"\n";
  return d_satSolver->solve(budget);
}

void TLazyBitblaster::getConflict(std::vector<TNode>& conflict)
{
  NodeManager* nm = NodeManager::currentNM();
  prop::SatClause conflictClause;
  d_satSolver->getUnsatCore(conflictClause);

  for (unsigned i = 0; i < conflictClause.size(); i++)
  {
    prop::SatLiteral lit = conflictClause[i];
    TNode atom = d_cnfStream->getNode(lit);
    Node not_atom;
    if (atom.getKind() == kind::NOT)
    {
      not_atom = atom[0];
    }
    else
    {
      not_atom = nm->mkNode(kind::NOT, atom);
    }
    conflict.push_back(not_atom);
  }
}

TLazyBitblaster::Statistics::Statistics(const std::string& prefix) :
  d_numTermClauses(prefix + "::NumTermSatClauses", 0),
  d_numAtomClauses(prefix + "::NumAtomSatClauses", 0),
  d_numTerms(prefix + "::NumBitblastedTerms", 0),
  d_numAtoms(prefix + "::NumBitblastedAtoms", 0),
  d_numExplainedPropagations(prefix + "::NumExplainedPropagations", 0),
  d_numBitblastingPropagations(prefix + "::NumBitblastingPropagations", 0),
  d_bitblastTimer(prefix + "::BitblastTimer")
{
  smtStatisticsRegistry()->registerStat(&d_numTermClauses);
  smtStatisticsRegistry()->registerStat(&d_numAtomClauses);
  smtStatisticsRegistry()->registerStat(&d_numTerms);
  smtStatisticsRegistry()->registerStat(&d_numAtoms);
  smtStatisticsRegistry()->registerStat(&d_numExplainedPropagations);
  smtStatisticsRegistry()->registerStat(&d_numBitblastingPropagations);
  smtStatisticsRegistry()->registerStat(&d_bitblastTimer);
}


TLazyBitblaster::Statistics::~Statistics() {
  smtStatisticsRegistry()->unregisterStat(&d_numTermClauses);
  smtStatisticsRegistry()->unregisterStat(&d_numAtomClauses);
  smtStatisticsRegistry()->unregisterStat(&d_numTerms);
  smtStatisticsRegistry()->unregisterStat(&d_numAtoms);
  smtStatisticsRegistry()->unregisterStat(&d_numExplainedPropagations);
  smtStatisticsRegistry()->unregisterStat(&d_numBitblastingPropagations);
  smtStatisticsRegistry()->unregisterStat(&d_bitblastTimer);
}

bool TLazyBitblaster::MinisatNotify::notify(prop::SatLiteral lit) {
  if(options::bvEagerExplanations()) {
    // compute explanation
    if (d_lazyBB->d_explanations->find(lit) == d_lazyBB->d_explanations->end()) {
      std::vector<prop::SatLiteral> literal_explanation;
      d_lazyBB->d_satSolver->explain(lit, literal_explanation);
      d_lazyBB->d_explanations->insert(lit, literal_explanation);
    } else {
      // we propagated it at a lower level
      return true;
    }
  }
  ++(d_lazyBB->d_statistics.d_numBitblastingPropagations);
  TNode atom = d_cnf->getNode(lit);
  return d_bv->storePropagation(atom, SUB_BITBLAST);
}

void TLazyBitblaster::MinisatNotify::notify(prop::SatClause& clause) {
  if (clause.size() > 1) {
    NodeBuilder<> lemmab(kind::OR);
    for (unsigned i = 0; i < clause.size(); ++ i) {
      lemmab << d_cnf->getNode(clause[i]);
    }
    Node lemma = lemmab;
    d_bv->d_inferManager.lemma(lemma);
  } else {
    d_bv->d_inferManager.lemma(d_cnf->getNode(clause[0]));
  }
}

void TLazyBitblaster::MinisatNotify::spendResource(ResourceManager::Resource r)
{
  d_bv->spendResource(r);
}

void TLazyBitblaster::MinisatNotify::safePoint(ResourceManager::Resource r)
{
  d_bv->d_inferManager.safePoint(r);
}

EqualityStatus TLazyBitblaster::getEqualityStatus(TNode a, TNode b)
{
  int numAssertions = d_bv->numAssertions();
  bool has_full_model =
      numAssertions != 0 && d_fullModelAssertionLevel.get() == numAssertions;

  Debug("bv-equality-status")
      << "TLazyBitblaster::getEqualityStatus " << a << " = " << b << "\n";
  Debug("bv-equality-status")
      << "BVSatSolver has full model? " << has_full_model << "\n";

  // First check if it trivially rewrites to false/true
  Node a_eq_b =
      Rewriter::rewrite(NodeManager::currentNM()->mkNode(kind::EQUAL, a, b));

  if (a_eq_b == utils::mkFalse()) return theory::EQUALITY_FALSE;
  if (a_eq_b == utils::mkTrue()) return theory::EQUALITY_TRUE;

  if (!has_full_model)
  {
    return theory::EQUALITY_UNKNOWN;
  }

  // Check if cache is valid (invalidated in check and pops)
  if (d_bv->d_invalidateModelCache.get())
  {
    invalidateModelCache();
  }
  d_bv->d_invalidateModelCache.set(false);

  Node a_value = getTermModel(a, true);
  Node b_value = getTermModel(b, true);

  Assert(a_value.isConst() && b_value.isConst());

  if (a_value == b_value)
  {
    Debug("bv-equality-status") << "theory::EQUALITY_TRUE_IN_MODEL\n";
    return theory::EQUALITY_TRUE_IN_MODEL;
  }
  Debug("bv-equality-status") << "theory::EQUALITY_FALSE_IN_MODEL\n";
  return theory::EQUALITY_FALSE_IN_MODEL;
}

bool TLazyBitblaster::isSharedTerm(TNode node) {
  return d_bv->d_sharedTermsSet.find(node) != d_bv->d_sharedTermsSet.end();
}

bool TLazyBitblaster::hasValue(TNode a) {
  Assert(hasBBTerm(a));
  Bits bits;
  getBBTerm(a, bits);
  for (int i = bits.size() -1; i >= 0; --i) {
    prop::SatValue bit_value;
    if (d_cnfStream->hasLiteral(bits[i])) {
      prop::SatLiteral bit = d_cnfStream->getLiteral(bits[i]);
      bit_value = d_satSolver->value(bit);
      if (bit_value ==  prop::SAT_VALUE_UNKNOWN)
        return false;
    } else {
      return false;
    }
  }
  return true;
}
/**
 * Returns the value a is currently assigned to in the SAT solver
 * or null if the value is completely unassigned.
 *
 * @param a
 * @param fullModel whether to create a "full model," i.e., add
 * constants to equivalence classes that don't already have them
 *
 * @return
 */
Node TLazyBitblaster::getModelFromSatSolver(TNode a, bool fullModel) {
  if (!hasBBTerm(a)) {
    return fullModel? utils::mkConst(utils::getSize(a), 0u) : Node();
  }

  Bits bits;
  getBBTerm(a, bits);
  Integer value(0);
  for (int i = bits.size() -1; i >= 0; --i) {
    prop::SatValue bit_value;
    if (d_cnfStream->hasLiteral(bits[i])) {
      prop::SatLiteral bit = d_cnfStream->getLiteral(bits[i]);
      bit_value = d_satSolver->value(bit);
      Assert(bit_value != prop::SAT_VALUE_UNKNOWN);
    } else {
      if (!fullModel) return Node();
      // unconstrained bits default to false
      bit_value = prop::SAT_VALUE_FALSE;
    }
    Integer bit_int = bit_value == prop::SAT_VALUE_TRUE ? Integer(1) : Integer(0);
    value = value * 2 + bit_int;
  }
  return utils::mkConst(bits.size(), value);
}

bool TLazyBitblaster::collectModelValues(TheoryModel* m,
                                         const std::set<Node>& termSet)
{
  for (std::set<Node>::const_iterator it = termSet.begin(); it != termSet.end(); ++it) {
    TNode var = *it;
    // not actually a leaf of the bit-vector theory
    if (d_variables.find(var) == d_variables.end())
      continue;

    Assert(Theory::theoryOf(var) == theory::THEORY_BV || isSharedTerm(var));
    // only shared terms could not have been bit-blasted
    Assert(hasBBTerm(var) || isSharedTerm(var));

    Node const_value = getModelFromSatSolver(var, true);
    Assert(const_value.isNull() || const_value.isConst());
    if(const_value != Node()) {
      Debug("bitvector-model")
          << "TLazyBitblaster::collectModelValues (assert (= " << var << " "
          << const_value << "))\n";
      if (!m->assertEquality(var, const_value, true))
      {
        return false;
      }
    }
  }
  return true;
}

void TLazyBitblaster::clearSolver() {
  Assert(d_ctx->getLevel() == 0);
  d_assertedAtoms->deleteSelf();
  d_assertedAtoms = new(true) context::CDList<prop::SatLiteral>(d_ctx);
  d_explanations->deleteSelf();
  d_explanations = new(true) ExplanationMap(d_ctx);
  d_bbAtoms.clear();
  d_variables.clear();
  d_termCache.clear();

  invalidateModelCache();
  // recreate sat solver
  d_satSolver.reset(
      prop::SatSolverFactory::createMinisat(d_ctx, smtStatisticsRegistry()));
  ResourceManager* rm = smt::currentResourceManager();
  d_cnfStream.reset(new prop::TseitinCnfStream(d_satSolver.get(),
                                               d_nullRegistrar.get(),
                                               d_nullContext.get(),
                                               nullptr,
                                               rm));
  d_satSolverNotify.reset(
      d_emptyNotify
          ? (prop::BVSatSolverNotify*)new MinisatEmptyNotify()
          : (prop::BVSatSolverNotify*)new MinisatNotify(
                d_cnfStream.get(), d_bv, this));
  d_satSolver->setNotify(d_satSolverNotify.get());
}

}  // namespace bv
}  // namespace theory
}  // namespace CVC4
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback