z3-src 501.0.1

Source distribution of the Z3 SMT solver, for use as a build dependency
Documentation
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
/*++
Copyright (c) 2012 Microsoft Corporation

Module Name:

    sls_engine.cpp

Abstract:

    A Stochastic Local Search (SLS) engine

Author:

    Christoph (cwinter) 2014-03-19

Notes:

--*/
#include<float.h> // Need DBL_MAX

#include "util/map.h"
#include "ast/ast_smt2_pp.h"
#include "ast/ast_pp.h"
#include "ast/rewriter/var_subst.h"
#include "model/model_pp.h"
#include "util/luby.h"

#include "params/sls_params.hpp"
#include "ast/sls/sls_bv_engine.h"


sls_engine::sls_engine(ast_manager & m, params_ref const & p) :
    m_manager(m),    
    m_powers(m_mpz_manager),
    m_zero(m_mpz_manager.mk_z(0)),
    m_one(m_mpz_manager.mk_z(1)),
    m_two(m_mpz_manager.mk_z(2)),
    m_bv_util(m),
    m_tracker(m, m_bv_util, m_mpz_manager, m_powers),
    m_evaluator(m, m_bv_util, m_tracker, m_mpz_manager, m_powers)
{
    updt_params(p);
    m_tracker.updt_params(p);
}

sls_engine::~sls_engine() {
    m_mpz_manager.del(m_zero);
    m_mpz_manager.del(m_one);
    m_mpz_manager.del(m_two);
}

void sls_engine::updt_params(params_ref const & _p) {
    sls_params p(_p);
    m_max_restarts = p.max_restarts();
    m_tracker.set_random_seed(p.random_seed());
    m_walksat = p.walksat();
    m_walksat_repick = p.walksat_repick();
    m_paws_sp = p.paws_sp();
    m_paws = m_paws_sp < 1024;
    m_wp = p.wp();
    m_vns_mc = p.vns_mc();
    m_vns_repick = p.vns_repick();

    m_restart_base = p.restart_base();
    m_restart_next = m_restart_base;
    m_restart_init = p.restart_init();

    m_early_prune = p.early_prune();
    m_random_offset = p.random_offset();
    m_rescore = p.rescore();

    // Andreas: Would cause trouble because repick requires an assertion being picked before which is not the case in GSAT.
    if (m_walksat_repick && !m_walksat)
        NOT_IMPLEMENTED_YET();
    if (m_vns_repick && !m_walksat)
        NOT_IMPLEMENTED_YET();
}



bool sls_engine::full_eval(model & mdl) {
    model::scoped_model_completion _scm(mdl, true);
    for (expr* a : m_assertions) {
        if (!m_manager.inc())
            return false;
        if (!mdl.is_true(a)) {
            TRACE(sls, tout << "Evaluation: false\n";);
            return false;
        }
    }    
    return true;
}

double sls_engine::top_score() {
    double top_sum = 0.0;
    for (expr* e : m_assertions) {
        top_sum += m_tracker.get_score(e);
    }
    TRACE(sls_top, tout << "Score distribution:";
          for (expr* e : m_assertions) 
              tout << " " << m_tracker.get_score(e);
          tout << " AVG: " << top_sum / (double)m_assertions.size() << std::endl;);

    m_tracker.set_top_sum(top_sum);

    return top_sum;
}

double sls_engine::rescore() {
    m_evaluator.update_all();
    m_stats.m_full_evals++;
    return top_score();
}

double sls_engine::serious_score(func_decl * fd, const mpz & new_value) {
    m_evaluator.serious_update(fd, new_value);
    m_stats.m_incr_evals++;
    return m_tracker.get_top_sum();
}

double sls_engine::incremental_score(func_decl * fd, const mpz & new_value) {
    m_evaluator.update(fd, new_value);
    m_stats.m_incr_evals++;
    return m_tracker.get_top_sum();
}

double sls_engine::incremental_score_prune(func_decl * fd, const mpz & new_value) {
    m_stats.m_incr_evals++;
    if (m_evaluator.update_prune(fd, new_value))
        return m_tracker.get_top_sum();
    else
        return -DBL_MAX;
}

