Repository navigation
Expand file tree
/
Copy pathkernel.py
More file actions
1819 lines (1587 loc) · 60.9 KB
/
Copy pathkernel.py
File metadata and controls
1819 lines (1587 loc) · 60.9 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
"""OProof kernel.
Sound proof-checking kernel for proving that two sequences of code are
EXACTLY the same (same types, same bit patterns, same definedness, for every
input).
"""
from __future__ import annotations
import os
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, NamedTuple
if TYPE_CHECKING: # axiom_store imports the kernel, so this is one-way
from axiom_store import Axiom
# Canonical value invariant (nailed down BEFORE any rewrite rule)
#
# Every concrete value ``v`` of a fully typed ``Lit(v, t)`` is stored in the
# *canonical* form for ``t``:
#
# * ``t.signed`` -> ``t.min_value <= v <= t.max_value``
# (two's-complement signed interpretation)
# * ``t.signed`` F -> ``0 <= v < 2**t.width``
# (plain unsigned bit pattern)
#
# ``t.wrap(raw)`` brings any integer into canonical form and is the ONLY
# place bits are re-interpreted. It follows from these semantics that:
#
# * ``exts`` (sign-extension) preserves the signed value: on a literal it
# is ``v -> v`` for signed destinations and ``v -> v mod 2**w`` for
# unsigned destinations;
# * ``extz`` (zero-extension) keeps the source unsigned bit pattern:
# ``v -> v mod 2**srcw``;
# * a right shift is *arithmetic* for signed types (``shrs``) and
# *logical* for unsigned ones (``shru``) -- never interchangeable;
# * every other operator wraps modulo ``2**t.width`` exactly like the bit
# pattern of the underlying machine type.
#
# Literals are stored "adaptable" (``type is None``) until ripening binds
# them to a type; ripening then wraps them into canonical form. Because
# canonical form is unique per bit pattern, ``key()`` equality between two
# sides of a proof is exactly bit-for-bit equality.
#
# Division semantics (an explicit decision, not an accident of Python):
#
# ``divs``/``rems`` are *signed machine* division and remainder: for
# negative operands they truncate toward zero (this is what C, RISC-V
# DIV/REM, WASM i32.div_s/rem_s and x86 IDIV do), and the remainder takes
# the sign of the dividend::
#
# divs(-3, 2) == -1 # NOT floor division (that would be -2)
# rems(-3, 2) == -1 # sign follows the dividend
#
# An arithmetic right shift (``shrs``) is *floor* division by ``2**k``
# (two's complement), so ``divs(x, 2**k) == shrs(x, k)`` holds only for
# ``x >= 0``. The identity sound for every ``x`` is the compiler's
# sign-corrected strength reduction, promoted in ``axioms/pow2.py``.
class KernelError(Exception):
"""Base error raised for ill-formed programs or proof steps."""
kind = "error"
def __init__(self, message: str):
super().__init__(message)
self.message = message
class TypeError_(KernelError):
kind = "type"
class DefinitionError(KernelError):
kind = "definition"
class OverFlowError(KernelError):
kind = "overflow"
class UndefinedError(KernelError):
kind = "undefined"
# Data types -- "data types control and resolvance"
class Type:
"""A fixed-width scalar machine type (two's complement)."""
__slots__ = ("name", "signed", "width")
def __init__(self, name: str, width: int, signed: bool):
self.name = name
self.width = width
self.signed = signed
@property
def modulus(self) -> int:
return 1 << self.width
@property
def mask(self) -> int:
return self.modulus - 1
@property
def min_value(self) -> int:
return -(1 << (self.width - 1)) if self.signed else 0
@property
def max_value(self) -> int:
if self.signed:
return (1 << (self.width - 1)) - 1
return self.modulus - 1
def wrap(self, raw: int) -> int:
v = raw % self.modulus
if self.signed and v >= (1 << (self.width - 1)):
v -= self.modulus
return v
def fits(self, raw: int) -> bool:
return self.min_value <= raw <= self.max_value
def is_bool(self) -> bool:
return self.width == 1 and not self.signed
def __repr__(self) -> str:
return self.name
__str__ = __repr__
def __hash__(self) -> int:
return hash((self.name, self.width, self.signed))
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Type)
and self.name == other.name
and self.width == other.width
and self.signed == other.signed
)
BOOL = Type("bool", 1, False)
int8 = INT8 = Type("int8", 8, True)
uint8 = UINT8 = Type("uint8", 8, False)
int16 = INT16 = Type("int16", 16, True)
uint16 = UINT16 = Type("uint16", 16, False)
int32 = INT32 = Type("int32", 32, True)
uint32 = UINT32 = Type("uint32", 32, False)
int64 = INT64 = Type("int64", 64, True)
uint64 = UINT64 = Type("uint64", 64, False)
_TYPES_BY_NAME: dict[str, Type] = {
t.name: t
for t in (BOOL, int8, uint8, int16, uint16, int32, uint32, int64, uint64)
}
_ACODE_IMPORTS = {
"bool": "BOOL",
"int8": "int8",
"uint8": "uint8",
"int16": "int16",
"uint16": "uint16",
"int32": "int32",
"uint32": "uint32",
"int64": "int64",
"uint64": "uint64",
}
def parse_type(name: str) -> Type:
try:
return _TYPES_BY_NAME[name]
except KeyError:
raise TypeError_(
f"unknown type {name!r}; known types: {', '.join(_TYPES_BY_NAME)}"
)
# Expressions
class Expr:
"""Immutable symbolic expression node carrying its resolved type."""
__slots__ = ("type",)
def __init__(self, ty: Type | None = None):
self.type = ty
def key(self) -> tuple:
raise NotImplementedError
def __hash__(self) -> int:
return hash(self.key())
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Expr)
and type(self) is type(other)
and self.key() == other.key()
)
def __repr__(self) -> str:
return self.sugar()
def sugar(self) -> str:
raise NotImplementedError
class Var(Expr):
"""A variable. Doubles as the pattern placeholder inside axiom LHS."""
__slots__ = ("name",)
def __init__(self, name: str, ty: Type | None = None):
super().__init__(ty)
self.name = name
def key(self):
t = self.type
return ("v", self.name, t.name if t else None)
def sugar(self) -> str:
return self.name
class Const(Expr):
"""A named symbolic constant (never substituted, part of the input)."""
__slots__ = ("name",)
def __init__(self, name: str, ty: Type | None = None):
super().__init__(ty)
self.name = name
def key(self):
t = self.type
return ("c", self.name, t.name if t else None)
def sugar(self) -> str:
return self.name
class Lit(Expr):
"""An integer literal.
``type`` may be ``None`` while the literal is still "adaptable": its type
(and so its wrap) is resolved from context during ripening.
"""
__slots__ = ("value",)
def __init__(self, value: int, ty: Type | None = None):
super().__init__(ty)
self.value = int(value)
def key(self):
t = self.type
return ("lit", self.value, t.name if t else None)
def sugar(self) -> str:
return str(self.value)
class Op(Expr):
__slots__ = ("args", "op")
def __init__(self, op: str, args: tuple[Expr, ...], ty: Type | None = None):
super().__init__(ty)
self.op = op
self.args = tuple(args)
def key(self):
t = self.type
return ("op", self.op, tuple(a.key() for a in self.args), t.name if t else None)
def sugar(self) -> str:
return f"{self.op}({', '.join(a.sugar() for a in self.args)})"
class Select(Expr):
__slots__ = ("cond", "else_expr", "then_expr")
def __init__(
self,
cond: Expr,
then_expr: Expr,
else_expr: Expr,
ty: Type | None = None,
):
super().__init__(ty)
self.cond = cond
self.then_expr = then_expr
self.else_expr = else_expr
def key(self):
t = self.type
return (
"sel",
self.cond.key(),
self.then_expr.key(),
self.else_expr.key(),
t.name if t else None,
)
def sugar(self) -> str:
return (
f"sel({self.cond.sugar()} ? {self.then_expr.sugar()}"
f" : {self.else_expr.sugar()})"
)
# Statements / blocks -- "two sequences of code"
class Stmt:
__slots__ = ()
class Assign(Stmt):
__slots__ = ("rhs", "var")
def __init__(self, var: Var, rhs: Expr):
if not isinstance(var, Var) or var.type is None:
raise TypeError_("assignment target must be a typed variable")
self.var = var
self.rhs = rhs
def __repr__(self) -> str:
return f"{self.var.name} = {self.rhs.sugar()}"
class Loop(Stmt):
"""Structured loop with a statically known or shared symbolic bound."""
__slots__ = ("body", "count")
def __init__(self, count: int | Expr, body: list[Stmt]):
if isinstance(count, int) and count < 0:
raise TypeError_("loop bound must be >= 0")
self.count = count
self.body = list(body)
def __repr__(self) -> str:
return f"loop({self.count}) {{ {self.body} }}"
class Nop(Stmt):
__slots__ = ()
def __repr__(self) -> str:
return "nop"
class Block:
__slots__ = ("name", "stmts")
def __init__(self, name: str = "block", stmts: list[Stmt] | None = None):
self.name = name
self.stmts = list(stmts or [])
def __repr__(self) -> str:
return f"Block({self.name!r}, {self.stmts})"
# Ripening -- type resolution ("resolvance") with literal adaptation
_DEFAULT_INT = int32
_BINARY_INT_OPS = {"add", "sub", "mul", "and", "or", "xor"}
_SHIFT_OPS = {"shl", "shru", "shrs"}
_DIV_OPS = {"divu", "divs", "remu", "rems"}
_CMP_OPS = {
"eq", "ne",
"ltu", "lteu", "gtu", "gteu",
"lts", "ltes", "gts", "gtes",
}
_UNARY_OPS = {"neg", "not"}
_CONV_OPS = {"extz", "exts", "trunc"}
_ALL_OPS = (
_BINARY_INT_OPS | _SHIFT_OPS | _DIV_OPS | _CMP_OPS | _UNARY_OPS | _CONV_OPS
)
_TRUE = Op("eq", (Lit(1), Lit(1)), BOOL)
_FALSE = Op("eq", (Lit(1), Lit(0)), BOOL)
def _truth(v: int) -> bool:
return v != 0
def _resolve_literal(raw: int, ty: Type) -> int:
return ty.wrap(raw)
def ripen(
expr: Expr,
expected: Type | None = None,
*,
top: bool = False,
env: Mapping[str, Any] | None = None,
) -> Expr:
"""Fully type-resolve an expression (bottom-up) into a typed tree.
Adaptable literals adopt ``expected`` (propagated top-down); where that is
unknown the sibling operand or ``int32`` decides. When ``top`` is set the
outermost literal must be representable in its type -- this is the
"data types control" guard that rejects silent narrowing on assignment.
"""
if isinstance(expr, (Var, Const)):
if env is not None and expr.name in env:
return env[expr.name][0]
ty = expr.type or expected or _DEFAULT_INT
if expr.type is not None:
return expr
# adaptable variable: adopt context (input/expected type, else int32)
return type(expr)(expr.name, ty)
if isinstance(expr, Lit):
if expr.type is not None:
return expr
ty = expected or _DEFAULT_INT
wrapped = _resolve_literal(expr.value, ty)
if top and not ty.fits(expr.value):
raise OverFlowError(
f"literal {expr.value} is not representable in {ty.name}"
)
return Lit(wrapped, ty)
if isinstance(expr, Select):
cond = ripen(expr.cond, BOOL, env=env)
if cond.type is not None and not cond.type.is_bool():
raise TypeError_("select condition must be of type bool")
if isinstance(cond, Lit) and cond.type is not None:
cond = Lit(_truth(cond.value), BOOL)
a = ripen(expr.then_expr, expected, env=env)
b = ripen(expr.else_expr, expected, env=env)
_require_same_type(a, b, "select branches")
return Select(cond, a, b, a.type)
if isinstance(expr, Op):
return _ripen_op(expr, expected, top=top, env=env)
raise TypeError_(f"cannot ripen {expr!r}")
def _require_same_type(a: Expr, b: Expr, what: str) -> None:
ta, tb = a.type, b.type
if ta is not None and tb is not None and ta != tb:
raise TypeError_(f"{what} have different types: {ta} vs {tb}")
def _effective_type(arg: Expr, env: Mapping[str, Any] | None) -> Type | None:
if arg.type is not None:
return arg.type
if isinstance(arg, (Var, Const)) and env is not None and arg.name in env:
return env[arg.name][1]
if isinstance(arg, Op):
# a compound expression built raw carries no type yet; look inside
# (e.g. shrs(add(x, ...), k) must see that x is int8, not default
# to int32 and then collide with the env binding)
for a in arg.args:
t = _effective_type(a, env)
if t is not None:
return t
return None
def _pick_type(
*args: Expr,
expected: Type | None,
what: str,
env: Mapping[str, Any] | None = None,
) -> Type:
if expected is not None:
return expected
for a in args:
t = _effective_type(a, env)
if t is not None:
return t
return _DEFAULT_INT
def _ripen_op(expr: Op, expected: Type | None, *, top: bool, env) -> Expr:
op = expr.op
if op not in _ALL_OPS:
raise TypeError_(f"unknown operation {op!r}")
if op in _BINARY_INT_OPS:
args = list(expr.args)
if len(args) != 2:
raise TypeError_(f"{op} takes exactly two arguments")
ty = _pick_type(args[0], args[1], expected=expected, what=op, env=env)
a = ripen(args[0], ty, env=env)
b = ripen(args[1], ty, env=env)
_require_same_type(a, b, f"operands of {op}")
return Op(op, (a, b), ty)
if op in _SHIFT_OPS:
lhs, amount = expr.args
ty = _pick_type(lhs, expected=expected, what=op, env=env)
ra = ripen(lhs, ty, env=env)
rn = ripen(amount, int32, env=env)
if rn.type is not None and rn.type.is_bool():
raise TypeError_(f"shift amount for {op} must be an integer, not bool")
return Op(op, (ra, rn), ty)
if op in _DIV_OPS:
args = list(expr.args)
ty = _pick_type(args[0], args[1], expected=expected, what=op, env=env)
a = ripen(args[0], ty, env=env)
b = ripen(args[1], ty, env=env)
_require_same_type(a, b, f"operands of {op}")
return Op(op, (a, b), ty)
if op in _CMP_OPS:
a = ripen(expr.args[0], expected, env=env)
b = ripen(expr.args[1], expected, env=env)
_require_same_type(a, b, f"operands of {op}")
return Op(op, (a, b), BOOL)
if op in _UNARY_OPS:
a = ripen(expr.args[0], expected, env=env)
if op == "neg" and a.type is not None and a.type.is_bool():
raise TypeError_("neg is not defined on bool")
if op == "not" and a.type is not None and a.type.is_bool():
return Op("not", (a,), a.type)
return Op(op, (a,), a.type)
if op in _CONV_OPS:
a = ripen(expr.args[0], None, env=env)
ty = expr.type or expected or a.type or _DEFAULT_INT
if a.type is not None and a.type.width > ty.width:
raise TypeError_(
f"{op} cannot widen {a.type.name} to the smaller {ty.name}"
)
return Op(op, (a,), ty)
raise TypeError_(f"cannot ripen {op}")
# Concrete evaluation (bit-for-bit, wrapping to the operand type)
def eval_c(expr: Expr) -> int:
"""Evaluate a fully ripened expression over exact two's-complement values."""
if isinstance(expr, Lit):
return expr.value
if isinstance(expr, (Var, Const)):
raise TypeError_(f"cannot evaluate symbolic {expr.sugar()!r}")
if isinstance(expr, Select):
return eval_c(expr.then_expr) if _truth(eval_c(expr.cond)) else eval_c(expr.else_expr)
if not isinstance(expr, Op):
raise TypeError_(f"cannot evaluate {expr!r}")
op, args = expr.op, expr.args
ty = expr.type
vals = [eval_c(a) for a in args]
x, y = (vals[0], vals[1]) if len(vals) == 2 else (vals[0], None)
def total(v: int) -> int:
return v if (ty is not None and ty.signed) else (v % ty.modulus if ty else v)
if op == "add":
r = x + y
elif op == "sub":
r = x - y
elif op == "mul":
r = x * y
elif op == "and":
r = x & y
elif op == "or":
r = x | y
elif op == "xor":
r = x ^ y
elif op == "neg":
r = -x
elif op == "not":
r = ~x
elif op == "shl":
r = x << y
elif op == "shru":
r = (x % ty.modulus) >> y
elif op == "shrs":
r = x >> y
elif op == "divu":
r = (x % ty.modulus) // (y % ty.modulus)
elif op == "divs":
# signed division truncates toward zero (C/RISC-V/WASM/x86), NOT
# Python's floor division
q = abs(x) // abs(y)
r = -q if (x < 0) != (y < 0) else q
elif op == "remu":
r = (x % ty.modulus) % (y % ty.modulus)
elif op == "rems":
# signed remainder takes the sign of the dividend: x - y*divs(x,y)
q = abs(x) // abs(y)
if (x < 0) != (y < 0):
q = -q
r = x - y * q
elif op == "eq":
return int(total(x) == total(y))
elif op == "ne":
return int(total(x) != total(y))
elif op == "ltu":
return int((x % ty.modulus) < (y % ty.modulus))
elif op == "lteu":
return int((x % ty.modulus) <= (y % ty.modulus))
elif op == "gtu":
return int((x % ty.modulus) > (y % ty.modulus))
elif op == "gteu":
return int((x % ty.modulus) >= (y % ty.modulus))
elif op == "lts":
return int(x < y)
elif op == "ltes":
return int(x <= y)
elif op == "gts":
return int(x > y)
elif op == "gtes":
return int(x >= y)
elif op == "extz":
return x % (1 << args[0].type.width)
elif op == "exts":
return x
elif op == "trunc":
return x % (1 << ty.width)
else:
raise TypeError_(f"cannot evaluate {op}")
return ty.wrap(r)
def free_vars(expr: Expr) -> set[str]:
got: set[str] = set()
_collect_vars(expr, got)
return got
def _collect_vars(expr: Expr, got: set[str]) -> None:
if isinstance(expr, (Var, Const)):
got.add(expr.name)
elif isinstance(expr, Op):
for a in expr.args:
_collect_vars(a, got)
elif isinstance(expr, Select):
_collect_vars(expr.cond, got)
_collect_vars(expr.then_expr, got)
_collect_vars(expr.else_expr, got)
def substitute(expr: Expr, subs: Mapping[str, Expr]) -> Expr:
if isinstance(expr, (Var, Const)):
return subs.get(expr.name, expr)
if isinstance(expr, Lit):
return expr
if isinstance(expr, Op):
return Op(expr.op, tuple(substitute(a, subs) for a in expr.args), expr.type)
if isinstance(expr, Select):
return Select(
substitute(expr.cond, subs),
substitute(expr.then_expr, subs),
substitute(expr.else_expr, subs),
expr.type,
)
return expr
# Definedness / "proper bit shifts check"
def check_defined(expr: Expr) -> list[tuple[str, str]]:
"""Return (severity, message) issues: ('reject', ...) or ('cannot', ...).
- ``shl``/``shru``/``shrs``: a literal shift amount outside ``[0, width)``
is definitely undefined -> ``reject``; a symbolic amount cannot be
verified -> ``cannot``.
- division/remainder by a literal zero is definitely undefined -> reject;
a symbolic divisor cannot be verified -> cannot.
"""
issues: list[tuple[str, str]] = []
def walk(e: Expr) -> None:
if isinstance(e, Op):
if e.op in _SHIFT_OPS:
lhs, n = e.args
width = lhs.type.width if lhs.type else 0
if isinstance(n, Lit):
v = n.value
if not (0 <= v < width):
issues.append(
("reject",
f"{e.op} by {v} on {width}-bit value is undefined"))
else:
issues.append(
("cannot",
f"{e.op} amount is symbolic, range not verified"))
elif e.op in _DIV_OPS:
_, d = e.args
if isinstance(d, Lit) and d.value == 0:
issues.append(("reject", f"division by literal zero in {e.op}"))
elif not isinstance(d, Lit):
issues.append(
("cannot", f"divisor of {e.op} is symbolic, may be zero"))
for a in e.args:
walk(a)
elif isinstance(e, Select):
walk(e.cond)
walk(e.then_expr)
walk(e.else_expr)
walk(expr)
return issues
# Normalization -- sound algebra + registered axioms
_ACOMM = {"add", "mul", "and", "or", "xor"}
def builtin_rewrite(e: Expr) -> Expr | None:
"""One sound algebraic rewrite at the root (args already normalized).
Every rule here is provably sound under two's-complement wraparound of
the operand types; no rule hides undefined behaviour.
"""
if not isinstance(e, Op):
return None
op, ty = e.op, e.type
args = e.args
if op in _ACOMM and len(args) == 2:
a, b = args
if isinstance(a, Lit) and isinstance(b, Lit) and ty is not None:
return Lit(_fold(op, a.value, b.value, ty), ty)
if a.key() > b.key():
return Op(op, (b, a), ty)
if op == "add":
if isinstance(b, Lit) and b.value == 0:
return a
if isinstance(a, Lit) and a.value == 0:
return b
if isinstance(a, Op) and a.op == "neg" and b == a.args[0]:
return Lit(0, ty)
if isinstance(b, Op) and b.op == "neg" and a == b.args[0]:
return Lit(0, ty)
if op == "mul":
if isinstance(b, Lit) and b.value == 1:
return a
if isinstance(b, Lit) and b.value == 0:
return Lit(0, ty)
if op == "and":
if isinstance(b, Lit) and b.value == 0:
return Lit(0, ty)
if isinstance(b, Lit) and b.value == ty.mask:
return a
if a == b:
return a
if op == "or":
if isinstance(b, Lit) and b.value == 0:
return a
if isinstance(b, Lit) and b.value == ty.mask:
return b
if a == b:
return a
if op == "xor":
if isinstance(b, Lit) and b.value == 0:
return a
if a == b:
return Lit(0, ty)
return None
if op in {"add", "mul", "and", "or", "xor"}:
return None
if op == "sub":
a, b = args
if isinstance(a, Lit) and isinstance(b, Lit) and ty is not None:
return Lit(_fold("sub", a.value, b.value, ty), ty)
if isinstance(b, Lit) and b.value == 0:
return a
if a == b:
return Lit(0, ty)
if isinstance(a, Lit) and a.value == 0 and ty is not None:
return Op("neg", (b,), ty)
return None
if op == "neg":
(a,) = args
if isinstance(a, Lit) and ty is not None:
return Lit(ty.wrap(-a.value), ty)
if isinstance(a, Op) and a.op == "neg":
return a.args[0]
return None
if op == "not":
(a,) = args
if isinstance(a, Lit) and ty is not None:
return Lit(ty.wrap(~a.value), ty)
if isinstance(a, Op) and a.op == "not":
return a.args[0]
return None
if op in _SHIFT_OPS:
x, n = args
if isinstance(n, Lit):
sh = n.value
width = x.type.width if x.type else 0
if sh == 0:
return x
if not (0 <= sh < width):
raise UndefinedError(
f"shift {op} by {sh} on {width}-bit value is undefined")
if op == "shl":
# x << n == x * 2**n (mod 2**w) holds unconditionally here.
return Op("mul", (x, Lit(x.type.wrap(pow(2, sh)), x.type)), x.type)
if isinstance(x, Lit):
return Lit(_fold(op, x.value, sh, x.type), x.type)
return None
if op in _DIV_OPS:
a, b = args
if isinstance(a, Lit) and isinstance(b, Lit) and ty is not None:
if b.value == 0:
raise UndefinedError("division by literal zero")
return Lit(_fold(op, a.value, b.value, ty), ty)
if isinstance(b, Lit):
if b.value == 1:
return a
if op in {"remu", "rems"} and b.value == 1:
return Lit(0, ty)
return None
if op in _CMP_OPS:
a, b = args
if isinstance(a, Lit) and isinstance(b, Lit) and ty is not None:
t = a.type
va = a.value % t.modulus if not t.signed else a.value
vb = b.value % t.modulus if not t.signed else b.value
res = _cmp(op, va, vb, t)
return Lit(int(res), BOOL)
if op == "eq" and a == b:
return Lit(1, BOOL)
if op == "ne" and a == b:
return Lit(0, BOOL)
return None
if op in _CONV_OPS:
(a,) = args
if isinstance(a, Lit) and ty is not None:
if op == "extz":
# zero-extension: keep the source's unsigned bit pattern,
# widened into the destination type.
return Lit(a.value % (1 << a.type.width), ty)
if op == "exts":
if ty.signed:
# sign-extension preserves the signed value.
return Lit(a.value, ty)
return Lit(a.value % (1 << ty.width), ty)
return Lit(a.value % (1 << ty.width), ty)
if a.type == ty:
return a
return None
return None
def _fold(op: str, x: int, y: int, ty: Type) -> int:
"""Fold a literal application to a canonical machine value.
Every result is wrapped into the operand type's canonical range (for
signed types that is ``[-2**(w-1), 2**(w-1)-1]``), and ``divs``/``rems``
use the kernel's explicit machine semantics (truncate toward zero,
remainder sign follows the dividend) -- never Python's floor behavior.
"""
if op == "add":
r = x + y
elif op == "sub":
r = x - y
elif op == "mul":
r = x * y
elif op == "and":
r = x & y
elif op == "or":
r = x | y
elif op == "xor":
r = x ^ y
elif op == "shru":
r = (x % ty.modulus) >> y
elif op == "shrs":
r = x >> y
elif op == "shl":
r = x << y
elif op == "divu":
r = (x % ty.modulus) // (y % ty.modulus)
elif op == "divs":
q = abs(x) // abs(y)
r = -q if (x < 0) != (y < 0) else q
elif op == "remu":
r = (x % ty.modulus) % (y % ty.modulus)
elif op == "rems":
q = abs(x) // abs(y)
if (x < 0) != (y < 0):
q = -q
r = x - y * q
else:
raise TypeError_(f"unexpected fold {op}")
return ty.wrap(r)
def _cmp(op: str, x: int, y: int, t: Type) -> bool:
if op == "eq":
return x == y
if op == "ne":
return x != y
if not t.signed:
if op == "ltu":
return x < y
if op == "lteu":
return x <= y
if op == "gtu":
return x > y
if op == "gteu":
return x >= y
else:
if op == "lts":
return x < y
if op == "ltes":
return x <= y
if op == "gts":
return x > y
if op == "gtes":
return x >= y
raise TypeError_(f"mismatched comparison {op} for {t.name}")
# Proof result
@dataclass
class Proof:
"""Outcome of a kernel check.
``status`` is one of ``"proven"``, ``"not_proven"``, ``"rejected"``.
* ``proven`` -- asserted only when the kernel has an exact argument.
* ``not_proven``-- the kernel could not establish the claim; never an
equality, so it can never corrupt a proof chain.
* ``rejected`` -- the claim is ill-formed (type error, UB, unrepresentable
literal, undefined read, ...). Rejection is final.
"""
status: str = "not_proven"
kind: str = "equivalence"
reason: str = ""
lhs: Any = None
rhs: Any = None
axioms_used: tuple = ()
derived_axioms: tuple = ()
#: How exactly the ``axioms_used`` were checked: ``"complete"`` (every
#: domain decided, bit-exact), ``"sampled"`` (the axioms were spot-checked
#: but the domain is too large to enumerate) or ``None`` (no axiom was
#: consulted, or the caller opted out of checking).
checked: str | None = None
def __bool__(self) -> bool:
return self.status == "proven"
def __repr__(self) -> str:
return (
f"<OProof {self.kind} {self.status}"
+ (f": {self.reason}" if self.reason else "")
+ ">"
)
PROVEN = Proof("proven")
# Symbolic execution of blocks
class _SymbolicLoop(Exception):
"""Raised internally when a loop's trip count is not statically known."""
class _Cell(NamedTuple):
"""One variable's value during symbolic execution.
``norm`` is the normalized (canonical) expression, ``ty`` its type, and
``raw`` the pre-normalization ripened expression (kept so generalization
can lift the concrete constants the programmer actually wrote).
"""
norm: Expr
ty: Type
raw: Expr
State = dict[str, _Cell]
def _static_int(v: Any) -> int | None:
if isinstance(v, int):
return v
if isinstance(v, Lit):
return v.value
return None
def _interface(block: Block) -> dict[str, Type]:
"""Read-before-write variables are the interface (inputs) of a block."""
inputs: dict[str, Type] = {}
written: set[str] = set()
def scan_expr(e: Expr) -> None:
if isinstance(e, (Var, Const)):
if e.name not in written and e.name not in inputs and e.type is not None:
inputs[e.name] = e.type
elif isinstance(e, Op):
for a in e.args:
scan_expr(a)
elif isinstance(e, Select):
scan_expr(e.cond)
scan_expr(e.then_expr)
scan_expr(e.else_expr)
def scan(stmts: list[Stmt]) -> None:
for st in stmts:
if isinstance(st, Assign):
scan_expr(st.rhs)
written.add(st.var.name)
elif isinstance(st, Loop):
if isinstance(st.count, Expr):
scan_expr(st.count)
scan(st.body)
elif isinstance(st, Nop):
pass
scan(block.stmts)
return inputs
def _writes(block: Block) -> set[str]: