about summary refs log tree commit diff homepage
path: root/lib/Solver/MetaSMTBuilder.h
blob: ffe4608de6aa5dcc021c9045c8e962334b64bc23 (plain) (blame)
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//===-- MetaSMTBuilder.h ----------------------------------------*- C++ -*-===//
//
//                     The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

/*
 * MetaSMTBuilder.h
 *
 *  Created on: 8 Aug 2012
 *      Author: hpalikar
 */

#ifndef KLEE_METASMTBUILDER_H
#define KLEE_METASMTBUILDER_H

#include "klee/Config/config.h"
#include "klee/Expr.h"
#include "klee/util/ExprPPrinter.h"
#include "klee/util/ArrayExprHash.h"
#include "klee/util/ExprHashMap.h"
#include "ConstantDivision.h"

#ifdef ENABLE_METASMT

#include "llvm/Support/CommandLine.h"

#include <metaSMT/frontend/Logic.hpp>
#include <metaSMT/frontend/QF_BV.hpp>
#include <metaSMT/frontend/Array.hpp>

using namespace metaSMT;
using namespace metaSMT::logic::QF_BV;

#define DIRECT_CONTEXT

namespace {
llvm::cl::opt<bool> UseConstructHashMetaSMT(
    "use-construct-hash-metasmt",
    llvm::cl::desc("Use hash-consing during metaSMT query construction."),
    llvm::cl::init(true));
}