// checks whether the score outcome of a given move is better than the previous score
bool sls_engine::what_if(
    func_decl * fd, 
    const unsigned & fd_inx, 
    const mpz & temp,
    double & best_score, 
    unsigned & best_const, 
    mpz & best_value) {

#ifdef Z3DEBUG
    mpz old_value;
    m_mpz_manager.set(old_value, m_tracker.get_value(fd));
#endif

    double r;
    if (m_early_prune)
        r = incremental_score_prune(fd, temp);
    else
        r = incremental_score(fd, temp);
#ifdef Z3DEBUG
    TRACE(sls_whatif, tout << "WHAT IF " << fd->get_name() << " WERE " << m_mpz_manager.to_string(temp) <<
            " --> " << r << std::endl;);

    m_mpz_manager.del(old_value);
#endif

    // Andreas: Had this idea on my last day. Maybe we could add a noise here similar to the one that worked so well for ucb assertion selection.
    // r += 0.0001 * m_tracker.get_random_uint(8);

    // Andreas: For some reason it is important to use > here instead of >=. Probably related to preferring the LSB.
    if (r > best_score) {
        best_score = r;
        best_const = fd_inx;
        m_mpz_manager.set(best_value, temp);
        return true;
    }

    return false;
}

void sls_engine::mk_add(unsigned bv_sz, const mpz & old_value, mpz & add_value, mpz & result) {
    mpz temp, mask, mask2;
    m_mpz_manager.add(old_value, add_value, temp);
    m_mpz_manager.set(mask, m_powers(bv_sz));
    m_mpz_manager.bitwise_not(bv_sz, mask, mask2);
    m_mpz_manager.bitwise_and(temp, mask2, result);
    m_mpz_manager.del(temp);
    m_mpz_manager.del(mask);
    m_mpz_manager.del(mask2);

}

void sls_engine::mk_inc(unsigned bv_sz, const mpz & old_value, mpz & incremented) {
    unsigned shift;
    m_mpz_manager.add(old_value, m_one, incremented);
    if (m_mpz_manager.is_power_of_two(incremented, shift) && shift == bv_sz)
        m_mpz_manager.set(incremented, m_zero);
}

void sls_engine::mk_dec(unsigned bv_sz, const mpz & old_value, mpz & decremented) {
    if (m_mpz_manager.is_zero(old_value)) {
        m_mpz_manager.set(decremented, m_powers(bv_sz));
        m_mpz_manager.dec(decremented);
    }
    else
        m_mpz_manager.sub(old_value, m_one, decremented);
}

void sls_engine::mk_inv(unsigned bv_sz, const mpz & old_value, mpz & inverted) {
    m_mpz_manager.bitwise_not(bv_sz, old_value, inverted);
}

void sls_engine::mk_flip(sort * s, const mpz & old_value, unsigned bit, mpz & flipped) {
    m_mpz_manager.set(flipped, m_zero);

    if (m_bv_util.is_bv_sort(s)) {
        mpz mask;
        m_mpz_manager.set(mask, m_powers(bit));
        m_mpz_manager.bitwise_xor(old_value, mask, flipped);
        m_mpz_manager.del(mask);
    }
    else if (m_manager.is_bool(s))
        m_mpz_manager.set(flipped, (m_mpz_manager.is_zero(old_value)) ? m_one : m_zero);
    else
        NOT_IMPLEMENTED_YET();
}

