-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathmemory.cpp
More file actions
3222 lines (2746 loc) · 103 KB
/
Copy pathmemory.cpp
File metadata and controls
3222 lines (2746 loc) · 103 KB
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
// Copyright (c) 2018-present The Alive2 Authors.
// Distributed under the MIT license that can be found in the LICENSE file.
#include "ir/memory.h"
#include "ir/function.h"
#include "ir/globals.h"
#include "ir/state.h"
#include "ir/value.h"
#include "smt/solver.h"
#include "util/compiler.h"
#include "util/config.h"
#include <algorithm>
#include <array>
#include <bit>
#include <numeric>
#include <string>
#define MAX_STORED_PTRS_SET 3
using namespace IR;
using namespace smt;
using namespace std;
using namespace util;
// Non-local block ids (assuming that no block is optimized out):
// 1. null block: has_null_block
// 2. global vars in source:
// + num_consts_src (constant globals)
// + num_globals_src (all globals incl constant)
// 3. pointer argument inputs:
// has_null_block + num_globals_src + num_ptrinputs
// 4. nonlocal blocks returned by loads/calls:
// has_null_block + num_globals_src + num_ptrinputs + 1 -> ...
// 5. a block reserved for encoding the memory touched by calls:
// num_nonlocals_src - num_inaccessiblememonly_fns - has_write_fncall
// 6. 1 block per inaccessiblememonly
// + num_inaccessiblememonly_fns ~ num_nonlocals_src - 1
// 7. constant global vars in target only:
// num_nonlocals_src ~ num_nonlocals - 1
// (constant globals in target only)
//--- Functions for non-local block analysis based on bid ---//
static bool skip_null() {
return has_null_block && !null_is_dereferenceable;
}
// If include_tgt is true, return true if bid is a global var existing in target
// only as well
static bool is_globalvar(unsigned bid, bool include_tgt) {
bool srcglb = has_null_block <= bid && bid < has_null_block + num_globals_src;
bool tgtglb = num_nonlocals_src <= bid && bid < num_nonlocals;
return srcglb || (include_tgt && tgtglb);
}
static bool is_constglb(unsigned bid, bool src_only = false) {
if (has_null_block <= bid && bid < num_consts_src + has_null_block) {
// src constglb
assert(is_globalvar(bid, false));
return true;
}
if (!src_only && num_nonlocals_src <= bid && bid < num_nonlocals) {
// tgt constglb
assert(!is_globalvar(bid, false) &&
is_globalvar(bid, true));
return true;
}
return false;
}
// Return true if bid is the nonlocal block used to encode function calls' side
// effects
static unsigned get_fncallmem_bid() {
assert(has_write_fncall || num_inaccessiblememonly_fns > 0);
return num_nonlocals_src - num_inaccessiblememonly_fns - has_write_fncall;
}
static bool is_fncall_mem(unsigned bid) {
if (!has_write_fncall && num_inaccessiblememonly_fns == 0)
return false;
return bid >= get_fncallmem_bid() && bid < num_nonlocals_src;
}
static void ensure_non_fncallmem(const Pointer &p) {
if (!p.isLocal().isFalse())
return;
uint64_t ubid;
assert(!p.getShortBid().isUInt(ubid) || !is_fncall_mem(ubid));
(void)ubid;
}
// bid: nonlocal block id
static bool always_alive(unsigned bid) {
return // globals are always live
is_globalvar(bid, true) ||
// We can assume that bid is always live if it is a fncall mem.
// Otherwise, fncall cannot write to the block.
is_fncall_mem(bid);
}
// bid: nonlocal block id
static bool always_noread(unsigned bid, bool is_fncall_accessible = false) {
return (!null_is_dereferenceable && bid < has_null_block) ||
(!is_fncall_accessible && is_fncall_mem(bid));
}
// bid: nonlocal block id
static bool always_nowrite(unsigned bid, bool src_only = false,
bool is_fncall_accessible = false) {
return always_noread(bid, is_fncall_accessible) || is_constglb(bid, src_only);
}
static expr mk_block_if(const expr &cond, expr then, expr els) {
if (cond.isTrue())
return then;
if (cond.isFalse())
return els;
bool is_bv1 = then.isBV();
bool is_bv2 = els.isBV();
if (is_bv1 != is_bv2) {
expr offset = expr::mkUInt(0, Pointer::bitsShortOffset());
if (is_bv1)
then = expr::mkConstArray(offset, then);
else
els = expr::mkConstArray(offset, els);
}
return expr::mkIf(cond, then, els);
}
static unsigned next_local_bid;
static unsigned next_const_bid;
static unsigned next_global_bid;
static unsigned next_ptr_input;
static unsigned size_byte_number() {
if (!num_sub_byte_bits)
return 0;
return
max(ilog2_ceil(divide_up(1 << num_sub_byte_bits, bits_byte), false), 1u);
}
static unsigned sub_byte_bits() {
return num_sub_byte_bits + size_byte_number();
}
static bool does_int_mem_access() {
return does_int_load || does_int_store;
}
static bool does_ptr_mem_access() {
return does_ptr_load || does_ptr_store;
}
static bool byte_has_ptr_bit() {
return does_int_mem_access() && does_ptr_mem_access();
}
static unsigned bits_ptr_byte_offset() {
if (bits_byte >= bits_program_pointer)
return 0;
return std::countr_zero(bits_program_pointer / bits_byte);
}
static unsigned padding_ptr_byte() {
return Byte::bitsByte() - byte_has_ptr_bit() - 1 - Pointer::totalBits()
- bits_ptr_byte_offset();
}
static unsigned padding_nonptr_byte() {
return
Byte::bitsByte() - byte_has_ptr_bit() - bits_byte - bits_poison_per_byte
- num_sub_byte_bits - size_byte_number();
}
static expr concat_if(const expr &ifvalid, expr &&e) {
return ifvalid.isValid() ? ifvalid.concat(e) : std::move(e);
}
static string local_name(const State *s, const char *name) {
return string(name) + (s->isSource() ? "_src" : "_tgt");
}
static bool align_ge_size(const expr &align, const expr &size) {
uint64_t algn, sz;
return align.isUInt(algn) && size.isUInt(sz) && (1ull << algn) >= sz;
}
static bool align_gt_size(const expr &align, const expr &size) {
uint64_t algn, sz;
return align.isUInt(algn) && size.isUInt(sz) && (1ull << algn) > sz;
}
// Assumes that both begin + len don't overflow
static expr disjoint(const expr &begin1, const expr &len1, const expr &align1,
const expr &begin2, const expr &len2, const expr &align2) {
// if blocks have the same alignment they can't start in the middle of
// each other. We just need to ensure they have a different addr.
if (align1.eq(align2) && align_ge_size(align1, len1) &&
align_ge_size(align2, len2))
return begin1 != begin2;
return begin1.uge(begin2 + len2) || begin2.uge(begin1 + len1);
}
static expr load_bv(const expr &var, const expr &idx0) {
auto bw = var.bits();
if (!bw)
return {};
if (var.isAllOnes())
return true;
auto idx = idx0.zextOrTrunc(bw);
return var.lshr(idx).extract(0, 0) == 1;
}
static void store_bv(Pointer &p, const expr &val, expr &local,
expr &non_local, bool assume_local = false,
const expr &cond = true) {
auto bid0 = p.getShortBid();
auto set = [&](const expr &var) {
auto bw = var.bits();
if (!bw)
return expr();
auto bid = bid0.zextOrTrunc(bw);
auto one = expr::mkUInt(1, var) << bid;
auto full = expr::mkInt(-1, bid);
auto mask = (full << (bid + expr::mkUInt(1, var))) |
full.lshr(expr::mkUInt(bw, var) - bid);
return expr::mkIf(val, var | one, var & mask);
};
auto is_local = p.isLocal() || assume_local;
local = mkIf_fold(cond && is_local, set(local), local);
non_local = mkIf_fold(cond && !is_local, set(non_local), non_local);
}
namespace IR {
Byte::Byte(const Memory &m, expr &&byterepr) : m(m), p(std::move(byterepr)) {
assert(!p.isValid() || p.bits() == bitsByte());
}
Byte::Byte(const Memory &m, const StateValue &ptr, unsigned i) : m(m) {
// TODO: support pointers larger than 64 bits.
assert(bits_program_pointer <= 64 && bits_program_pointer % 8 == 0);
assert(i == 0 || bits_ptr_byte_offset() > 0);
if (!does_ptr_mem_access()) {
p = expr::mkUInt(0, bitsByte());
return;
}
if (byte_has_ptr_bit())
p = expr::mkUInt(1, 1);
p = concat_if(p,
expr::mkIf(ptr.non_poison, expr::mkUInt(1, 1),
expr::mkUInt(0, 1)))
.concat(ptr.value);
if (bits_ptr_byte_offset())
p = p.concat(expr::mkUInt(i, bits_ptr_byte_offset()));
p = p.concat_zeros(padding_ptr_byte());
assert(!ptr.isValid() || p.bits() == bitsByte());
}
Byte::Byte(const Memory &m, const StateValue &v, unsigned bits_read,
unsigned byte_number)
: m(m) {
assert(!v.isValid() || v.value.bits() == bits_byte);
assert(!v.isValid() || v.non_poison.isBool() ||
v.non_poison.bits() == bits_poison_per_byte);
if (!does_int_mem_access()) {
p = expr::mkUInt(0, bitsByte());
return;
}
if (byte_has_ptr_bit())
p = expr::mkUInt(0, 1);
expr np = v.non_poison.isBool()
? expr::mkIf(v.non_poison,
expr::mkInt(-1, bits_poison_per_byte),
expr::mkUInt(0, bits_poison_per_byte))
: v.non_poison;
p = concat_if(p, np.concat(v.value));
if (num_sub_byte_bits) {
// optimization: byte number doesn't matter in assembly
if (m.isAsmMode()) {
p = p.concat_zeros(sub_byte_bits());
} else {
if ((bits_read % 8) == 0)
bits_read = 0;
p = p.concat(expr::mkUInt(bits_read, num_sub_byte_bits)
.concat(expr::mkUInt(byte_number, size_byte_number())));
}
}
p = p.concat_zeros(padding_nonptr_byte());
assert(!p.isValid() || p.bits() == bitsByte());
}
Byte Byte::mkPoisonByte(const Memory &m) {
return { m, StateValue(expr::mkUInt(0, bits_byte), false), 0, true };
}
expr Byte::isPtr() const {
if (!byte_has_ptr_bit())
return does_ptr_mem_access();
return p.sign() == 1;
}
expr Byte::ptrNonpoison() const {
auto bit = p.bits() - 1 - byte_has_ptr_bit();
return isAsmMode() ? expr(true) : p.extract(bit, bit) == 1;
}
Pointer Byte::ptr() const {
return { m, ptrValue() };
}
expr Byte::ptrValue() const {
if (!does_ptr_mem_access())
return expr::mkUInt(0, Pointer::totalBits());
auto start = bits_ptr_byte_offset() + padding_ptr_byte();
return p.extract(Pointer::totalBits() + start - 1, start);
}
expr Byte::ptrByteoffset() const {
if (!does_ptr_mem_access())
return expr::mkUInt(0, bits_ptr_byte_offset());
if (bits_ptr_byte_offset() == 0)
return expr::mkUInt(0, 1);
unsigned start = padding_ptr_byte();
return p.extract(bits_ptr_byte_offset() + start - 1, start);
}
expr Byte::nonptrNonpoison() const {
if (!does_int_mem_access())
return expr::mkUInt(0, 1);
if (isAsmMode())
return expr::mkInt(-1, bits_poison_per_byte);
unsigned start = padding_nonptr_byte() + bits_byte + sub_byte_bits();
return p.extract(start + bits_poison_per_byte - 1, start);
}
expr Byte::boolNonptrNonpoison() const {
expr np = nonptrNonpoison();
return np == expr::mkInt(-1, np);
}
expr Byte::nonptrValue() const {
if (!does_int_mem_access())
return expr::mkUInt(0, bits_byte);
unsigned start = padding_nonptr_byte() + sub_byte_bits();
return p.extract(start + bits_byte - 1, start);
}
expr Byte::numStoredBits() const {
unsigned start = padding_nonptr_byte() + size_byte_number();
return p.extract(start + num_sub_byte_bits - 1, start);
}
expr Byte::byteNumber() const {
unsigned start = padding_nonptr_byte();
return p.extract(start + size_byte_number() - 1, start);
}
expr Byte::isPoison() const {
if (!does_int_mem_access())
return does_ptr_mem_access() ? !ptrNonpoison() : true;
if (isAsmMode())
return false;
expr np = nonptrNonpoison();
if (byte_has_ptr_bit() && bits_poison_per_byte == 1) {
assert(!np.isValid() || ptrNonpoison().eq(np == 1));
return np != 1;
}
return expr::mkIf(isPtr(), !ptrNonpoison(), np != expr::mkInt(-1, np));
}
expr Byte::nonPoison() const {
if (isAsmMode())
return expr::mkInt(-1, bits_poison_per_byte);
if (!does_int_mem_access())
return ptrNonpoison();
expr np = nonptrNonpoison();
if (byte_has_ptr_bit() && bits_poison_per_byte == 1) {
assert(!np.isValid() || ptrNonpoison().eq(np == 1));
return np;
}
return expr::mkIf(isPtr(),
expr::mkIf(ptrNonpoison(), expr::mkInt(-1, np),
expr::mkUInt(0, np)),
np);
}
expr Byte::isZero() const {
return expr::mkIf(isPtr(), ptr().isNull(), nonptrValue() == 0);
}
bool Byte::isAsmMode() const {
return m.isAsmMode();
}
expr Byte::castPtrToInt() const {
auto offset = ptrByteoffset().zextOrTrunc(bits_ptr_address);
offset = offset * expr::mkUInt(bits_byte, offset);
return ptr().getAddress().lshr(offset).zextOrTrunc(bits_byte);
}
expr Byte::forceCastToInt() const {
return mkIf_fold(isPtr(), castPtrToInt(), nonptrValue());
}
expr TypedByte::isPtr() const {
return (type & DATA_PTR) ? byte.isPtr() : expr(false);
}
expr TypedByte::forceCastToInt() const {
switch (type) {
case DATA_NONE: return expr::mkUInt(0, bits_byte);
case DATA_INT: return nonptrValue();
case DATA_PTR: return castPtrToInt();
case DATA_ANY: return byte.forceCastToInt();
}
}
expr TypedByte::nonPoison() const {
if (isAsmMode())
return expr::mkInt(-1, bits_poison_per_byte);
switch (type) {
case DATA_NONE: return expr::mkUInt(0, bits_poison_per_byte);
case DATA_INT: return nonptrNonpoison();
case DATA_ANY: return byte.nonPoison();
case DATA_PTR: {
auto np = ptrNonpoison();
if (!does_int_mem_access())
return np;
auto zero = expr::mkUInt(0, bits_poison_per_byte);
return expr::mkIf(np, expr::mkInt(-1, zero), zero);
}
}
}
expr TypedByte::isPoison() const {
switch (type) {
case DATA_NONE: return expr(!isAsmMode());
case DATA_PTR: return !ptrNonpoison();
case DATA_ANY: return byte.isPoison();
case DATA_INT: {
auto np = nonptrNonpoison();
return np != expr::mkInt(-1, np);
}
}
}
expr TypedByte::refined(const TypedByte &other) const {
bool asm_mode = other.isAsmMode();
expr is_ptr = isPtr();
expr is_ptr2 = other.isPtr();
// allow int -> ptr type punning
expr v1 = nonptrValue();
expr v2 = other.forceCastToInt();
expr np1 = nonptrNonpoison();
expr np2 = other.nonPoison();
// int byte
expr int_cnstr = (asm_mode || !num_sub_byte_bits) ? expr(true)
: (np1 == 0 ||
(numStoredBits() == other.numStoredBits() &&
byteNumber() == other.byteNumber()));
if (does_int_store) {
if (bits_poison_per_byte == bits_byte) {
int_cnstr &= (np2 & np1) == np1 && (v1 & np1) == (v2 & np1);
}
else if (bits_poison_per_byte > 1) {
assert((bits_byte % bits_poison_per_byte) == 0);
unsigned bits_val = bits_byte / bits_poison_per_byte;
for (unsigned i = 0; i < bits_poison_per_byte; ++i) {
expr ev1 = v1.extract((i+1) * bits_val - 1, i * bits_val);
expr ev2 = v2.extract((i+1) * bits_val - 1, i * bits_val);
expr enp1 = np1.extract(i, i);
expr enp2 = np2.extract(i, i);
int_cnstr
&= enp1 == 0 || ((enp1.eq(enp2) ? true : enp2 == 1) && ev1 == ev2);
}
} else {
assert(!np1.isValid() || np1.bits() == 1);
int_cnstr &= np1 == 0 || ((np1.eq(np2) ? true : np2 == 1) && v1 == v2);
}
}
expr ptr_cnstr;
// fast path: if we didn't do any ptr store, then all ptrs in memory were
// already there and don't need checking
if (!does_ptr_store || is_ptr.isFalse()) {
ptr_cnstr = true;
} else if (!does_int_store) {
ptr_cnstr = ptrNonpoison().implies(
other.ptrNonpoison() &&
ptrByteoffset() == other.ptrByteoffset() &&
ptr().refined(other.ptr()));
} else {
auto other_int = other.nonptrValue();
ptr_cnstr = ptrNonpoison().implies(
expr::mkIf(is_ptr2,
other.ptrNonpoison() &&
ptrByteoffset() == other.ptrByteoffset() &&
ptr().refined(other.ptr()),
// allow a ptr without provenance to be replaced with an
// integer
other.boolNonptrNonpoison() &&
(asm_mode ? castPtrToInt() == other_int
: (ptr().isLogical()
.implies(ptr().getBid() == 0) &&
ptr().getAddress()
.zextOrTrunc(other_int.bits()) ==
other_int)
)));
}
return expr::mkIf(is_ptr, ptr_cnstr, int_cnstr);
}
unsigned Byte::bitsByte() {
unsigned ptr_bits = does_ptr_mem_access() *
(1 + Pointer::totalBits() + bits_ptr_byte_offset());
unsigned int_bits = does_int_mem_access() * (bits_byte + bits_poison_per_byte)
+ sub_byte_bits();
// allow at least 1 bit if there's no memory access
return max(1u, byte_has_ptr_bit() + max(ptr_bits, int_bits));
}
ostream& operator<<(ostream &os, const Byte &byte) {
if (byte.isPtr().isTrue()) {
if (byte.ptrNonpoison().isTrue()) {
os << byte.ptr() << ", byte offset=";
byte.ptrByteoffset().printUnsigned(os);
} else {
os << "poison";
}
} else {
auto np = byte.nonptrNonpoison();
auto val = byte.nonptrValue();
if (np.isZero())
return os << "poison";
if (np.isAllOnes()) {
val.printHexadecimal(os);
} else {
os << "#b";
for (unsigned i = 0; i < bits_poison_per_byte; ++i) {
unsigned idx = bits_poison_per_byte - i - 1;
auto is_poison = np.extract(idx, idx).isZero();
auto v = val.extract(idx, idx).isAllOnes();
os << (is_poison ? 'p' : (v ? '1' : '0'));
}
}
uint64_t num_bits;
if (num_sub_byte_bits &&
byte.numStoredBits().isUInt(num_bits) && num_bits != 0) {
os << " / written with " << num_bits << " bits";
if (byte.byteNumber().isUInt(num_bits))
os << " / byte #" << num_bits;
}
}
return os;
}
unsigned Memory::bitsAlignmentInfo() {
return ilog2_ceil(bits_size_t, false);
}
bool Memory::observesAddresses() {
return true; //observes_addresses;
}
static bool isFnReturnValue(const expr &e) {
expr arr, idx;
if (e.isLoad(arr, idx))
return isFnReturnValue(arr);
expr val;
unsigned hi, lo;
if (e.isExtract(val, hi, lo))
return isFnReturnValue(val);
return e.fn_name().starts_with("#fnret_");
}
int Memory::isInitialMemBlock(const expr &e, bool match_any_init) {
string_view name;
expr load, blk, idx;
unsigned hi, lo;
if (e.isExtract(load, hi, lo) && load.isLoad(blk, idx))
name = blk.fn_name();
else
name = e.fn_name();
if (name.starts_with("init_mem_"))
return 1;
return match_any_init && name.starts_with("blk_val!") ? 2 : 0;
}
bool Memory::isInitialMemoryOrLoad(const expr &e, bool match_any_init) {
expr arr, idx;
if (e.isLoad(arr, idx))
return isInitialMemoryOrLoad(arr, match_any_init);
expr val;
unsigned hi, lo;
if (e.isExtract(val, hi, lo))
return isInitialMemoryOrLoad(val, match_any_init);
return isInitialMemBlock(e, match_any_init) != 0;
}
}
static void pad(StateValue &v, unsigned amount, State &s) {
if (amount == 0)
return;
expr ty = expr::mkUInt(0, amount);
auto pad = [&](expr &v) {
expr var = expr::mkFreshVar("padding", ty);
v = var.concat(v);
s.addQuantVar(var);
};
pad(v.value);
if (!v.non_poison.isBool())
pad(v.non_poison);
}
static vector<Byte> valueToBytes(const StateValue &val, const Type &fromType,
const Memory &mem, State &s) {
vector<Byte> bytes;
if (fromType.isPtrType()) {
Pointer p(mem, val.value);
unsigned bytesize = bits_program_pointer / bits_byte;
// constant global can't store pointers that alias with local blocks
if (s.isInitializationPhase() && !p.isLocal().isFalse()) {
expr bid = expr::mkUInt(0, 1).concat(p.getShortBid());
p = Pointer(mem, bid, p.getOffset(), p.getAttrs());
}
for (unsigned i = 0; i < bytesize; ++i)
bytes.emplace_back(mem, StateValue(expr(p()), expr(val.non_poison)), i);
} else {
assert(!fromType.isAggregateType() || isNonPtrVector(fromType));
StateValue bvval = fromType.toInt(s, val);
unsigned bitsize = bvval.bits();
unsigned bytesize = divide_up(bitsize, bits_byte);
// There are no sub-byte accesses in assembly
if (mem.isAsmMode() && (bitsize % 8) != 0) {
s.addUB(expr(false));
}
pad(bvval, bytesize * bits_byte - bitsize, s);
unsigned np_mul = bits_poison_per_byte;
for (unsigned i = 0; i < bytesize; ++i) {
StateValue data {
bvval.value.extract((i + 1) * bits_byte - 1, i * bits_byte),
bvval.non_poison.extract((i + 1) * np_mul - 1, i * np_mul)
};
bytes.emplace_back(mem, data, bitsize, i);
}
}
return bytes;
}
static StateValue bytesToValue(const Memory &m, const vector<TypedByte> &bytes,
const Type &toType) {
assert(!bytes.empty());
auto ub_pre = [&](expr &&e) -> expr {
if (config::disallow_ub_exploitation) {
m.getState().addPre(std::move(e));
return true;
}
return std::move(e);
};
bool is_asm = m.isAsmMode();
if (toType.isPtrType()) {
assert(bytes.size() == bits_program_pointer / bits_byte);
expr loaded_ptr, all_are_ptr;
// The result is not poison if all of these hold:
// (1) There's no poison byte, and they are all pointer bytes
// (2) All of the bytes have the same information
// (3) Byte offsets should be correct
// Integers are converted to pointers without provenance
expr non_poison = true;
expr byte_offset_np = true;
expr int_cast_offset;
for (unsigned i = 0, e = bytes.size(); i < e; ++i) {
auto &b = bytes[i];
expr ptr_value = b.ptrValue();
expr int_value = b.forceCastToInt();
expr b_is_ptr = b.isPtr();
if (i == 0) {
loaded_ptr = ptr_value;
all_are_ptr = std::move(b_is_ptr);
int_cast_offset = std::move(int_value);
} else {
all_are_ptr &= b_is_ptr;
int_cast_offset = int_value.concat(int_cast_offset);
}
byte_offset_np &= b.ptrByteoffset() == i && ptr_value == loaded_ptr;
non_poison &= !b.isPoison();
}
non_poison &= ub_pre(all_are_ptr.implies(byte_offset_np));
if (is_asm)
non_poison = true;
Pointer auto_cast(m, expr::mkUInt(0, bits_for_bid),
int_cast_offset.zextOrTrunc(bits_for_offset));
return { expr::mkIf(all_are_ptr, loaded_ptr, auto_cast()),
std::move(non_poison) };
} else {
assert(!toType.isAggregateType() || isNonPtrVector(toType));
auto bitsize = toType.bits();
assert(divide_up(bitsize, bits_byte) == bytes.size());
StateValue val;
bool first = true;
IntType ibyteTy("", bits_byte);
unsigned byte_number = 0;
for (auto &b: bytes) {
expr expr_np = true;
if (num_sub_byte_bits) {
unsigned bits = (bitsize % 8) == 0 ? 0 : bitsize;
expr_np &= b.numStoredBits() == bits;
expr_np &= b.byteNumber() == byte_number++;
}
auto np = ibyteTy.combine_poison(expr_np, b.nonptrNonpoison());
if (is_asm) {
np = expr::mkInt(-1, np);
} else if (does_ptr_mem_access()) {
expr np_ptr = expr::mkIf(b.ptrNonpoison() && (bitsize % 8) == 0,
expr::mkInt(-1, np), expr::mkUInt(0, np));
np = expr::mkIf(b.isPtr(), np_ptr, np);
}
StateValue v(b.forceCastToInt(), std::move(np));
val = first ? std::move(v) : v.concat(val);
first = false;
}
return toType.fromInt(val.trunc(bitsize, toType.np_bits(true)));
}
}
namespace IR {
Memory::AliasSet::AliasSet(const Memory &m)
: local(m.numLocals(), false), non_local(m.numNonlocals(), false) {}
Memory::AliasSet::AliasSet(const Memory &m1, const Memory &m2)
: local(max(m1.numLocals(), m2.numLocals()), false),
non_local(max(m1.numNonlocals(), m2.numNonlocals()), false) {}
size_t Memory::AliasSet::size(bool islocal) const {
return (islocal ? local : non_local).size();
}
int Memory::AliasSet::isFullUpToAlias(bool islocal) const {
auto &v = islocal ? local : non_local;
unsigned i = 0;
for (unsigned e = v.size(); i != e; ++i) {
if (!v[i])
break;
}
for (unsigned i2 = i, e = v.size(); i2 != e; ++i2) {
if (v[i])
return -1;
}
return i - 1;
}
expr Memory::AliasSet::mayAlias(bool islocal, const expr &bid) const {
int upto = isFullUpToAlias(islocal);
if (upto >= 0)
return bid.ule(upto);
expr ret(false);
for (unsigned i = 0, e = size(islocal); i < e; ++i) {
if (mayAlias(islocal, i))
ret |= bid == i;
}
return ret;
}
bool Memory::AliasSet::mayAlias(bool islocal, unsigned bid) const {
return (islocal ? local : non_local)[bid];
}
unsigned Memory::AliasSet::numMayAlias(bool islocal) const {
auto &v = islocal ? local : non_local;
return count(v.begin(), v.end(), true);
}
void Memory::AliasSet::setMayAlias(bool islocal, unsigned bid) {
(islocal ? local : non_local)[bid] = true;
}
void Memory::AliasSet::setMayAliasUpTo(bool local, unsigned limit) {
for (unsigned i = 0; i <= limit; ++i) {
setMayAlias(local, i);
}
}
void Memory::AliasSet::setNoAlias(bool islocal, unsigned bid) {
(islocal ? local : non_local)[bid] = false;
}
void Memory::AliasSet::intersectWith(const AliasSet &other) {
auto intersect = [](auto &a, const auto &b) {
auto I2 = b.begin(), E2 = b.end();
for (auto I = a.begin(), E = a.end(); I != E && I2 != E2; ++I, ++I2) {
*I = *I && *I2;
}
};
intersect(local, other.local);
intersect(non_local, other.non_local);
}
void Memory::AliasSet::unionWith(const AliasSet &other) {
auto unionfn = [](auto &a, const auto &b) {
auto I2 = b.begin(), E2 = b.end();
for (auto I = a.begin(), E = a.end(); I != E && I2 != E2; ++I, ++I2) {
*I = *I || *I2;
}
};
unionfn(local, other.local);
unionfn(non_local, other.non_local);
}
static const array<uint64_t, 5> alias_buckets_vals = { 1, 2, 3, 5, 10 };
static array<uint64_t, 6> alias_buckets_hits = { 0 };
static uint64_t only_local = 0, only_nonlocal = 0;
void Memory::AliasSet::computeAccessStats() const {
auto nlocal = numMayAlias(true);
auto nnonlocal = numMayAlias(false);
if (nlocal > 0 && nnonlocal == 0)
++only_local;
else if (nlocal == 0 && nnonlocal > 0)
++only_nonlocal;
auto alias = nlocal + nnonlocal;
for (unsigned i = 0; i < alias_buckets_vals.size(); ++i) {
if (alias <= alias_buckets_vals[i]) {
++alias_buckets_hits[i];
return;
}
}
++alias_buckets_hits.back();
}
void Memory::AliasSet::printStats(ostream &os) {
double total
= accumulate(alias_buckets_hits.begin(), alias_buckets_hits.end(), 0);
if (!total)
return;
total /= 100.0;
os.precision(1);
os << fixed;
os << "\n\nAlias sets statistics\n=====================\n"
"Only local: " << only_local
<< " (" << (only_local / total)
<< "%)\nOnly non-local: " << only_nonlocal
<< " (" << (only_nonlocal / total)
<< "%)\n\nBuckets:\n";
for (unsigned i = 0; i < alias_buckets_vals.size(); ++i) {
os << "\u2264 " << alias_buckets_vals[i] << ": "
<< alias_buckets_hits[i]
<< " (" << (alias_buckets_hits[i] / total) << "%)\n";
}
os << "> " << alias_buckets_vals.back() << ": "
<< alias_buckets_hits.back()
<< " (" << (alias_buckets_hits.back() / total) << "%)\n";
}
void Memory::AliasSet::print(ostream &os) const {
auto print = [&](const char *str, const auto &v) {
os << str;
for (auto bit : v) {
os << bit;
}
};
bool has_local = false;
if (numMayAlias(true) > 0) {
print("local: ", local);
has_local = true;
}
if (numMayAlias(false) > 0) {
if (has_local) os << " / ";
print("non-local: ", non_local);
} else if (!has_local)
os << "(empty)";
}
weak_ordering Memory::MemBlock::operator<=>(const MemBlock &rhs) const {
// FIXME:
// 1) xcode doesn't have tuple::operator<=>
// 2) gcc has a bug and can't generate the default
if (auto cmp = val <=> rhs.val; is_neq(cmp)) return cmp;
if (auto cmp = undef <=> rhs.undef; is_neq(cmp)) return cmp;
if (auto cmp = type <=> rhs.type; is_neq(cmp)) return cmp;
return weak_ordering::equivalent;
}
static set<Pointer> all_leaf_ptrs(const Memory &m, const expr &ptr) {
set<Pointer> ptrs;
for (auto &ptr_val : ptr.leafs()) {
ptrs.emplace(m, ptr_val);
}
return ptrs;
}
static set<expr> extract_possible_local_bids(Memory &m, const expr &eptr) {
set<expr> ret;
for (auto &ptr : all_leaf_ptrs(m, eptr)) {
if (!ptr.isLocal().isFalse() && !ptr.isLogical().isFalse())
ret.emplace(ptr.getShortBid());
}
return ret;
}
static unsigned max_program_nonlocal_bid() {
return num_nonlocals_src-1 - num_inaccessiblememonly_fns - has_write_fncall;
}
unsigned Memory::nextNonlocalBid() {
unsigned next = min(next_nonlocal_bid++, max_program_nonlocal_bid());
assert(!is_fncall_mem(next));
return next;
}
unsigned Memory::numCurrentNonLocals() const {
unsigned bids = min(next_nonlocal_bid, max_program_nonlocal_bid());
assert(!is_fncall_mem(bids));
return bids + 1;
}
unsigned Memory::numLocals() const {
return state->isSource() ? num_locals_src : num_locals_tgt;
}
unsigned Memory::numNonlocals() const {
return state->isSource() ? num_nonlocals_src : num_nonlocals;
}
expr Memory::isBlockAlive(const expr &bid, bool local) const {
uint64_t bid_n;
if (!local && bid.isUInt(bid_n) && always_alive(bid_n))
return true;
return
load_bv(local ? local_block_liveness : non_local_block_liveness, bid) &&
(!local && has_null_block && !null_is_dereferenceable ? bid != 0 : true);
}
bool Memory::mayalias(const Pointer &p, bool local, unsigned bid0,
const expr &offset0, const expr &bytes, uint64_t align,
bool write) const {
if (local && bid0 >= next_local_bid)