-
Notifications
You must be signed in to change notification settings - Fork 0
/
patmatlang.py
1502 lines (1216 loc) · 40.7 KB
/
patmatlang.py
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
import sys
from contextlib import contextmanager
from collections import defaultdict
from rply import LexerGenerator, LexingError, ParserGenerator, ParsingError
from rply.token import BaseBox
from rpython.rlib.rarithmetic import LONG_BIT, r_uint, intmask, ovfcheck, uint_mul_high
# ____________________________________________________________
# lexer
lg = LexerGenerator()
alltokens = []
def addtok(name, regex):
alltokens.append(name)
lg.add(name, regex)
def addkeyword(kw):
addtok(kw.upper(), r"\b" + kw + r"\b")
addkeyword("check")
addkeyword("and")
addkeyword("or")
addtok("NUMBER", r"[+-]?([1-9]\d*)|0")
addtok("NAME", r"[a-zA-Z_][a-zA-Z_0-9]*")
addtok("LSHIFT", r"[<][<]")
addtok("ARSHIFT", r"[>][>]a")
addtok("URSHIFT", r"[>][>]u")
addtok("ARROW", r"=>")
addtok("LPAREN", r"[(]")
addtok("RPAREN", r"[)]")
addtok("COMMA", r"[,]")
addtok("EQUALEQUAL", r"[=][=]")
addtok("EQUAL", r"[=]")
addtok("COLON", r"[:]")
addtok("DOT", r"[.]")
addtok("GE", r"[>][=]")
addtok("GT", r"[>]")
addtok("LE", r"[<][=]")
addtok("LT", r"[<]")
addtok("NE", r"[!=]")
addtok("PLUS", r"[+]")
addtok("MINUS", r"[-]")
addtok("MUL", r"[*]")
addtok("DIV", r"[/][/]")
addtok("OP_AND", r"[&]")
addtok("OP_OR", r"[|]")
addtok("OP_XOR", r"^")
addtok("INVERT", r"~")
addtok("NEWLINE", r" *([#].*)?\n")
lg.ignore(r"[ ]")
lexer = lg.build()
# ____________________________________________________________
# AST classes
class Visitor(object):
def visit(self, ast):
meth = getattr(self, "visit_%s" % type(ast).__name__, None)
if meth is not None:
return meth(ast)
return self.default_visit(ast)
def default_visit(self, ast):
pass
class BaseAst(BaseBox):
# __metaclass__ = extendabletype
def __eq__(self, other):
if type(self) != type(other):
return NotImplemented
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
def __repr__(self):
args = ["%s=%r" % (key, value) for key, value in self.__dict__.items()]
if len(args) == 1:
args = [repr(self.__dict__.values()[0])]
return "%s(%s)" % (
type(self).__name__,
", ".join(args),
)
def view(self):
from rpython.translator.tool.make_dot import DotGen
from dotviewer import graphclient
import pytest
dotgen = DotGen("G")
self._dot(dotgen)
p = pytest.ensuretemp("pyparser").join("temp.dot")
p.write(dotgen.generate(target=None))
graphclient.display_dot_file(str(p))
def _dot(self, dotgen):
arcs = []
label = [type(self).__name__]
for key, value in self.__dict__.items():
if isinstance(value, BaseAst):
arcs.append((value, key))
value._dot(dotgen)
elif isinstance(value, list) and value and isinstance(value[0], BaseAst):
for index, item in enumerate(value):
arcs.append((item, "%s[%s]" % (key, index)))
item._dot(dotgen)
else:
label.append("%s = %r" % (key, value))
dotgen.emit_node(str(id(self)), shape="box", label="\n".join(label))
for target, label in arcs:
dotgen.emit_edge(str(id(self)), str(id(target)), label)
class File(BaseAst):
def __init__(self, rules):
self.rules = rules
class Rule(BaseAst):
def __init__(self, name, pattern, elements, target):
self.name = name
self.pattern = pattern
self.elements = elements
self.target = target
def __str__(self):
lines = [self.name + ": " + str(self.pattern)]
for el in self.elements:
lines.append(" " + str(el))
lines.append(" => " + str(self.target))
return "\n".join(lines)
class Pattern(BaseAst):
pass
class PatternVar(Pattern):
def __init__(self, name):
self.name = name
def sort_key(self):
return (2, self.name)
def sort_key_result(self):
return (1, self.name)
def __str__(self):
return self.name
class PatternConst(BaseAst):
def __init__(self, const):
self.const = const
def sort_key(self):
return (0, self.const)
def sort_key_result(self):
return (0, self.const)
def __str__(self):
return str(self.const)
class PatternOp(BaseAst):
def __init__(self, opname, args):
self.opname = opname
self.args = args
def newargs(self, args):
return PatternOp(self.opname, args)
def sort_key(self):
return (1, self.opname) + tuple(sorted(arg.sort_key() for arg in self.args))
def sort_key_result(self):
return (2, self.opname) + tuple(
sorted(arg.sort_key_result() for arg in self.args)
)
def __str__(self):
return "%s(%s)" % (self.opname, ", ".join([str(arg) for arg in self.args]))
class Compute(BaseAst):
def __init__(self, name, expr):
self.name = name
self.expr = expr
def __str__(self):
return "compute %s = %s" % (self.name, self.expr)
class Check(BaseAst):
def __init__(self, expr):
self.expr = expr
def __str__(self):
return "check %s" % (self.expr,)
class Expression(BaseAst):
pass
class Name(BaseAst):
def __init__(self, name):
self.name = name
class Number(BaseAst):
def __init__(self, value):
self.value = value
class BinOp(Expression):
def __init__(self, left, right):
self.left = left
self.right = right
class IntBinOp(BinOp):
pass
class Add(IntBinOp):
opname = "int_add"
class Sub(IntBinOp):
opname = "int_sub"
class Mul(IntBinOp):
opname = "int_mul"
class Div(IntBinOp):
opname = "int_div"
class LShift(IntBinOp):
opname = "int_lshift"
class URShift(IntBinOp):
opname = "uint_rshift"
class ARShift(IntBinOp):
opname = "int_rshift"
class OpAnd(IntBinOp):
opname = "int_and"
class OpOr(IntBinOp):
opname = "int_or"
class OpXor(IntBinOp):
opname = "int_xor"
class Eq(IntBinOp):
opname = "int_eq"
class Ge(IntBinOp):
opname = "int_ge"
class Gt(IntBinOp):
opname = "int_gt"
class Le(IntBinOp):
opname = "int_le"
class Lt(IntBinOp):
opname = "int_lt"
class Ne(IntBinOp):
opname = "int_ne"
class ShortcutAnd(BinOp):
pass
class ShortcutOr(BinOp):
pass
class UnaryOp(Expression):
def __init__(self, left):
self.left = left
class IntUnaryOp(UnaryOp):
pass
class Invert(IntUnaryOp):
opname = "int_invert"
class Attribute(BaseAst):
def __init__(self, varname, attrname):
self.varname = varname
self.attrname = attrname
class MethodCall(BaseAst):
def __init__(self, value, methname, args):
self.value = value
self.methname = methname
self.args = args
class FuncCall(BaseAst):
def __init__(self, funcname, args):
self.funcname = funcname
self.args = args
# ____________________________________________________________
# parser
pg = ParserGenerator(
alltokens,
precedence=[
("left", ["OR"]),
("left", ["AND"]),
("left", ["NOT"]),
("left", ["EQUALEQUAL", "GE", "GT", "LE", "LT", "NE"]),
("left", ["OP_OR"]),
("left", ["OP_XOR"]),
("left", ["OP_AND"]),
("left", ["LSHIFT", "ARSHIFT", "URSHIFT"]),
("left", ["PLUS", "MINUS"]),
("left", ["MUL", "DIV"]),
("left", ["INVERT"]),
("left", ["DOT"]),
],
)
@pg.production("file : rule | file rule")
def file(p):
if len(p) == 1:
return File(p)
return File(p[0].rules + [p[1]])
@pg.production("newlines : NEWLINE | NEWLINE newlines")
def newlines(p):
return None
@pg.production("rule : NAME COLON pattern elements ARROW pattern newlines")
def rule(p):
return Rule(p[0].value, p[2], p[3], p[5])
@pg.production("pattern : NAME")
def pattern_var(p):
return PatternVar(p[0].value)
@pg.production("pattern : NUMBER")
def pattern_const(p):
return PatternConst(p[0].value)
@pg.production("pattern : NAME LPAREN patternargs RPAREN")
def pattern_op(p):
return PatternOp(p[0].value, p[2])
@pg.production("patternargs : pattern | pattern COMMA patternargs")
def patternargs(p):
if len(p) == 1:
return p
return [p[0]] + p[2]
@pg.production("elements : newlines | newlines element elements")
def elements(p):
if len(p) == 1:
return []
return [p[1]] + p[2]
@pg.production("element : NAME EQUAL expression")
def compute_element(p):
return Compute(p[0].value, p[2])
@pg.production("element : CHECK expression")
def check(p):
return Check(p[1])
@pg.production("expression : NUMBER")
def expression_number(p):
return Number(int(p[0].getstr()))
@pg.production("expression : NAME")
def expression_name(p):
return Name(p[0].getstr())
@pg.production("expression : LPAREN expression RPAREN")
def expression_parens(p):
return p[1]
@pg.production("expression : INVERT expression")
def expression_unary(p):
return Invert(p[1])
@pg.production("expression : expression PLUS expression")
@pg.production("expression : expression MINUS expression")
@pg.production("expression : expression MUL expression")
@pg.production("expression : expression DIV expression")
@pg.production("expression : expression LSHIFT expression")
@pg.production("expression : expression URSHIFT expression")
@pg.production("expression : expression ARSHIFT expression")
@pg.production("expression : expression AND expression")
@pg.production("expression : expression OR expression")
@pg.production("expression : expression OP_AND expression")
@pg.production("expression : expression OP_OR expression")
@pg.production("expression : expression OP_XOR expression")
@pg.production("expression : expression EQUALEQUAL expression")
@pg.production("expression : expression GE expression")
@pg.production("expression : expression GT expression")
@pg.production("expression : expression LE expression")
@pg.production("expression : expression LT expression")
@pg.production("expression : expression NE expression")
def expression_binop(p):
left = p[0]
right = p[2]
if p[1].gettokentype() == "PLUS":
return Add(left, right)
elif p[1].gettokentype() == "MINUS":
return Sub(left, right)
elif p[1].gettokentype() == "MUL":
return Mul(left, right)
elif p[1].gettokentype() == "DIV":
return Div(left, right)
elif p[1].gettokentype() == "LSHIFT":
return LShift(left, right)
elif p[1].gettokentype() == "URSHIFT":
return URShift(left, right)
elif p[1].gettokentype() == "ARSHIFT":
return ARShift(left, right)
elif p[1].gettokentype() == "AND":
return ShortcutAnd(left, right)
elif p[1].gettokentype() == "OR":
return ShortcutOr(left, right)
elif p[1].gettokentype() == "OP_AND":
return OpAnd(left, right)
elif p[1].gettokentype() == "OP_OR":
return OpOr(left, right)
elif p[1].gettokentype() == "OP_XOR":
return OpXor(left, right)
elif p[1].gettokentype() == "EQUALEQUAL":
return Eq(left, right)
elif p[1].gettokentype() == "GE":
return Ge(left, right)
elif p[1].gettokentype() == "GT":
return Gt(left, right)
elif p[1].gettokentype() == "LE":
return Le(left, right)
elif p[1].gettokentype() == "LT":
return Lt(left, right)
elif p[1].gettokentype() == "NE":
return Ne(left, right)
else:
raise AssertionError("Oops, this should not be possible!")
@pg.production("expression : expression DOT NAME maybecall")
def attr_or_method(p):
assert p[1].gettokentype() == "DOT"
if p[3] is not None:
return MethodCall(p[0], p[2].value, p[3])
return Attribute(p[0].name, p[2].value)
@pg.production("expression : NAME LPAREN args RPAREN")
def funccall(p):
return FuncCall(p[0].value, p[2])
@pg.production("maybecall : | LPAREN args RPAREN")
def methodcall(p):
if not p:
return None
return p[1]
@pg.production("args : | expression | expression COMMA args ")
def args(p):
if len(p) <= 1:
return p
import pdb
pdb.set_trace()
parser = pg.build()
def print_conflicts():
if parser.lr_table.rr_conflicts:
print("rr conflicts")
for rule_num, token, conflict in parser.lr_table.rr_conflicts:
print(rule_num, token, conflict)
if parser.lr_table.sr_conflicts:
print("sr conflicts")
for rule_num, token, conflict in parser.lr_table.sr_conflicts:
print(rule_num, token, conflict)
parser = pg.build()
print_conflicts()
def parse(s):
return parser.parse(lexer.lex(s))
def test_parse_int_add_zero():
s = """\
add_zero: int_add(x, 0)
=> x
"""
ast = parse(s)
assert ast == File(
rules=[
Rule(
elements=[],
name="add_zero",
pattern=PatternOp(
args=[PatternVar(name="x"), PatternConst(const="0")],
opname="int_add",
),
target=PatternVar(name="x"),
)
]
)
def test_parse_int_add_zero():
s = """\
add_reassoc_consts: int_add(int_add(x, C1), C2)
C = C1 + C2
=> int_add(x, C)
"""
ast = parse(s)
assert ast == File(
rules=[
Rule(
elements=[
Compute(
expr=Add(left=Name(name="C1"), right=Name(name="C2")), name="C"
)
],
name="add_reassoc_consts",
pattern=PatternOp(
args=[
PatternOp(
args=[PatternVar(name="x"), PatternVar(name="C1")],
opname="int_add",
),
PatternVar(name="C2"),
],
opname="int_add",
),
target=PatternOp(
args=[PatternVar(name="x"), PatternVar(name="C")], opname="int_add"
),
)
]
)
def test_parse_int_mul():
s = """\
mul_zero: int_mul(x, 0)
=> 0
mul_one: int_mul(x, 1)
=> 1
mul_minus_one: int_mul(x, -1)
=> int_neg(x)
mul_neg_neg: int_mul(int_neg(x), int_neg(y))
=> int_mul(x, y)
"""
ast = parse(s)
assert ast == File(
rules=[
Rule(
elements=[],
name="mul_zero",
pattern=PatternOp(
args=[PatternVar(name="x"), PatternConst(const="0")],
opname="int_mul",
),
target=PatternConst(const="0"),
),
Rule(
elements=[],
name="mul_one",
pattern=PatternOp(
args=[PatternVar(name="x"), PatternConst(const="1")],
opname="int_mul",
),
target=PatternConst(const="1"),
),
Rule(
elements=[],
name="mul_minus_one",
pattern=PatternOp(
args=[PatternVar(name="x"), PatternConst(const="-1")],
opname="int_mul",
),
target=PatternOp(args=[PatternVar(name="x")], opname="int_neg"),
),
Rule(
elements=[],
name="mul_neg_neg",
pattern=PatternOp(
args=[
PatternOp(args=[PatternVar(name="x")], opname="int_neg"),
PatternOp(args=[PatternVar(name="y")], opname="int_neg"),
],
opname="int_mul",
),
target=PatternOp(
args=[PatternVar(name="x"), PatternVar(name="y")], opname="int_mul"
),
),
]
)
def test_parse_lshift_rshift():
s = """\
int_lshift_int_rshift_consts: int_lshift(int_rshift(x, C1), C1)
C = (-1 >>a C1) << C1
=> int_and(x, C)
"""
ast = parse(s)
def generate_commutative_patterns_args(args):
if not args:
yield []
return
arg0 = args[0]
args1 = args[1:]
for subarg0 in generate_commutative_patterns(arg0):
for subargs1 in generate_commutative_patterns_args(args1):
yield [subarg0] + subargs1
def generate_commutative_patterns(pattern):
if not isinstance(pattern, PatternOp):
yield pattern
return
for subargs in generate_commutative_patterns_args(pattern.args):
if pattern.opname not in commutative_ops:
yield pattern.newargs(subargs)
else:
yield pattern.newargs(subargs)
yield pattern.newargs(subargs[::-1])
def generate_commutative_rules(rule):
for pattern in generate_commutative_patterns(rule.pattern):
yield Rule(rule.name, pattern, rule.elements, rule.target)
def test_generate_commutative_rules():
s = """\
add_zero: int_add(x, 0)
=> x
"""
ast = parse(s)
patterns = list(generate_commutative_patterns(ast.rules[0].pattern))
assert patterns == [
PatternOp(
args=[PatternVar(name="x"), PatternConst(const="0")], opname="int_add"
),
PatternOp(
args=[PatternConst(const="0"), PatternVar(name="x")], opname="int_add"
),
]
assert len(patterns) == 2
s = """\
add_reassoc_consts: int_add(int_add(x, C1), C2)
C = C1 + C2
=> int_add(x, C)
"""
ast = parse(s)
patterns = list(generate_commutative_patterns(ast.rules[0].pattern))
assert patterns == [
PatternOp(
opname="int_add",
args=[
PatternOp(opname="int_add", args=[PatternVar("x"), PatternVar("C1")]),
PatternVar("C2"),
],
),
PatternOp(
opname="int_add",
args=[
PatternVar("C2"),
PatternOp(opname="int_add", args=[PatternVar("x"), PatternVar("C1")]),
],
),
PatternOp(
opname="int_add",
args=[
PatternOp(opname="int_add", args=[PatternVar("C1"), PatternVar("x")]),
PatternVar("C2"),
],
),
PatternOp(
opname="int_add",
args=[
PatternVar("C2"),
PatternOp(opname="int_add", args=[PatternVar("C1"), PatternVar("x")]),
],
),
]
def sort_rules(rules):
return sorted(
rules, key=lambda rule: (rule.target.sort_key_result(), rule.pattern.sort_key())
)
def test_sort_patterns():
s = """\
int_sub_zero: int_sub(x, 0)
=> x
int_sub_x_x: int_sub(x, x)
=> 0
int_sub_add: int_sub(int_add(x, y), y)
=> x
int_sub_zero_neg: int_sub(0, x)
=> int_neg(x)
"""
ast = parse(s)
rules = sort_rules(ast.rules)
assert rules == [
Rule(
name="int_sub_x_x",
pattern=PatternOp(
opname="int_sub", args=[PatternVar("x"), PatternVar("x")]
),
elements=[],
target=PatternConst("0"),
),
Rule(
name="int_sub_zero",
pattern=PatternOp(
opname="int_sub", args=[PatternVar("x"), PatternConst("0")]
),
elements=[],
target=PatternVar("x"),
),
Rule(
name="int_sub_add",
pattern=PatternOp(
opname="int_sub",
args=[
PatternOp(
opname="int_add", args=[PatternVar("x"), PatternVar("y")]
),
PatternVar("y"),
],
),
elements=[],
target=PatternVar("x"),
),
Rule(
name="int_sub_zero_neg",
pattern=PatternOp(
opname="int_sub", args=[PatternConst("0"), PatternVar("x")]
),
elements=[],
target=PatternOp(opname="int_neg", args=[PatternVar("x")]),
),
]
commutative_ops = {"int_add", "int_mul"}
# ___________________________________________________________________________
import z3
from rpython.jit.metainterp.optimizeopt.test.test_z3intbound import (
Z3IntBound,
make_z3_intbounds_instance,
)
class CouldNotProve(Exception):
pass
TRUEBV = z3.BitVecVal(1, LONG_BIT)
FALSEBV = z3.BitVecVal(0, LONG_BIT)
def z3_cond(z3expr):
return z3.If(z3expr, TRUEBV, FALSEBV)
def z3_bool_expression(opname, arg0, arg1=None):
expr = None
valid = True
if opname == "int_eq":
expr = arg0 == arg1
elif opname == "int_ne":
expr = arg0 != arg1
elif opname == "int_lt":
expr = arg0 < arg1
elif opname == "int_le":
expr = arg0 <= arg1
elif opname == "int_gt":
expr = arg0 > arg1
elif opname == "int_ge":
expr = arg0 >= arg1
elif opname == "uint_lt":
expr = z3.ULT(arg0, arg1)
elif opname == "uint_le":
expr = z3.ULE(arg0, arg1)
elif opname == "uint_gt":
expr = z3.UGT(arg0, arg1)
elif opname == "uint_ge":
expr = z3.UGE(arg0, arg1)
elif opname == "int_is_true":
expr = arg0 != FALSEBV
elif opname == "int_is_zero":
expr = arg0 == FALSEBV
else:
assert 0
return expr, valid
def z3_expression(opname, arg0, arg1=None):
expr = None
valid = True
if opname == "int_add":
expr = arg0 + arg1
elif opname == "int_sub":
expr = arg0 - arg1
elif opname == "int_mul":
expr = arg0 * arg1
elif opname == "int_and":
expr = arg0 & arg1
elif opname == "int_or":
expr = arg0 | arg1
elif opname == "int_xor":
expr = arg0 ^ arg1
elif opname == "int_lshift":
expr = arg0 << arg1
valid = z3.And(arg1 >= 0, arg1 < LONG_BIT)
elif opname == "int_rshift":
expr = arg0 >> arg1
valid = z3.And(arg1 >= 0, arg1 < LONG_BIT)
elif opname == "uint_rshift":
expr = z3.LShR(arg0, arg1)
valid = z3.And(arg1 >= 0, arg1 < LONG_BIT)
elif opname == "uint_mul_high":
# zero-extend args to 2*LONG_BIT bit, then multiply and extract
# highest LONG_BIT bits
zarg0 = z3.ZeroExt(LONG_BIT, arg0)
zarg1 = z3.ZeroExt(LONG_BIT, arg1)
expr = z3.Extract(LONG_BIT * 2 - 1, LONG_BIT, zarg0 * zarg1)
elif opname == "int_neg":
expr = -arg0
elif opname == "int_invert":
expr = ~arg0
else:
expr, valid = z3_bool_expression(opname, arg0, arg1)
return z3_cond(expr), valid
return expr, valid
def z3_and(*args):
args = [arg for arg in args if arg is not True]
if args:
if len(args) == 1:
return args[0]
return z3.And(*args)
return True
def z3_implies(a, b):
if a is True:
return b
return z3.Implies(a, b)
def popcount64(w):
w -= (w >> 1) & 0x5555555555555555
w = (w & 0x3333333333333333) + ((w >> 2) & 0x3333333333333333)
w = (w + (w >> 4)) & 0x0F0F0F0F0F0F0F0F
return ((w * 0x0101010101010101) >> 56) & 0xFF
def highest_bit(x):
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
x |= x >> 32
return popcount64(x) - 1
def z3_highest_bit(x):
x |= z3.LShR(x, 1)
x |= z3.LShR(x, 2)
x |= z3.LShR(x, 4)
x |= z3.LShR(x, 8)
x |= z3.LShR(x, 16)
x |= z3.LShR(x, 32)
return popcount64(x) - 1
def test_higest_bit():
for i in range(64):
assert highest_bit(r_uint(1) << i) == i
class Prover(object):
def __init__(self):
self.solver = z3.Solver()
self.name_to_z3 = {}
self.name_to_intbound = {}
self.glue_conditions_added = set()
self.glue_conditions = []
def prove(self, cond):
z3res = self.solver.check(z3.Not(cond))
if z3res == z3.unsat:
return True
elif z3res == z3.unknown:
return False
elif z3res == z3.sat:
global model
model = self.solver.model()
return False
def _convert_var(self, name):
def newvar(name, suffix=""):
if suffix:
name += "_" + suffix
res = z3.BitVec(name, LONG_BIT)
self.name_to_z3[name] = res
return res
if name in self.name_to_z3:
return self.name_to_z3[name]
res = newvar(name)
b = make_z3_intbounds_instance(name, res)