void sls_engine::mk_random_move(ptr_vector<func_decl> & unsat_constants)
{
    unsigned rnd_mv = 0;
    unsigned ucc = unsat_constants.size();
    unsigned rc = (m_tracker.get_random_uint((ucc < 16) ? 4 : (ucc < 256) ? 8 : (ucc < 4096) ? 12 : (ucc < 65536) ? 16 : 32)) % ucc;
    func_decl * fd = unsat_constants[rc];

    mpz new_value;

    sort * srt = fd->get_range();
    if (m_manager.is_bool(srt))
        m_mpz_manager.set(new_value, (m_mpz_manager.is_zero(m_tracker.get_value(fd))) ? m_one : m_zero);
    else
    {
        if (m_mpz_manager.is_one(m_tracker.get_random_bool())) rnd_mv = 2;
        if (m_mpz_manager.is_one(m_tracker.get_random_bool())) rnd_mv++;

        // Andreas: The other option would be to scale the probability for flips according to the bit-width.
        /* unsigned bv_sz2 = m_bv_util.get_bv_size(srt);
        rnd_mv = m_tracker.get_random_uint(16) % (bv_sz2 + 3);
        if (rnd_mv > 3) rnd_mv = 0; */

        move_type mt = (move_type)rnd_mv;

        // Andreas: Christoph claimed inversion doesn't make sense, let's do a flip instead. Is this really true?
        if (mt == MV_INV) mt = MV_FLIP;
        unsigned bit = 0;

        switch (mt)
        {
        case MV_FLIP: {
            unsigned bv_sz = m_bv_util.get_bv_size(srt);
            bit = (m_tracker.get_random_uint((bv_sz < 16) ? 4 : (bv_sz < 256) ? 8 : (bv_sz < 4096) ? 12 : (bv_sz < 65536) ? 16 : 32)) % bv_sz;
            mk_flip(fd->get_range(), m_tracker.get_value(fd), bit, new_value);
            break;
        }
        case MV_INC:
            mk_inc(m_bv_util.get_bv_size(fd->get_range()), m_tracker.get_value(fd), new_value);
            break;
        case MV_DEC:
            mk_dec(m_bv_util.get_bv_size(fd->get_range()), m_tracker.get_value(fd), new_value);
            break;
        case MV_INV:
            mk_inv(m_bv_util.get_bv_size(fd->get_range()), m_tracker.get_value(fd), new_value);
            break;
        }

        TRACE(sls, tout << "Randomization candidates: ";
        for (unsigned i = 0; i < unsat_constants.size(); ++i)
            tout << unsat_constants[i]->get_name() << ", ";
        tout << std::endl;
        tout << "Random move: ";
        switch (mt) {
        case MV_FLIP: tout << "Flip #" << bit << " in " << fd->get_name() << std::endl; break;
        case MV_INC: tout << "+1 for " << fd->get_name() << std::endl; break;
        case MV_DEC: tout << "-1 for " << fd->get_name() << std::endl; break;
        case MV_INV: tout << "NEG for " << fd->get_name() << std::endl; break;
        }
        tout << "Locally randomized model: " << std::endl; m_tracker.show_model(tout););
    }

    m_evaluator.serious_update(fd, new_value);
    m_mpz_manager.del(new_value);
}

// finds the move that increased score the most. returns best_const = -1, if no increasing move exists.
double sls_engine::find_best_move(
    ptr_vector<func_decl> & to_evaluate, 
    double score,
    unsigned & best_const, 
    mpz & best_value, 
    unsigned & new_bit, 
    move_type & move) 
{
    mpz old_value, temp;
    unsigned bv_sz;
    double new_score = score;

    // Andreas: Introducting a bit of randomization by using a random offset and a random direction to go through the candidate list.
    unsigned sz = to_evaluate.size();
    unsigned offset = (m_random_offset) ? m_tracker.get_random_uint(16) % sz : 0;
    for (unsigned j = 0; j < sz; ++j) {
        unsigned i = j + offset;
        if (i >= sz) i -= sz;
    //for (unsigned i = 0; i < to_evaluate.size(); ++i) {
        func_decl * fd = to_evaluate[i];
        sort * srt = fd->get_range();
        bv_sz = (m_manager.is_bool(srt)) ? 1 : m_bv_util.get_bv_size(srt);
        m_mpz_manager.set(old_value, m_tracker.get_value(fd));

        // first try to flip every bit
        for (unsigned j = 0; j < bv_sz; ++j) {
            // What would happen if we flipped bit #i ?                
            mk_flip(srt, old_value, j, temp);

            if (what_if(fd, i, temp, new_score, best_const, best_value)) {
                new_bit = j;
                move = MV_FLIP;
            }
        }

        if (m_bv_util.is_bv_sort(srt) && bv_sz > 1) {
            if (!m_mpz_manager.is_even(old_value)) {
                // for odd values, try +1
                mk_inc(bv_sz, old_value, temp);
                if (what_if(fd, i, temp, new_score, best_const, best_value))
                    move = MV_INC;
            }
            else {
                // for even values, try -1
                mk_dec(bv_sz, old_value, temp);
                if (what_if(fd, i, temp, new_score, best_const, best_value))
                    move = MV_DEC;
            }
            // try inverting
            mk_inv(bv_sz, old_value, temp);
            if (what_if(fd, i, temp, new_score, best_const, best_value))
                move = MV_INV;
        }
        // reset to what it was before
        incremental_score(fd, old_value);
    }

    m_mpz_manager.del(old_value);
    m_mpz_manager.del(temp);

    return new_score;
}