namespace klee {

typedef metaSMT::logic::Predicate<proto::terminal<
    metaSMT::logic::tag::true_tag>::type> const MetaSMTConstTrue;
typedef metaSMT::logic::Predicate<proto::terminal<
    metaSMT::logic::tag::false_tag>::type> const MetaSMTConstFalse;
typedef metaSMT::logic::Array::array MetaSMTArray;

template <typename SolverContext> class MetaSMTBuilder;

template <typename SolverContext>
class MetaSMTArrayExprHash
    : public ArrayExprHash<typename SolverContext::result_type> {

  friend class MetaSMTBuilder<SolverContext>;

public:
  MetaSMTArrayExprHash(){};
  virtual ~MetaSMTArrayExprHash(){};
};

template <typename SolverContext> class MetaSMTBuilder {
public:
  MetaSMTBuilder(SolverContext &solver, bool optimizeDivides)
      : _solver(solver), _optimizeDivides(optimizeDivides){};
  virtual ~MetaSMTBuilder(){};

  typename SolverContext::result_type construct(ref<Expr> e);

  typename SolverContext::result_type getInitialRead(const Array *root,
                                                     unsigned index);

  typename SolverContext::result_type getTrue() {
    return (evaluate(_solver, metaSMT::logic::True));
  }

  typename SolverContext::result_type getFalse() {
    return (evaluate(_solver, metaSMT::logic::False));
  }

  typename SolverContext::result_type bvOne(unsigned width) {
    return bvZExtConst(width, 1);
  }

  typename SolverContext::result_type bvZero(unsigned width) {
    return bvZExtConst(width, 0);
  }

  typename SolverContext::result_type bvMinusOne(unsigned width) {
    return bvSExtConst(width, (int64_t)-1);
  }

  typename SolverContext::result_type bvConst32(unsigned width,
                                                uint32_t value) {
    return (evaluate(_solver, bvuint(value, width)));
  }

  typename SolverContext::result_type bvConst64(unsigned width,
                                                uint64_t value) {
    return (evaluate(_solver, bvuint(value, width)));
  }

  typename SolverContext::result_type bvZExtConst(unsigned width,
                                                  uint64_t value);
  typename SolverContext::result_type bvSExtConst(unsigned width,
                                                  uint64_t value);

  // logical left and right shift (not arithmetic)
  typename SolverContext::result_type
  bvLeftShift(typename SolverContext::result_type expr, unsigned width,
              unsigned shift);
  typename SolverContext::result_type
  bvRightShift(typename SolverContext::result_type expr, unsigned width,
               unsigned shift);
  typename SolverContext::result_type
  bvVarLeftShift(typename SolverContext::result_type expr,
                 typename SolverContext::result_type shift, unsigned width);
  typename SolverContext::result_type
  bvVarRightShift(typename SolverContext::result_type expr,
                  typename SolverContext::result_type shift, unsigned width);
  typename SolverContext::result_type
  bvVarArithRightShift(typename SolverContext::result_type expr,
                       typename SolverContext::result_type shift,
                       unsigned width);

  typename SolverContext::result_type getArrayForUpdate(const Array *root,
                                                        const UpdateNode *un);
  typename SolverContext::result_type getInitialArray(const Array *root);
  MetaSMTArray buildArray(unsigned elem_width, unsigned index_width);

private:
  typedef ExprHashMap<std::pair<typename SolverContext::result_type, unsigned> >
      MetaSMTExprHashMap;
  typedef typename MetaSMTExprHashMap::iterator MetaSMTExprHashMapIter;
  typedef typename MetaSMTExprHashMap::const_iterator
      MetaSMTExprHashMapConstIter;

  SolverContext &_solver;
  bool _optimizeDivides;
  MetaSMTArrayExprHash<SolverContext> _arr_hash;
  MetaSMTExprHashMap _constructed;

  typename SolverContext::result_type constructActual(ref<Expr> e,
                                                      int *width_out);
  typename SolverContext::result_type construct(ref<Expr> e, int *width_out);

  typename SolverContext::result_type
  bvBoolExtract(typename SolverContext::result_type expr, int bit);
  typename SolverContext::result_type
  bvExtract(typename SolverContext::result_type expr, unsigned top,
            unsigned bottom);
  typename SolverContext::result_type
  eqExpr(typename SolverContext::result_type a,
         typename SolverContext::result_type b);

  typename SolverContext::result_type
  constructAShrByConstant(typename SolverContext::result_type expr,
                          unsigned width, unsigned shift,
                          typename SolverContext::result_type isSigned);
  typename SolverContext::result_type
  constructMulByConstant(typename SolverContext::result_type expr,
                         unsigned width, uint64_t x);
  typename SolverContext::result_type
  constructUDivByConstant(typename SolverContext::result_type expr_n,
                          unsigned width, uint64_t d);
  typename SolverContext::result_type
  constructSDivByConstant(typename SolverContext::result_type expr_n,
                          unsigned width, uint64_t d);
};

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::getArrayForUpdate(const Array *root,
                                                 const UpdateNode *un) {

  if (!un) {
    return (getInitialArray(root));
  } else {
    typename SolverContext::result_type un_expr;
    bool hashed = _arr_hash.lookupUpdateNodeExpr(un, un_expr);

    if (!hashed) {
      un_expr = evaluate(_solver,
                         metaSMT::logic::Array::store(
                             getArrayForUpdate(root, un->next),
                             construct(un->index, 0), construct(un->value, 0)));
      _arr_hash.hashUpdateNodeExpr(un, un_expr);
    }
    return (un_expr);
  }
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::getInitialArray(const Array *root) {
  assert(root);
  typename SolverContext::result_type array_expr;
  bool hashed = _arr_hash.lookupArrayExpr(root, array_expr);

  if (!hashed) {

    array_expr =
        evaluate(_solver, buildArray(root->getRange(), root->getDomain()));

    if (root->isConstantArray()) {
      for (unsigned i = 0, e = root->size; i != e; ++i) {
        typename SolverContext::result_type tmp = evaluate(
            _solver,
            metaSMT::logic::Array::store(
                array_expr,
                construct(ConstantExpr::alloc(i, root->getDomain()), 0),
                construct(root->constantValues[i], 0)));
        array_expr = tmp;
      }
    }
    _arr_hash.hashArrayExpr(root, array_expr);
  }

  return (array_expr);
}

template <typename SolverContext>
MetaSMTArray MetaSMTBuilder<SolverContext>::buildArray(unsigned elem_width,
                                                       unsigned index_width) {
  return (metaSMT::logic::Array::new_array(elem_width, index_width));
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::getInitialRead(const Array *root,
                                              unsigned index) {
  assert(root);
  assert(false);
  typename SolverContext::result_type array_exp = getInitialArray(root);
  typename SolverContext::result_type res =
      evaluate(_solver, metaSMT::logic::Array::select(
                            array_exp, bvuint(index, root->getDomain())));
  return (res);
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvZExtConst(unsigned width, uint64_t value) {

  typename SolverContext::result_type res;

  if (width <= 64) {
    res = bvConst64(width, value);
  } else {
    typename SolverContext::result_type expr = bvConst64(64, value);
    typename SolverContext::result_type zero = bvConst64(64, 0);

    for (width -= 64; width > 64; width -= 64) {
      expr = evaluate(_solver, concat(zero, expr));
    }
    res = evaluate(_solver, concat(bvConst64(width, 0), expr));
  }

  return (res);
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvSExtConst(unsigned width, uint64_t value) {

  typename SolverContext::result_type res;

  if (width <= 64) {
    res = bvConst64(width, value);
  } else {
    // ToDo Reconsider -- note differences in STP and metaSMT for sign_extend
    // arguments
    res = evaluate(_solver, sign_extend(width - 64, bvConst64(64, value)));
  }
  return (res);
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvBoolExtract(
    typename SolverContext::result_type expr, int bit) {
  return (evaluate(_solver,
                   metaSMT::logic::equal(extract(bit, bit, expr), bvOne(1))));
}

template <typename SolverContext>
typename SolverContext::result_type MetaSMTBuilder<SolverContext>::bvExtract(
    typename SolverContext::result_type expr, unsigned top, unsigned bottom) {
  return (evaluate(_solver, extract(top, bottom, expr)));
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::eqExpr(typename SolverContext::result_type a,
                                      typename SolverContext::result_type b) {
  return (evaluate(_solver, metaSMT::logic::equal(a, b)));
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::constructAShrByConstant(
    typename SolverContext::result_type expr, unsigned width, unsigned shift,
    typename SolverContext::result_type isSigned) {
  typename SolverContext::result_type res;

  if (shift == 0) {
    res = expr;
  } else if (shift >= width) {
    res = bvZero(width);
  } else {
    res = evaluate(
        _solver,
        metaSMT::logic::Ite(isSigned, concat(bvMinusOne(shift),
                                             bvExtract(expr, width - 1, shift)),
                            bvRightShift(expr, width, shift)));
  }

  return (res);
}

// width is the width of expr; x -- number of bits to shift with
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::constructMulByConstant(
    typename SolverContext::result_type expr, unsigned width, uint64_t x) {

  uint64_t add, sub;
  typename SolverContext::result_type res;
  bool first = true;

  // expr*x == expr*(add-sub) == expr*add - expr*sub
  ComputeMultConstants64(x, add, sub);

  // legal, these would overflow completely
  add = bits64::truncateToNBits(add, width);
  sub = bits64::truncateToNBits(sub, width);

  for (int j = 63; j >= 0; j--) {
    uint64_t bit = 1LL << j;

    if ((add & bit) || (sub & bit)) {
      assert(!((add & bit) && (sub & bit)) && "invalid mult constants");

      typename SolverContext::result_type op = bvLeftShift(expr, width, j);

      if (add & bit) {
        if (!first) {
          res = evaluate(_solver, bvadd(res, op));
        } else {
          res = op;
          first = false;
        }
      } else {
        if (!first) {
          res = evaluate(_solver, bvsub(res, op));
        } else {
          // To reconsider: vc_bvUMinusExpr in STP
          res = evaluate(_solver, bvsub(bvZero(width), op));
          first = false;
        }
      }
    }
  }

  if (first) {
    res = bvZero(width);
  }

  return (res);
}

/*
 * Compute the 32-bit unsigned integer division of n by a divisor d based on
 * the constants derived from the constant divisor d.
 *
 * Returns n/d without doing explicit division.  The cost is 2 adds, 3 shifts,
 * and a (64-bit) multiply.
 *
 * @param expr_n numerator (dividend) n as an expression
 * @param width  number of bits used to represent the value
 * @param d      the divisor
 *
 * @return n/d without doing explicit division
 */
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::constructUDivByConstant(
    typename SolverContext::result_type expr_n, unsigned width, uint64_t d) {

  assert(width == 32 && "can only compute udiv constants for 32-bit division");

  // Compute the constants needed to compute n/d for constant d without division
  // by d.
  uint32_t mprime, sh1, sh2;
  ComputeUDivConstants32(d, mprime, sh1, sh2);
  typename SolverContext::result_type expr_sh1 = bvConst32(32, sh1);
  typename SolverContext::result_type expr_sh2 = bvConst32(32, sh2);

  // t1  = MULUH(mprime, n) = ( (uint64_t)mprime * (uint64_t)n ) >> 32
  typename SolverContext::result_type expr_n_64 =
      evaluate(_solver, concat(bvZero(32), expr_n)); // extend to 64 bits
  typename SolverContext::result_type t1_64bits =
      constructMulByConstant(expr_n_64, 64, (uint64_t)mprime);
  typename SolverContext::result_type t1 =
      bvExtract(t1_64bits, 63, 32); // upper 32 bits

  // n/d = (((n - t1) >> sh1) + t1) >> sh2;
  typename SolverContext::result_type n_minus_t1 =
      evaluate(_solver, bvsub(expr_n, t1));
  typename SolverContext::result_type shift_sh1 =
      bvVarRightShift(n_minus_t1, expr_sh1, 32);
  typename SolverContext::result_type plus_t1 =
      evaluate(_solver, bvadd(shift_sh1, t1));
  typename SolverContext::result_type res =
      bvVarRightShift(plus_t1, expr_sh2, 32);

  return (res);
}

/*
 * Compute the 32-bitnsigned integer division of n by a divisor d based on
 * the constants derived from the constant divisor d.
 *
 * Returns n/d without doing explicit division.  The cost is 3 adds, 3 shifts,
 * a (64-bit) multiply, and an XOR.
 *
 * @param n      numerator (dividend) as an expression
 * @param width  number of bits used to represent the value
 * @param d      the divisor
 *
 * @return n/d without doing explicit division
 */
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::constructSDivByConstant(
    typename SolverContext::result_type expr_n, unsigned width, uint64_t d) {

  assert(width == 32 && "can only compute udiv constants for 32-bit division");

  // Compute the constants needed to compute n/d for constant d w/o division by
  // d.
  int32_t mprime, dsign, shpost;
  ComputeSDivConstants32(d, mprime, dsign, shpost);
  typename SolverContext::result_type expr_dsign = bvConst32(32, dsign);
  typename SolverContext::result_type expr_shpost = bvConst32(64, shpost);

  // q0 = n + MULSH( mprime, n ) = n + (( (int64_t)mprime * (int64_t)n ) >> 32)
  int64_t mprime_64 = (int64_t)mprime;

  // ToDo Reconsider -- note differences in STP and metaSMT for sign_extend
  // arguments
  typename SolverContext::result_type expr_n_64 =
      evaluate(_solver, sign_extend(64 - width, expr_n));
  typename SolverContext::result_type mult_64 =
      constructMulByConstant(expr_n_64, 64, mprime_64);
  typename SolverContext::result_type mulsh =
      bvExtract(mult_64, 63, 32); // upper 32-bits
  typename SolverContext::result_type n_plus_mulsh =
      evaluate(_solver, bvadd(expr_n, mulsh));

  // Improved variable arithmetic right shift: sign extend, shift, extract.
  typename SolverContext::result_type extend_npm =
      evaluate(_solver, sign_extend(64 - width, n_plus_mulsh));
  typename SolverContext::result_type shift_npm =
      bvVarRightShift(extend_npm, expr_shpost, 64);
  typename SolverContext::result_type shift_shpost =
      bvExtract(shift_npm, 31, 0); // lower 32-bits

  /////////////

  // XSIGN(n) is -1 if n is negative, positive one otherwise
  typename SolverContext::result_type is_signed = bvBoolExtract(expr_n, 31);
  typename SolverContext::result_type neg_one = bvMinusOne(32);
  typename SolverContext::result_type xsign_of_n =
      evaluate(_solver, metaSMT::logic::Ite(is_signed, neg_one, bvZero(32)));

  // q0 = (n_plus_mulsh >> shpost) - XSIGN(n)
  typename SolverContext::result_type q0 =
      evaluate(_solver, bvsub(shift_shpost, xsign_of_n));

  // n/d = (q0 ^ dsign) - dsign
  typename SolverContext::result_type q0_xor_dsign =
      evaluate(_solver, bvxor(q0, expr_dsign));
  typename SolverContext::result_type res =
      evaluate(_solver, bvsub(q0_xor_dsign, expr_dsign));

  return (res);
}

template <typename SolverContext>
typename SolverContext::result_type MetaSMTBuilder<SolverContext>::bvLeftShift(
    typename SolverContext::result_type expr, unsigned width, unsigned shift) {

  typename SolverContext::result_type res;

  if (shift == 0) {
    res = expr;
  } else if (shift >= width) {
    res = bvZero(width);
  } else {
    // stp shift does "expr @ [0 x s]" which we then have to extract,
    // rolling our own gives slightly smaller exprs
    res = evaluate(_solver,
                   concat(extract(width - shift - 1, 0, expr), bvZero(shift)));
  }

  return (res);
}

template <typename SolverContext>
typename SolverContext::result_type MetaSMTBuilder<SolverContext>::bvRightShift(
    typename SolverContext::result_type expr, unsigned width, unsigned shift) {

  typename SolverContext::result_type res;

  if (shift == 0) {
    res = expr;
  } else if (shift >= width) {
    res = bvZero(width);
  } else {
    res = evaluate(_solver,
                   concat(bvZero(shift), extract(width - 1, shift, expr)));
  }

  return (res);
}

// left shift by a variable amount on an expression of the specified width
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvVarLeftShift(
    typename SolverContext::result_type expr,
    typename SolverContext::result_type shift, unsigned width) {

  assert(_solver.get_bv_width(expr) == width);
  assert(_solver.get_bv_width(shift) == width);

  // If overshifting, shift to zero
  return evaluate(_solver,
                  metaSMT::logic::Ite(bvult(shift, bvConst32(width, width)),
                                      bvshl(expr, shift), bvZero(width)));
}

// logical right shift by a variable amount on an expression of the specified
// width
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvVarRightShift(
    typename SolverContext::result_type expr,
    typename SolverContext::result_type shift, unsigned width) {

  assert(_solver.get_bv_width(expr) == width);
  assert(_solver.get_bv_width(shift) == width);

  // If overshifting, shift to zero
  return evaluate(_solver,
                  metaSMT::logic::Ite(bvult(shift, bvConst32(width, width)),
                                      bvshr(expr, shift), bvZero(width)));
}

// arithmetic right shift by a variable amount on an expression of the specified
// width
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::bvVarArithRightShift(
    typename SolverContext::result_type expr,
    typename SolverContext::result_type shift, unsigned width) {

  assert(_solver.get_bv_width(expr) == width);
  assert(_solver.get_bv_width(shift) == width);

  // If overshifting, shift to zero
  return evaluate(_solver,
                  metaSMT::logic::Ite(bvult(shift, bvConst32(width, width)),
                                      bvashr(expr, shift), bvZero(width)));
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::construct(ref<Expr> e) {
  typename SolverContext::result_type res = construct(e, 0);
  _constructed.clear();
  return res;
}

/** if *width_out!=1 then result is a bitvector,
    otherwise it is a bool */
template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::construct(ref<Expr> e, int *width_out) {

  if (!UseConstructHashMetaSMT || isa<ConstantExpr>(e)) {
    return (constructActual(e, width_out));
  } else {
    MetaSMTExprHashMapIter it = _constructed.find(e);
    if (it != _constructed.end()) {
      if (width_out) {
        *width_out = it->second.second;
      }
      return it->second.first;
    } else {
      int width = 0;
      if (!width_out) {
        width_out = &width;
      }
      typename SolverContext::result_type res = constructActual(e, width_out);
      _constructed.insert(std::make_pair(e, std::make_pair(res, *width_out)));
      return res;
    }
  }
}

template <typename SolverContext>
typename SolverContext::result_type
MetaSMTBuilder<SolverContext>::constructActual(ref<Expr> e, int *width_out) {

  typename SolverContext::result_type res;

  int width = 0;
  if (!width_out) {
    // assert(false);
    width_out = &width;
  }

  ++stats::queryConstructs;

  //     llvm::errs() << "Constructing expression ";
  //     ExprPPrinter::printSingleExpr(llvm::errs(), e);
  //     llvm::errs() << "\n";

  switch (e->getKind()) {

  case Expr::Constant: {
    ConstantExpr *coe = cast<ConstantExpr>(e);
    assert(coe);
    unsigned coe_width = coe->getWidth();
    *width_out = coe_width;

    // Coerce to bool if necessary.
    if (coe_width == 1) {
      res = (coe->isTrue()) ? getTrue() : getFalse();
    } else if (coe_width <= 32) {
      res = bvConst32(coe_width, coe->getZExtValue(32));
    } else if (coe_width <= 64) {
      res = bvConst64(coe_width, coe->getZExtValue());
    } else {
      ref<ConstantExpr> tmp = coe;
      res = bvConst64(64, tmp->Extract(0, 64)->getZExtValue());
      while (tmp->getWidth() > 64) {
        tmp = tmp->Extract(64, tmp->getWidth() - 64);
        unsigned min_width = std::min(64U, tmp->getWidth());
        res = evaluate(_solver,
                       concat(bvConst64(min_width, tmp->Extract(0, min_width)
                                                       ->getZExtValue()),
                              res));
      }
    }
    break;
  }

  case Expr::NotOptimized: {
    NotOptimizedExpr *noe = cast<NotOptimizedExpr>(e);
    assert(noe);
    res = construct(noe->src, width_out);
    break;
  }

  case Expr::Select: {
    SelectExpr *se = cast<SelectExpr>(e);
    assert(se);
    res = evaluate(_solver,
                   metaSMT::logic::Ite(construct(se->cond, 0),
                                       construct(se->trueExpr, width_out),
                                       construct(se->falseExpr, width_out)));
    break;
  }

  case Expr::Read: {
    ReadExpr *re = cast<ReadExpr>(e);
    assert(re && re->updates.root);
    *width_out = re->updates.root->getRange();
    // FixMe call method of Array
    res = evaluate(_solver,
                   metaSMT::logic::Array::select(
                       getArrayForUpdate(re->updates.root, re->updates.head),
                       construct(re->index, 0)));
    break;
  }

  case Expr::Concat: {
    ConcatExpr *ce = cast<ConcatExpr>(e);
    assert(ce);
    *width_out = ce->getWidth();
    unsigned numKids = ce->getNumKids();

    if (numKids > 0) {
      res = evaluate(_solver, construct(ce->getKid(numKids - 1), 0));
      for (int i = numKids - 2; i >= 0; i--) {
        res = evaluate(_solver, concat(construct(ce->getKid(i), 0), res));
      }
    }
    break;
  }

  case Expr::Extract: {
    ExtractExpr *ee = cast<ExtractExpr>(e);
    assert(ee);
    // ToDo spare evaluate?
    typename SolverContext::result_type child =
        evaluate(_solver, construct(ee->expr, width_out));

    unsigned ee_width = ee->getWidth();
    *width_out = ee_width;

    if (ee_width == 1) {
      res = bvBoolExtract(child, ee->offset);
    } else {
      res = evaluate(_solver,
                     extract(ee->offset + ee_width - 1, ee->offset, child));
    }
    break;
  }

  case Expr::ZExt: {
    CastExpr *ce = cast<CastExpr>(e);
    assert(ce);

    int child_width = 0;
    typename SolverContext::result_type child =
        evaluate(_solver, construct(ce->src, &child_width));

    unsigned ce_width = ce->getWidth();
    *width_out = ce_width;

    if (child_width == 1) {
      res = evaluate(_solver, metaSMT::logic::Ite(child, bvOne(ce_width),
                                                  bvZero(ce_width)));
    } else {
      res = evaluate(_solver, zero_extend(ce_width - child_width, child));
    }

    // ToDo calculate how many zeros to add
    // Note: STP and metaSMT differ in the prototype arguments;
    // STP requires the width of the resulting bv;
    // whereas metaSMT (and Z3) require the width of the zero vector that is to
    // be appended
    // res = evaluate(_solver, zero_extend(ce_width, construct(ce->src)));

    break;
  }

  case Expr::SExt: {
    CastExpr *ce = cast<CastExpr>(e);
    assert(ce);

    int child_width = 0;
    typename SolverContext::result_type child =
        evaluate(_solver, construct(ce->src, &child_width));

    unsigned ce_width = ce->getWidth();
    *width_out = ce_width;

    if (child_width == 1) {
      res = evaluate(_solver, metaSMT::logic::Ite(child, bvMinusOne(ce_width),
                                                  bvZero(ce_width)));
    } else {
      // ToDo ce_width - child_width? It is only ce_width in STPBuilder
      res = evaluate(_solver, sign_extend(ce_width - child_width, child));
    }

    break;
  }

  case Expr::Add: {
    AddExpr *ae = cast<AddExpr>(e);
    assert(ae);
    res = evaluate(_solver, bvadd(construct(ae->left, width_out),
                                  construct(ae->right, width_out)));
    assert(*width_out != 1 && "uncanonicalized add");
    break;
  }

  case Expr::Sub: {
    SubExpr *se = cast<SubExpr>(e);
    assert(se);
    res = evaluate(_solver, bvsub(construct(se->left, width_out),
                                  construct(se->right, width_out)));
    assert(*width_out != 1 && "uncanonicalized sub");
    break;
  }

  case Expr::Mul: {
    MulExpr *me = cast<MulExpr>(e);
    assert(me);

    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(me->right, width_out));
    assert(*width_out != 1 && "uncanonicalized mul");

    ConstantExpr *CE = dyn_cast<ConstantExpr>(me->left);
    if (CE && (CE->getWidth() <= 64)) {
      res = constructMulByConstant(right_expr, *width_out, CE->getZExtValue());
    } else {
      res =
          evaluate(_solver, bvmul(construct(me->left, width_out), right_expr));
    }
    break;
  }

  case Expr::UDiv: {
    UDivExpr *de = cast<UDivExpr>(e);
    assert(de);

    typename SolverContext::result_type left_expr =
        construct(de->left, width_out);
    assert(*width_out != 1 && "uncanonicalized udiv");
    bool construct_both = true;

    ConstantExpr *CE = dyn_cast<ConstantExpr>(de->right);
    if (CE && (CE->getWidth() <= 64)) {
      uint64_t divisor = CE->getZExtValue();
      if (bits64::isPowerOfTwo(divisor)) {
        res = bvRightShift(left_expr, *width_out,
                           bits64::indexOfSingleBit(divisor));
        construct_both = false;
      } else if (_optimizeDivides) {
        if (*width_out == 32) { // only works for 32-bit division
          res =
              constructUDivByConstant(left_expr, *width_out, (uint32_t)divisor);
          construct_both = false;
        }
      }
    }

    if (construct_both) {
      res =
          evaluate(_solver, bvudiv(left_expr, construct(de->right, width_out)));
    }
    break;
  }

  case Expr::SDiv: {
    SDivExpr *de = cast<SDivExpr>(e);
    assert(de);

    typename SolverContext::result_type left_expr =
        construct(de->left, width_out);
    assert(*width_out != 1 && "uncanonicalized sdiv");

    bool optimized = false;
    ConstantExpr *CE = dyn_cast<ConstantExpr>(de->right);
    if (CE && _optimizeDivides && (*width_out == 32)) {
      llvm::APInt divisor = CE->getAPValue();
      if (divisor != llvm::APInt(CE->getWidth(), 1, false /*unsigned*/) &&
          divisor != llvm::APInt(CE->getWidth(), -1, true /*signed*/)) {
        res = constructSDivByConstant(left_expr, *width_out,
                                      CE->getZExtValue(32));
        optimized = true;
      }
    }
    if (!optimized) {
      res =
          evaluate(_solver, bvsdiv(left_expr, construct(de->right, width_out)));
    }
    break;
  }

  case Expr::URem: {
    URemExpr *de = cast<URemExpr>(e);
    assert(de);

    typename SolverContext::result_type left_expr =
        construct(de->left, width_out);
    assert(*width_out != 1 && "uncanonicalized urem");

    bool construct_both = true;
    ConstantExpr *CE = dyn_cast<ConstantExpr>(de->right);
    if (CE && (CE->getWidth() <= 64)) {

      uint64_t divisor = CE->getZExtValue();

      if (bits64::isPowerOfTwo(divisor)) {

        unsigned bits = bits64::indexOfSingleBit(divisor);
        // special case for modding by 1 or else we bvExtract -1:0
        if (bits == 0) {
          res = bvZero(*width_out);
          construct_both = false;
        } else {
          res = evaluate(_solver, concat(bvZero(*width_out - bits),
                                         bvExtract(left_expr, bits - 1, 0)));
          construct_both = false;
        }
      }

      // Use fast division to compute modulo without explicit division for
      // constant divisor.

      if (_optimizeDivides &&
          *width_out == 32) { // only works for 32-bit division
        typename SolverContext::result_type quotient =
            constructUDivByConstant(left_expr, *width_out, (uint32_t)divisor);
        typename SolverContext::result_type quot_times_divisor =
            constructMulByConstant(quotient, *width_out, divisor);
        res = evaluate(_solver, bvsub(left_expr, quot_times_divisor));
        construct_both = false;
      }
    }

    if (construct_both) {
      res =
          evaluate(_solver, bvurem(left_expr, construct(de->right, width_out)));
    }
    break;
  }

  case Expr::SRem: {
    SRemExpr *de = cast<SRemExpr>(e);
    assert(de);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(de->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(de->right, width_out));
    assert(*width_out != 1 && "uncanonicalized srem");

    bool construct_both = true;

#if 0 // not faster per first benchmark
            
            if (_optimizeDivides) {
                if (ConstantExpr *cre = de->right->asConstant()) {
                    uint64_t divisor = cre->asUInt64;
    
                    //use fast division to compute modulo without explicit division for constant divisor
                    if( *width_out == 32 ) { //only works for 32-bit division
                       	typename SolverContext::result_type quotient = constructSDivByConstant(left, *width_out, divisor);
                        typename SolverContext::result_type quot_times_divisor = constructMulByConstant(quotient, *width_out, divisor);
                        res = vc_bvMinusExpr( vc, *width_out, left, quot_times_divisor );
                        construct_both = false;
                    }
                }
            }

#endif

    if (construct_both) {
      res = evaluate(_solver, bvsrem(left_expr, right_expr));
    }
    break;
  }

  case Expr::Not: {
    NotExpr *ne = cast<NotExpr>(e);
    assert(ne);

    typename SolverContext::result_type child =
        evaluate(_solver, construct(ne->expr, width_out));
    if (*width_out == 1) {
      res = evaluate(_solver, metaSMT::logic::Not(child));
    } else {
      res = evaluate(_solver, bvnot(child));
    }
    break;
  }

  case Expr::And: {
    AndExpr *ae = cast<AndExpr>(e);
    assert(ae);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(ae->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(ae->right, width_out));

    if (*width_out == 1) {
      res = evaluate(_solver, metaSMT::logic::And(left_expr, right_expr));
    } else {
      res = evaluate(_solver, bvand(left_expr, right_expr));
    }

    break;
  }

  case Expr::Or: {
    OrExpr *oe = cast<OrExpr>(e);
    assert(oe);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(oe->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(oe->right, width_out));

    if (*width_out == 1) {
      res = evaluate(_solver, metaSMT::logic::Or(left_expr, right_expr));
    } else {
      res = evaluate(_solver, bvor(left_expr, right_expr));
    }

    break;
  }

  case Expr::Xor: {
    XorExpr *xe = cast<XorExpr>(e);
    assert(xe);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(xe->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(xe->right, width_out));

    if (*width_out == 1) {
      res = evaluate(_solver, metaSMT::logic::Xor(left_expr, right_expr));
    } else {
      res = evaluate(_solver, bvxor(left_expr, right_expr));
    }

    break;
  }

  case Expr::Shl: {
    ShlExpr *se = cast<ShlExpr>(e);
    assert(se);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(se->left, width_out));
    assert(*width_out != 1 && "uncanonicalized shl");

    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(se->right)) {
      res = bvLeftShift(left_expr, *width_out, (unsigned)CE->getLimitedValue());
    } else {
      int shiftWidth = 0;
      typename SolverContext::result_type right_expr =
          evaluate(_solver, construct(se->right, &shiftWidth));
      res = bvVarLeftShift(left_expr, right_expr, *width_out);
    }

    break;
  }

  case Expr::LShr: {
    LShrExpr *lse = cast<LShrExpr>(e);
    assert(lse);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(lse->left, width_out));
    assert(*width_out != 1 && "uncanonicalized lshr");

    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(lse->right)) {
      res =
          bvRightShift(left_expr, *width_out, (unsigned)CE->getLimitedValue());
    } else {
      int shiftWidth = 0;
      typename SolverContext::result_type right_expr =
          evaluate(_solver, construct(lse->right, &shiftWidth));
      res = bvVarRightShift(left_expr, right_expr, *width_out);
    }

    break;
  }

  case Expr::AShr: {
    AShrExpr *ase = cast<AShrExpr>(e);
    assert(ase);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(ase->left, width_out));
    assert(*width_out != 1 && "uncanonicalized ashr");

    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(ase->right)) {
      unsigned shift = (unsigned)CE->getLimitedValue();
      typename SolverContext::result_type signedBool =
          bvBoolExtract(left_expr, *width_out - 1);
      res = constructAShrByConstant(left_expr, *width_out, shift, signedBool);
    } else {
      int shiftWidth = 0;
      typename SolverContext::result_type right_expr =
          evaluate(_solver, construct(ase->right, &shiftWidth));
      res = bvVarArithRightShift(left_expr, right_expr, *width_out);
    }

    break;
  }

  case Expr::Eq: {
    EqExpr *ee = cast<EqExpr>(e);
    assert(ee);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(ee->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(ee->right, width_out));

    if (*width_out == 1) {
      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(ee->left)) {
        if (CE->isTrue()) {
          res = right_expr;
        } else {
          res = evaluate(_solver, metaSMT::logic::Not(right_expr));
        }
      } else {
        res = evaluate(_solver, metaSMT::logic::equal(left_expr, right_expr));
      }
    } // end of *width_out == 1
    else {
      *width_out = 1;
      res = evaluate(_solver, metaSMT::logic::equal(left_expr, right_expr));
    }

    break;
  }

  case Expr::Ult: {
    UltExpr *ue = cast<UltExpr>(e);
    assert(ue);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(ue->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(ue->right, width_out));

    assert(*width_out != 1 && "uncanonicalized ult");
    *width_out = 1;

    res = evaluate(_solver, bvult(left_expr, right_expr));
    break;
  }

  case Expr::Ule: {
    UleExpr *ue = cast<UleExpr>(e);
    assert(ue);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(ue->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(ue->right, width_out));

    assert(*width_out != 1 && "uncanonicalized ule");
    *width_out = 1;

    res = evaluate(_solver, bvule(left_expr, right_expr));
    break;
  }

  case Expr::Slt: {
    SltExpr *se = cast<SltExpr>(e);
    assert(se);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(se->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(se->right, width_out));

    assert(*width_out != 1 && "uncanonicalized slt");
    *width_out = 1;

    res = evaluate(_solver, bvslt(left_expr, right_expr));
    break;
  }

  case Expr::Sle: {
    SleExpr *se = cast<SleExpr>(e);
    assert(se);

    typename SolverContext::result_type left_expr =
        evaluate(_solver, construct(se->left, width_out));
    typename SolverContext::result_type right_expr =
        evaluate(_solver, construct(se->right, width_out));

    assert(*width_out != 1 && "uncanonicalized sle");
    *width_out = 1;

    res = evaluate(_solver, bvsle(left_expr, right_expr));
    break;
  }

// unused due to canonicalization
#if 0
        case Expr::Ne:
        case Expr::Ugt:
        case Expr::Uge:
        case Expr::Sgt:
        case Expr::Sge:
#endif

  default:
    assert(false);
    break;
  };
  return res;
}

} /* end of namespace klee */

#endif /* ENABLE_METASMT */

#endif /* KLEE_METASMTBUILDER_H */