summaryrefslogtreecommitdiff
path: root/src/theory/subs_minimize.cpp
blob: c16fab4a9df32de43fdbfc5012644fb8cf72e9ed (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
/*********************                                                        */
/*! \file subs_minimize.cpp
 ** \verbatim
 ** Top contributors (to current version):
 **   Andrew Reynolds
 ** This file is part of the CVC4 project.
 ** Copyright (c) 2009-2019 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 Implementation of substitution minimization.
 **/

#include "theory/subs_minimize.h"

#include "expr/node_algorithm.h"
#include "theory/bv/theory_bv_utils.h"
#include "theory/rewriter.h"

using namespace std;
using namespace CVC4::kind;

namespace CVC4 {
namespace theory {

SubstitutionMinimize::SubstitutionMinimize() {}

bool SubstitutionMinimize::find(Node t,
                                Node target,
                                const std::vector<Node>& vars,
                                const std::vector<Node>& subs,
                                std::vector<Node>& reqVars)
{
  return findInternal(t, target, vars, subs, reqVars);
}

void getConjuncts(Node n, std::vector<Node>& conj)
{
  if (n.getKind() == AND)
  {
    for (const Node& nc : n)
    {
      conj.push_back(nc);
    }
  }
  else
  {
    conj.push_back(n);
  }
}

bool SubstitutionMinimize::findWithImplied(Node t,
                                           const std::vector<Node>& vars,
                                           const std::vector<Node>& subs,
                                           std::vector<Node>& reqVars,
                                           std::vector<Node>& impliedVars)
{
  NodeManager* nm = NodeManager::currentNM();
  Node truen = nm->mkConst(true);
  if (!findInternal(t, truen, vars, subs, reqVars))
  {
    return false;
  }
  if (reqVars.empty())
  {
    return true;
  }

  // map from conjuncts of t to whether they may be used to show an implied var
  std::vector<Node> tconj;
  getConjuncts(t, tconj);
  // map from conjuncts to their free symbols
  std::map<Node, std::unordered_set<Node, NodeHashFunction> > tcFv;

  std::unordered_set<Node, NodeHashFunction> reqSet;
  std::vector<Node> reqSubs;
  std::map<Node, unsigned> reqVarToIndex;
  for (const Node& v : reqVars)
  {
    reqVarToIndex[v] = reqSubs.size();
    const std::vector<Node>::const_iterator& it =
        std::find(vars.begin(), vars.end(), v);
    Assert(it != vars.end());
    ptrdiff_t pos = std::distance(vars.begin(), it);
    reqSubs.push_back(subs[pos]);
  }
  std::vector<Node> finalReqVars;
  for (const Node& v : vars)
  {
    if (reqVarToIndex.find(v) == reqVarToIndex.end())
    {
      // not a required variable, nothing to do
      continue;
    }
    unsigned vindex = reqVarToIndex[v];
    Node prev = reqSubs[vindex];
    // make identity substitution
    reqSubs[vindex] = v;
    bool madeImplied = false;
    // it is a required variable, can we make an implied variable?
    for (const Node& tc : tconj)
    {
      // ensure we've computed its free symbols
      std::map<Node, std::unordered_set<Node, NodeHashFunction> >::iterator
          itf = tcFv.find(tc);
      if (itf == tcFv.end())
      {
        expr::getSymbols(tc, tcFv[tc]);
        itf = tcFv.find(tc);
      }
      // only have a chance if contains v
      if (itf->second.find(v) == itf->second.end())
      {
        continue;
      }
      // try the current substitution
      Node tcs = tc.substitute(
          reqVars.begin(), reqVars.end(), reqSubs.begin(), reqSubs.end());
      Node tcsr = Rewriter::rewrite(tcs);
      std::vector<Node> tcsrConj;
      getConjuncts(tcsr, tcsrConj);
      for (const Node& tcc : tcsrConj)
      {
        if (tcc.getKind() == EQUAL)
        {
          for (unsigned r = 0; r < 2; r++)
          {
            if (tcc[r] == v)
            {
              Node res = tcc[1 - r];
              if (res.isConst())
              {
                Assert(res == prev);
                madeImplied = true;
                break;
              }
            }
          }
        }
        if (madeImplied)
        {
          break;
        }
      }
      if (madeImplied)
      {
        break;
      }
    }
    if (!madeImplied)
    {
      // revert the substitution
      reqSubs[vindex] = prev;
      finalReqVars.push_back(v);
    }
    else
    {
      impliedVars.push_back(v);
    }
  }
  reqVars.clear();
  reqVars.insert(reqVars.end(), finalReqVars.begin(), finalReqVars.end());

  return true;
}

bool SubstitutionMinimize::findInternal(Node n,
                                        Node target,
                                        const std::vector<Node>& vars,
                                        const std::vector<Node>& subs,
                                        std::vector<Node>& reqVars)
{
  Trace("subs-min") << "Substitution minimize : " << std::endl;
  Trace("subs-min") << "  substitution : " << vars << " -> " << subs
                    << std::endl;
  Trace("subs-min") << "  node : " << n << std::endl;
  Trace("subs-min") << "  target : " << target << std::endl;

  Trace("subs-min") << "--- Compute values for subterms..." << std::endl;
  // the value of each subterm in n under the substitution
  std::unordered_map<TNode, Node, TNodeHashFunction> value;
  std::unordered_map<TNode, Node, TNodeHashFunction>::iterator it;
  std::vector<TNode> visit;
  TNode cur;
  visit.push_back(n);
  do
  {
    cur = visit.back();
    visit.pop_back();
    it = value.find(cur);

    if (it == value.end())
    {
      if (cur.isVar())
      {
        const std::vector<Node>::const_iterator& it =
            std::find(vars.begin(), vars.end(), cur);
        if (it == vars.end())
        {
          value[cur] = cur;
        }
        else
        {
          ptrdiff_t pos = std::distance(vars.begin(), it);
          value[cur] = subs[pos];
        }
      }
      else
      {
        value[cur] = Node::null();
        visit.push_back(cur);
        if (cur.getKind() == APPLY_UF)
        {
          visit.push_back(cur.getOperator());
        }
        visit.insert(visit.end(), cur.begin(), cur.end());
      }
    }
    else if (it->second.isNull())
    {
      Node ret = cur;
      if (cur.getNumChildren() > 0)
      {
        std::vector<Node> children;
        NodeBuilder<> nb(cur.getKind());
        if (cur.getMetaKind() == kind::metakind::PARAMETERIZED)
        {
          if (cur.getKind() == APPLY_UF)
          {
            children.push_back(cur.getOperator());
          }
          else
          {
            nb << cur.getOperator();
          }
        }
        children.insert(children.end(), cur.begin(), cur.end());
        for (const Node& cn : children)
        {
          it = value.find(cn);
          Assert(it != value.end());
          Assert(!it->second.isNull());
          nb << it->second;
        }
        ret = nb.constructNode();
        ret = Rewriter::rewrite(ret);
      }
      value[cur] = ret;
    }
  } while (!visit.empty());
  Assert(value.find(n) != value.end());
  Assert(!value.find(n)->second.isNull());

  Trace("subs-min") << "... got " << value[n] << std::endl;
  if (value[n] != target)
  {
    Trace("subs-min") << "... not equal to target " << target << std::endl;
    return false;
  }

  Trace("subs-min") << "--- Compute relevant variables..." << std::endl;
  std::unordered_set<Node, NodeHashFunction> rlvFv;
  // only variables that occur in assertions are relevant

  visit.push_back(n);
  std::unordered_set<TNode, TNodeHashFunction> visited;
  std::unordered_set<TNode, TNodeHashFunction>::iterator itv;
  do
  {
    cur = visit.back();
    visit.pop_back();
    itv = visited.find(cur);
    if (itv == visited.end())
    {
      visited.insert(cur);
      it = value.find(cur);
      if (it->second == cur)
      {
        // if its value is the same as current, there is nothing to do
      }
      else if (cur.isVar())
      {
        // must include
        rlvFv.insert(cur);
      }
      else if (cur.getKind() == ITE)
      {
        // only recurse on relevant branch
        Node bval = value[cur[0]];
        Assert(!bval.isNull() && bval.isConst());
        unsigned cindex = bval.getConst<bool>() ? 1 : 2;
        visit.push_back(cur[0]);
        visit.push_back(cur[cindex]);
      }
      else if (cur.getNumChildren() > 0)
      {
        Kind ck = cur.getKind();
        bool alreadyJustified = false;

        // if the operator is an apply uf, check its value
        if (cur.getKind() == APPLY_UF)
        {
          Node op = cur.getOperator();
          it = value.find(op);
          Assert(it != value.end());
          TNode vop = it->second;
          if (vop.getKind() == LAMBDA)
          {
            visit.push_back(op);
            // do iterative partial evaluation on the body of the lambda
            Node curr = vop[1];
            for (unsigned i = 0, size = cur.getNumChildren(); i < size; i++)
            {
              it = value.find(cur[i]);
              Assert(it != value.end());
              Node scurr = curr.substitute(vop[0][i], it->second);
              // if the valuation of the i^th argument changes the
              // interpretation of the body of the lambda, then the i^th
              // argument is relevant to the substitution. Hence, we add
              // i to visit, and update curr below.
              if (scurr != curr)
              {
                curr = Rewriter::rewrite(scurr);
                visit.push_back(cur[i]);
              }
            }
            alreadyJustified = true;
          }
        }
        if (!alreadyJustified)
        {
          // a subset of the arguments of cur that fully justify the evaluation
          std::vector<unsigned> justifyArgs;
          if (cur.getNumChildren() > 1)
          {
            for (unsigned i = 0, size = cur.getNumChildren(); i < size; i++)
            {
              Node cn = cur[i];
              it = value.find(cn);
              Assert(it != value.end());
              Assert(!it->second.isNull());
              if (isSingularArg(it->second, ck, i))
              {
                // have we seen this argument already? if so, we are done
                if (visited.find(cn) != visited.end())
                {
                  alreadyJustified = true;
                  break;
                }
                justifyArgs.push_back(i);
              }
            }
          }
          // we need to recurse on at most one child
          if (!alreadyJustified && !justifyArgs.empty())
          {
            unsigned sindex = justifyArgs[0];
            // could choose a best index, for now, we just take the first
            visit.push_back(cur[sindex]);
            alreadyJustified = true;
          }
        }
        if (!alreadyJustified)
        {
          // must recurse on all arguments, including operator
          if (cur.getKind() == APPLY_UF)
          {
            visit.push_back(cur.getOperator());
          }
          for (const Node& cn : cur)
          {
            visit.push_back(cn);
          }
        }
      }
    }
  } while (!visit.empty());

  for (const Node& v : rlvFv)
  {
    Assert(std::find(vars.begin(), vars.end(), v) != vars.end());
    reqVars.push_back(v);
  }

  Trace("subs-min") << "... requires " << reqVars.size() << "/" << vars.size()
                    << " : " << reqVars << std::endl;

  return true;
}

bool SubstitutionMinimize::isSingularArg(Node n, Kind k, unsigned arg)
{
  // Notice that this function is hardcoded. We could compute this function
  // in a theory-independent way using partial evaluation. However, we
  // prefer performance to generality here.

  // TODO: a variant of this code is implemented in quantifiers::TermUtil.
  // These implementations should be merged (see #1216).
  if (!n.isConst())
  {
    return false;
  }
  if (k == AND)
  {
    return !n.getConst<bool>();
  }
  else if (k == OR)
  {
    return n.getConst<bool>();
  }
  else if (k == IMPLIES)
  {
    return arg == (n.getConst<bool>() ? 1 : 0);
  }
  if (k == MULT
      || (arg == 0
          && (k == DIVISION_TOTAL || k == INTS_DIVISION_TOTAL
              || k == INTS_MODULUS_TOTAL))
      || (arg == 2 && k == STRING_SUBSTR))
  {
    // zero
    if (n.getConst<Rational>().sgn() == 0)
    {
      return true;
    }
  }
  if (k == BITVECTOR_AND || k == BITVECTOR_MULT || k == BITVECTOR_UDIV_TOTAL
      || k == BITVECTOR_UREM_TOTAL
      || (arg == 0
          && (k == BITVECTOR_SHL || k == BITVECTOR_LSHR
              || k == BITVECTOR_ASHR)))
  {
    if (bv::utils::isZero(n))
    {
      return true;
    }
  }
  if (k == BITVECTOR_OR)
  {
    // bit-vector ones
    if (bv::utils::isOnes(n))
    {
      return true;
    }
  }

  if ((arg == 1 && k == STRING_STRCTN) || (arg == 0 && k == STRING_SUBSTR))
  {
    // empty string
    if (n.getConst<String>().size() == 0)
    {
      return true;
    }
  }
  if ((arg != 0 && k == STRING_SUBSTR) || (arg == 2 && k == STRING_STRIDOF))
  {
    // negative integer
    if (n.getConst<Rational>().sgn() < 0)
    {
      return true;
    }
  }
  return false;
}

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