// finds the move that increased score the most. returns best_const = -1, if no increasing move exists.
double sls_engine::find_best_move_mc(ptr_vector<func_decl> & to_evaluate, double score,
                        unsigned & best_const, mpz & best_value) {
    mpz old_value, temp, temp2;
    unsigned bv_sz;
    double new_score = score;

    // Andreas: Introducting a bit of randomization by using a random offset and a random direction to go through the candidate list.
    unsigned sz = to_evaluate.size();
    unsigned offset = (m_random_offset) ? m_tracker.get_random_uint(16) % sz : 0;
    for (unsigned j = 0; j < sz; ++j) {
        unsigned i = j + offset;
        if (i >= sz) i -= sz;
    //for (unsigned i = 0; i < to_evaluate.size(); ++i) {
        func_decl * fd = to_evaluate[i];
        sort * srt = fd->get_range();
        bv_sz = (m_manager.is_bool(srt)) ? 1 : m_bv_util.get_bv_size(srt);
        m_mpz_manager.set(old_value, m_tracker.get_value(fd));

        if (m_bv_util.is_bv_sort(srt) && bv_sz > 2) {
            for (unsigned j = 0; j < bv_sz; ++j) {
                mk_flip(srt, old_value, j, temp);
                for (unsigned l = 0; l < m_vns_mc && l < bv_sz / 2; ++l)
                {
                    unsigned k = m_tracker.get_random_uint(16) % bv_sz;
                    while (k == j)
                        k = m_tracker.get_random_uint(16) % bv_sz;
                    mk_flip(srt, temp, k, temp2);
                    what_if(fd, i, temp2, new_score, best_const, best_value);
                }
            }
        }
        // reset to what it was before
        incremental_score(fd, old_value);
    }

    m_mpz_manager.del(old_value);
    m_mpz_manager.del(temp);
    m_mpz_manager.del(temp2);

    return new_score;
}

// main search loop
lbool sls_engine::search() {
    lbool res = l_undef;
    double score = 0.0;
    unsigned new_const = (unsigned)-1, new_bit;
    mpz new_value;
    move_type move;

    score = rescore();

    while (check_restart(m_stats.m_moves)) {
        if (!m_manager.inc())
            return l_undef;
        m_stats.m_moves++;

        // Andreas: Every base restart interval ...
        if (m_stats.m_moves % m_restart_base == 0)
        {
            // ... potentially smooth the touched counters ...
            m_tracker.ucb_forget(m_assertions);
            // ... or normalize the top-level score.
            if (m_rescore) score = rescore();
        }

        // get candidate variables
        ptr_vector<func_decl> & to_evaluate = m_tracker.get_unsat_constants(m_assertions);
        
        if (to_evaluate.empty())
        {
            res = l_true;
            goto bailout;
        }

        // random walk with probability wp / 1024
        if (m_wp && m_tracker.get_random_uint(10) < m_wp)
        {
            mk_random_move(to_evaluate);
            score = m_tracker.get_top_sum();
            continue;
        }

        new_const = (unsigned)-1;

        // find best increasing move
        score = find_best_move(to_evaluate, score, new_const, new_value, new_bit, move);

        // use Monte Carlo 2-bit-flip sampling if no increasing move was found previously
        if (m_vns_mc && (new_const == static_cast<unsigned>(-1)))
            score = find_best_move_mc(to_evaluate, score, new_const, new_value);
   
        // repick assertion if no increasing move was found previously
        if (m_vns_repick && (new_const == static_cast<unsigned>(-1)))
        {
            expr * q = m_tracker.get_new_unsat_assertion(m_assertions);
            // only apply if another unsatisfied assertion actually exists
            if (q)
            {
                ptr_vector<func_decl> & to_evaluate2 = m_tracker.get_unsat_constants_walksat(q);
                find_best_move(to_evaluate2, score, new_const, new_value, new_bit, move);

                if (new_const != static_cast<unsigned>(-1)) {
                    func_decl * fd = to_evaluate2[new_const];
                    score = serious_score(fd, new_value);
                    continue;
                }
            }
        }

        // randomize if no increasing move was found
        if (new_const == static_cast<unsigned>(-1)) {
            if (m_walksat_repick)
                m_evaluator.randomize_local(m_assertions);
            else
                m_evaluator.randomize_local(to_evaluate);

            score = m_tracker.get_top_sum();

            // update assertion weights if a weighting is enabled (sp < 1024)
            if (m_paws)
            {
                for (auto q : m_assertions) {
                    // smooth weights with probability sp / 1024
                    if (m_tracker.get_random_uint(10) < m_paws_sp)
                    {
                        if (m_mpz_manager.eq(m_tracker.get_value(q), m_one))
                            m_tracker.decrease_weight(q);
                    }
                    // increase weights otherwise
                    else
                    {
                        if (m_mpz_manager.eq(m_tracker.get_value(q), m_zero))
                            m_tracker.increase_weight(q);
                    }
                }                  
            }
        }
        // otherwise, apply most increasing move
        else {
            func_decl * fd = to_evaluate[new_const];
            score = serious_score(fd, new_value);
        }
    }

bailout:
    m_mpz_manager.del(new_value);

    return res;
}


lbool sls_engine::operator()() {    
    m_tracker.initialize(m_assertions);
    m_tracker.reset(m_assertions);
    if (m_restart_init)
        m_tracker.randomize(m_assertions);

    return search_loop();
}


lbool sls_engine::search_loop() {

    lbool res = l_undef;

    do {
        if (!m_manager.inc())
            return l_undef;

        // report_tactic_progress("Searching... restarts left:", m_max_restarts - m_stats.m_restarts);
        res = search();

        if (res == l_undef)
        {
            if (m_restart_init)
                m_tracker.randomize(m_assertions);
            else
                m_tracker.reset(m_assertions);
        }
    } while (res != l_true && m_stats.m_restarts++ < m_max_restarts);

    verbose_stream() << "(restarts: " << m_stats.m_restarts << " flips: " << m_stats.m_moves << " fps: " << (m_stats.m_moves / m_stats.m_stopwatch.get_current_seconds()) << ")" << std::endl;
    return res;
}

/* Andreas: Needed for Armin's restart scheme if we don't want to use loops.
double sls_engine::get_restart_armin(unsigned cnt_restarts)
{
    unsigned outer_id = (unsigned)(0.5 + sqrt(0.25 + 2 * cnt_restarts));
    unsigned inner_id = cnt_restarts - (outer_id - 1) * outer_id / 2;
    return pow((double) _RESTART_CONST_ARMIN_, (int) inner_id + 1);
}    
*/

unsigned sls_engine::check_restart(unsigned curr_value)
{
    if (curr_value > m_restart_next)
    {
        /* Andreas: My own scheme (= 1) seems to work best. Other schemes are disabled so that we save one parameter.
        I leave the other versions as comments in case you want to try it again somewhen.
#if _RESTART_SCHEME_ == 5
        m_restart_next += (unsigned)(m_restart_base * pow(_RESTART_CONST_ARMIN_, m_stats.m_restarts));
#elif _RESTART_SCHEME_ == 4
        m_restart_next += (m_stats.m_restarts & (m_stats.m_restarts + 1)) ? m_restart_base : (m_restart_base * m_stats.m_restarts + 1);
#elif _RESTART_SCHEME_ == 3
        m_restart_next += (unsigned)get_restart_armin(m_stats.m_restarts + 1) * m_restart_base;
#elif _RESTART_SCHEME_ == 2
        m_restart_next += get_luby(m_stats.m_restarts + 1) * m_restart_base;
#elif _RESTART_SCHEME_ == 1
        if (m_stats.m_restarts & 1)
            m_restart_next += m_restart_base;
        else
            m_restart_next += (2 << (m_stats.m_restarts >> 1)) * m_restart_base;
#else
        m_restart_limit += m_restart_base;
#endif  */
        if (m_stats.m_restarts & 1)
            m_restart_next += m_restart_base;
        else
            m_restart_next += (2 << (m_stats.m_restarts >> 1)) * m_restart_base;
        return 0;
    }
    return 1;
}