omega-bridge
Omega-first language interoperability: checked conversion backends and native language bindings
Brought by drakestapleton
GitHub aien-dev/omega-bridge#56 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/omega-bridge/patches/645bba276ba0e557.bundle -o 645bba276ba0e557.bundle git fetch 645bba276ba0e557.bundle refs/pull/56/head
Provenance
github-import 1
aien-dev/omega-bridge
56
f9f1f7cf7abb200f34fab7244c353141938a24c2
{"kind":"github-import","owner":"aien-dev","repo":"omega-bridge","number":56,"url":"https://github.com/aien-dev/omega-bridge/pull/56","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:01Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/AGENTS.md b/AGENTS.md index 6bacb03..ad57a4d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ Shared rules: read https://www.aienos.com/agents/RULES.md first. This file adds - `tests/`: Python test harness (infrastructure only), fixtures, refusal cases, native callers in six languages, GPU adapter protocol tests. - `conformance/`: separate-process Omega versus Modular MAX harness. `evidence/`: raw logs and result manifests. - `pytorch/`: `torch.compile` backend `"omega"` (docs/OMEGA-TORCH.md). Kernels are `.om` (`pytorch/kernels/`); `pytorch/omega_torch/` is interim Python glue that registers the backend, walks the FX graph and calls units through the native ABI. It must never compute a tensor value; an unsupported op raises, and eager fallback only happens for ops the caller names, counted. -- No compiler binary is stored here. Python/C input conversion is not implemented. Text constants, floats, heap operations and other target languages are refused by the C/Python converters. +- No compiler binary is stored here. Python/C input conversion is not implemented. Text constants, heap operations and other target languages are refused by the C/Python converters. Floats are refused by the baseline `tools/bridge` and by Python; only the additive seeded C frontend (`tools/bridge-seeded c`) lowers internal f32/f64 scalars, float constants and float ops (see `docs/CAPABILITIES.md`; run `python3 tests/seeded_float.py`). ## Installation diff --git a/README.md b/README.md index fef54ee..ab1835d 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Run real C and Python application callers: quiet-build python3 tests/attachments.py ``` -See [supported features and limits](docs/CAPABILITIES.md), [caller ABI and ownership](docs/ABI.md), [design and study decisions](docs/DESIGN.md), and [provenance](docs/PROVENANCE.md). Text constants, floats, heap operations and other target languages are explicitly unsupported by the C/Python converters. GPU interoperability is a separate, opt-in adapter boundary (it converts no host program): see [GPU adapter](docs/GPU-ADAPTER.md) and the [support matrix](docs/GPU-SUPPORT-MATRIX.md). Python/C input conversion is not implemented. The Python test harness is infrastructure; all conversion logic and both runtime emitters are in [src/toc.om](src/toc.om). +See [supported features and limits](docs/CAPABILITIES.md), [caller ABI and ownership](docs/ABI.md), [design and study decisions](docs/DESIGN.md), and [provenance](docs/PROVENANCE.md). Text constants, heap operations and other target languages are explicitly unsupported by the C/Python converters; floats are refused except internal f32/f64 scalars, constants and operators in the additive seeded C frontend (`tools/bridge-seeded c`, checked by `tests/seeded_float.py`). GPU interoperability is a separate, opt-in adapter boundary (it converts no host program): see [GPU adapter](docs/GPU-ADAPTER.md) and the [support matrix](docs/GPU-SUPPORT-MATRIX.md). Python/C input conversion is not implemented. The Python test harness is infrastructure; all conversion logic and both runtime emitters are in [src/toc.om](src/toc.om). PyTorch: `torch.compile(model, backend="omega")` runs a small set of float32 core-ATen ops (mm, addmm, 2-D transpose, add, relu, softmax) on CPU through Omega-generated AArch64 kernels called via the native call ABI, and refuses everything else. The Python under `pytorch/omega_torch/` is interim glue that computes no tensor value. Exercised on CPU against PyTorch eager only; see [docs/OMEGA-TORCH.md](docs/OMEGA-TORCH.md). diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index 7649c45..60a84ba 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -48,7 +48,7 @@ narrowing functions become `volatile`, the `o_get`/`o_io`/`o_buf` helpers take suites (`tools/test.sh`, seeded, seeded-float, freestanding) are unchanged and pass; byte-identical output to the previous `tools/bridge` is not claimed. -The additive mode accepts at most 32 numeric literal constants, 512 functions, +The additive mode accepts at most 1024 numeric constants (integer, `f32` or `f64`; error 14 beyond), 512 functions, six parameters per function, function names up to the frontend's 63-byte limit (other names retain its limits), fixed view/edit shapes up to 16,777,216 elements, explicit `view`/`edit` call prefixes and bounded-loop @@ -60,15 +60,23 @@ Checked arithmetic, bounds, alias refusals, call budget and no-heap restrictions remain enforced. Text constants and external calls remain unsupported. These are implementation bounds, not performance measurements. -Seeded C permits internal binary32 scalars for explicit `f32` literals, -`bitcast uint`/`bitcast f32`, `fabs`, multiplication and ordered `le`. -Decimal conversion reuses the pinned Omega e5b32567 implementation; storage is -canonical IEEE-754 bits and C arithmetic uses binary32 intermediates under the -host's default floating-point environment. Fast-math and incompatible binary32 -implementations are refused at C compilation. Public floating-point -parameters/results, floating-point arrays, numeric float casts and other -float operators remain refused, as do all Python and baseline float inputs. -No implicit f64 or approximate integer substitute is emitted. +Seeded C permits internal binary32 (`f32`) and binary64 (`f64`) scalars: unsuffixed +float constants (`const K f64 0.1`; a suffixed literal is error 16 and an integer literal error 16, +as in omc), typed or suffixed float literals in expressions, `add`/`sub`/`mul`/`div`, `neg`, +`fabs`, ordered comparisons and `eq`/`ne`, int<->float and f32<->f64 conversions (an integer +literal under a float conversion is typed `long`, as in omc), and same-width bitcasts +between `f32` and `uint` and between `f64` and `ulong`/`long`. Operations go through `o_fp`/`o_fcv` +with explicit ARM (AArch64) NaN propagation and FCVTZS/FCVTZU saturation, so results match the +seeded omc's AArch64 bits. Decimal conversion reuses the pinned Omega e5b32567 implementation, +including its limits: at most 2^63-1 significant digits (error 8) and overflow to infinity +refused (error 8). That conversion is not always correctly rounded (aien-dev/omega-mv#1024); +the converter reproduces omc's bits, and `tests/seeded_float.py` pins the two known misrounded +literals. Storage is canonical IEEE-754 bits. Fast-math and incompatible binary32/binary64 +implementations are refused at C compilation. Where omc refuses a float program the converter +reports omc's error code; programs omc accepts but this target does not lower (public float +parameters/results, float arrays, float shift counts, untyped float literals as a left +operand, `int`/`long`-with-`f32` bitcasts) are refused with error 24, as are all Python and +baseline float inputs. No approximate integer substitute is emitted. Function units export only their final function, using `omega_NAME`. `h` validates every function body through the same emitter before emitting the @@ -95,9 +103,11 @@ ABI, and includes wrong-seed and arithmetic-emitter negative controls. No device qualification is implied. `python3 tests/seeded_float.py` compares the seeded executable and generated C -byte-for-byte over zero, subnormal, normal, overflow, infinity and NaN inputs. +byte-for-byte (host and x86-64 under qemu) over zero, subnormal, normal, overflow, infinity +and NaN inputs for f32 and f64, 132 constants against an exact round-to-nearest-even oracle +(one-ulp mutant detected), and converter refusal codes cross-checked against omc. It includes baseline/Python, public-float, array, numeric-cast, unsupported-op, -header-validation and fast-math refusal controls. These are host results only. +header-validation and fast-math refusal controls. These are host/emulator results only. ## Portable import-free scalar profile diff --git a/src/toc.om b/src/toc.om index 827ab91..73219b8 100644 --- a/src/toc.om +++ b/src/toc.om @@ -60,11 +60,11 @@ global loopty ulong 32 note Extended, separately seed-checked mode; baseline capability limits remain unchanged. global seeded ulong 1 global nc ulong 1 -global co_off ulong 32 -global co_nl ulong 32 -global co_ty ulong 32 -global co_val ulong 32 -global co_neg ulong 32 +global co_off ulong 1024 +global co_nl ulong 1024 +global co_ty ulong 1024 +global co_val ulong 1024 +global co_neg ulong 1024 global fsgn ulong 1 global fnd ulong 1 global fp10 long 1 @@ -82,13 +82,15 @@ global fg_stk ulong 1 global fg_low ulong 1 global fg_ov ulong 1 text fword "f32" +text f64word "f64" text bcword "bitcast" text absword "fabs" -text fcall ";o_f32(" +text fcall ";o_fp(" +text fcvcall "o_fcv(" text cntword "continue" text cntc "continue;\n" text volword "volatile uint64_t " -text frun "#include <float.h>\n#include <fenv.h>\n#if FLT_RADIX != 2 || FLT_MANT_DIG != 24 || FLT_MAX_EXP != 128 || FLT_EVAL_METHOD != 0\n#error unsupported binary32 environment\n#endif\n#if defined(__FAST_MATH__)\n#error fast math is not a supported Omega environment\n#endif\nstatic uint64_t o_f32(unsigned op,uint64_t a,uint64_t b){uint32_t ua=(uint32_t)a,ub=(uint32_t)b,ur;float x,y;__builtin_memcpy(&x,&ua,4);__builtin_memcpy(&y,&ub,4);if(op==1)return ua&UINT32_C(0x7fffffff);if(op==2){volatile float z=x*y;__builtin_memcpy(&ur,(const void*)&z,4);return ur;}return x<=y;}\n" +text frun "#include <float.h>\n#include <fenv.h>\n#if FLT_RADIX != 2 || FLT_MANT_DIG != 24 || FLT_MAX_EXP != 128 || DBL_MANT_DIG != 53 || DBL_MAX_EXP != 1024 || FLT_EVAL_METHOD != 0\n#error unsupported binary32 or binary64 environment\n#endif\n#if defined(__FAST_MATH__)\n#error fast math is not a supported Omega environment\n#endif\nstatic int o_fnan(unsigned t,uint64_t a){return t==11?((a>>23&255)==255&&(a&UINT64_C(0x7fffff))!=0):((a>>52&2047)==2047&&(a&UINT64_C(0xfffffffffffff))!=0);}\nstatic uint64_t o_fpn(unsigned t,uint64_t a,uint64_t b,uint64_t r){uint64_t q=t==11?UINT64_C(0x400000):UINT64_C(0x8000000000000);if(!o_fnan(t,r))return r;if(o_fnan(t,a)&&!(a&q))return a|q;if(o_fnan(t,b)&&!(b&q))return b|q;if(o_fnan(t,a))return a;if(o_fnan(t,b))return b;return t==11?UINT64_C(0x7fc00000):UINT64_C(0x7ff8000000000000);}\nstatic uint64_t o_fp(unsigned op,unsigned t,uint64_t a,uint64_t b){if(t==11){uint32_t ua=(uint32_t)a,ub=(uint32_t)b,ur;float x,y;volatile float z;__builtin_memcpy(&x,&ua,4);__builtin_memcpy(&y,&ub,4);switch(op){case 1:z=x+y;break;case 2:z=x-y;break;case 3:z=x*y;break;case 4:z=x/y;break;case 6:return x==y;case 7:return x!=y;case 8:return x<y;case 9:return x<=y;case 10:return x>y;case 11:return x>=y;case 17:return ua^UINT32_C(0x80000000);case 19:return ua&UINT32_C(0x7fffffff);default:__builtin_trap();}__builtin_memcpy(&ur,(const void*)&z,4);return o_fpn(11,ua,ub,ur);}uint64_t ur;double x,y;volatile double z;__builtin_memcpy(&x,&a,8);__builtin_memcpy(&y,&b,8);switch(op){case 1:z=x+y;break;case 2:z=x-y;break;case 3:z=x*y;break;case 4:z=x/y;break;case 6:return x==y;case 7:return x!=y;case 8:return x<y;case 9:return x<=y;case 10:return x>y;case 11:return x>=y;case 17:return a^UINT64_C(0x8000000000000000);case 19:return a&UINT64_C(0x7fffffffffffffff);default:__builtin_trap();}__builtin_memcpy(&ur,(const void*)&z,8);return o_fpn(12,a,b,ur);}\nstatic uint64_t o_fcv(unsigned t,unsigned s,uint64_t a){uint32_t u=(uint32_t)a;float f;double x;if(s==t)return a;if(s<11){if(t==11){volatile float z=s>=6?(float)(int64_t)a:(float)a;__builtin_memcpy(&u,(const void*)&z,4);return u;}volatile double z=s>=6?(double)(int64_t)a:(double)a;__builtin_memcpy(&a,(const void*)&z,8);return a;}if(t==12){if(o_fnan(11,a))return (uint64_t)(u>>31)<<63|UINT64_C(0x7ff8000000000000)|(uint64_t)(u&UINT32_C(0x7fffff))<<29;__builtin_memcpy(&f,&u,4);volatile double z=f;__builtin_memcpy(&a,(const void*)&z,8);return a;}if(t==11){if(o_fnan(12,a))return (a>>63)<<31|UINT64_C(0x7fc00000)|(a>>29&UINT64_C(0x3fffff));__builtin_memcpy(&x,&a,8);volatile float z=(float)x;__builtin_memcpy(&u,(const void*)&z,4);return u;}if(s==11){__builtin_memcpy(&f,&u,4);x=f;}else __builtin_memcpy(&x,&a,8);if(x!=x)return 0;unsigned w=o_width(t);if(t>=6){double m=(double)((uint64_t)1<<(w-1));if(x>=m)return ((uint64_t)1<<(w-1))-1;if(x<-m)return (uint64_t)0-((uint64_t)1<<(w-1));return (uint64_t)(int64_t)x;}if(x<1.0)return 0;if(x>=(w==64?18446744073709551616.0:(double)((uint64_t)1<<w)))return w==64?UINT64_MAX:((uint64_t)1<<w)-1;return (uint64_t)x;}\n" text cword "const" text bword "break" text breakc "break;\n" @@ -437,9 +439,13 @@ end fn ty_of w ulong to ulong if and eq get seeded 0 1 eq get target 0 0 -if eq floatkw 1 +fk = floatkw +if eq fk 1 ret 11 end +if eq fk 4 +ret 12 +end end if eq w 1819242338 ret 1 @@ -544,7 +550,7 @@ ret i end i = add i 1 end -ret 99 +ret 4096 end note A length is a literal or a previously checked unsigned numeric constant. @@ -553,7 +559,7 @@ if eq get tk 0 2 ret get tw 0 end c = constof -if eq c 99 +if eq c 4096 fail 16 end if ne get co_ty c 5 @@ -568,10 +574,10 @@ if ne get tk 0 1 fail 16 end i = get nc 0 -if ge i 32 +if ge i 1024 fail 14 end -if ne constof 99 +if ne constof 4096 fail 10 end put co_off i get ts 0 @@ -582,9 +588,28 @@ if eq t 0 fail 7 end tok +if eq get tk 0 4 +if eq isflt t 0 +fail 16 +end +fparse get ts 0 get tl 0 +note omc e5b32567 s_const takes only an unsuffixed float literal (error 16 for 1.5f64 too). +if ne get fsuf 0 0 +fail 16 +end +put co_ty i t +put co_val i fbits sub t 1 +put co_neg i 0 +put nc 0 add i 1 +ret +end if ne get tk 0 2 fail 24 end +note omc: an integer literal under a float constant type is error 16. +if eq isflt t 1 +fail 16 +end negative = ulong 0 if eq get src get ts 0 45 negative = 1 @@ -678,7 +703,7 @@ end if gt pk 0 tok pty = ty_of get tw 0 -if eq pty 11 +if eq isflt pty 1 fail 24 end if eq pty 0 @@ -732,7 +757,7 @@ put g_off i get ts 0 put g_nl i get tl 0 tok ty = ty_of get tw 0 -if eq ty 11 +if eq isflt ty 1 fail 24 end if eq ty 0 @@ -1863,6 +1888,10 @@ ret 64 end fn checknum n ulong t ulong to void +note omc: an untyped integer literal where a float is required is mixing (error 7). +if eq isflt t 1 +fail 7 +end v = get nv n isneg = get nb n w = width t @@ -1950,10 +1979,18 @@ if or eq get seeded 0 0 ne get target 0 0 fail 24 end fparse get ts 0 get tl 0 -if ne get fsuf 0 1 +t = ulong 0 +if eq get fsuf 0 0 +if eq isflt exp 1 +t = exp +end +else +t = add get fsuf 0 10 +end +if eq t 0 fail 24 end -ret node 1 11 0 0 fbits 10 +ret node 1 t 0 0 fbits sub t 1 end if eq get tk 0 2 negative = ulong 0 @@ -1961,7 +1998,9 @@ if eq get src get ts 0 45 negative = 1 end n = node 1 0 0 negative get tw 0 -if gt exp 0 +note An integer literal under a float expectation stays untyped: a conversion types it as long +note (omc: SCVTF, error 8 beyond long), an operand context refuses it through checknum (error 7). +if and gt exp 0 eq isflt exp 0 checknum n exp end ret n @@ -1979,17 +2018,32 @@ ret node 1 1 0 0 bv end t = ty_of w if gt t 0 -if eq t 11 -fail 24 -end -a = expr 0 -if eq get nt a 11 -fail 24 +bt = ulong 0 +if eq isflt t 1 +bt = t end -if eq get nt a 0 +a = expr bt +at = get nt a +if eq at 0 +if eq isflt t 1 +checknum a 9 +else checknum a t ret a end +end +if or eq isflt t 1 eq isflt at 1 +note omc: bool of a float is error 9, a float of a bool is error 7. +if eq t 1 +fail 9 +end +if eq at 1 +fail 7 +end +if eq at t +ret a +end +end ret node 4 t a 0 0 end if and eq get seeded 0 1 eq get target 0 0 @@ -1997,20 +2051,43 @@ fk = floatkw if eq fk 2 tok bt = ty_of get tw 0 -if and ne bt 4 ne bt 11 -fail 24 -end aa = expr 0 at = get nt aa -if not or and eq bt 4 eq at 11 and eq bt 11 eq at 4 +io = ulong 0 +if or and eq bt 4 eq at 11 and eq bt 11 eq at 4 +io = 1 +end +if and eq bt 12 or eq at 5 eq at 9 +io = 1 +end +if and eq at 12 or eq bt 5 eq bt 9 +io = 1 +end +if eq io 0 +note omc: a bitcast across widths or with a bool is error 7; a same-width pair the C target +note does not lower (int/long with a float) is a capability refusal. +wb = width bt +if eq bt 11 +wb = 32 +end +wa = width at +if eq at 11 +wa = 32 +end +if or ne wb wa or eq bt 1 eq at 1 +fail 7 +end fail 24 end ret node 9 bt aa 0 0 end if eq fk 3 -aa = expr 11 -expect aa 11 -ret node 10 11 aa 0 1 +aa = expr 0 +at = get nt aa +if eq isflt at 0 +fail 7 +end +ret node 10 at aa 0 19 end end if eq w 7628135 @@ -2074,7 +2151,7 @@ if gt op 0 a = expr 0 b = ulong 0 if lt op 17 -b = expr 0 +b = expr mul isflt get nt a get nt a if and eq get nt a 0 eq get nt b 0 fail 11 end @@ -2095,10 +2172,19 @@ fail 11 end end t = get nt a -if eq t 11 -if and ne op 3 ne op 9 +if eq isflt t 1 +if or eq op 5 and ge op 12 ne op 17 +fail 7 +end +end +if and eq isflt t 0 lt op 17 +if eq isflt get nt b 1 +note omc accepts a float shift count; this converter does not lower it. +if or eq op 15 eq op 16 fail 24 end +fail 7 +end end rt = t if and ge op 6 le op 11 @@ -2109,7 +2195,7 @@ put nx n t ret n end c = constof -if ne c 99 +if ne c 4096 ret node 1 get co_ty c 0 get co_neg c get co_val c end f = fn_of @@ -2231,11 +2317,17 @@ eexpr a ret end if eq k 10 -emitfloat v a b +emitfloat v t a b ret end if eq k 4 +if or eq isflt t 1 eq isflt get nt a 1 +for j ulong len fcvcall +e_b ulong get fcvcall j +end +else emitstr 6 +end e_dec t e_comma e_dec get nt a @@ -2257,12 +2349,8 @@ e_b 41 ret end if eq k 3 -if eq get nx n 11 -fv = ulong 2 -if eq v 9 -fv = 3 -end -emitfloat fv a b +if eq isflt get nx n 1 +emitfloat v get nx n a b ret end if eq py 0 @@ -2439,7 +2527,7 @@ fail 7 end tok t = ty_of get tw 0 -if eq t 11 +if eq isflt t 1 fail 24 end if lt t 2 @@ -3245,11 +3333,11 @@ e_b 10 end fn exportfn f ulong to void -if eq get fn_ret f 11 +if eq isflt get fn_ret f 1 fail 24 end for i ulong get fn_np f -if eq get fn_pt add mul f 6 i 11 +if eq isflt get fn_pt add mul f 6 i 1 fail 24 end end @@ -3674,14 +3762,34 @@ if ok ret 3 end end +if eq get tl 0 len f64word +ok = true +for i ulong len f64word +if ne get src add get ts 0 i get f64word i +ok = false +end +end +if ok +ret 4 +end +end ret 0 end -fn emitfloat op ulong a ulong b ulong to void +note isflt: 1 for the seeded C float types f32 (11) and f64 (12). +fn isflt t ulong to ulong +if or eq t 11 eq t 12 +ret 1 +end +ret 0 +end + +note emitfloat: o_fp(op, t, a, b) with the toc operator code (19 fabs); unary 17/19 pass b as 0. +fn emitfloat op ulong t ulong a ulong b ulong to void emitstr 8 eexpr a emitstr 9 -if eq op 1 +if ge op 17 e_b 48 else eexpr b @@ -3691,6 +3799,8 @@ e_b ulong get fcall i end e_dec op e_comma +e_dec t +e_comma emitstr 12 end diff --git a/tests/seeded_float.py b/tests/seeded_float.py index 4fd3485..f65eeb6 100644 --- a/tests/seeded_float.py +++ b/tests/seeded_float.py @@ -1,47 +1,200 @@ -"""Seeded-only internal binary32 differential and fail-closed controls.""" +"""Seeded-only internal binary32/binary64 differential and fail-closed controls. + +The seeded omc executable is the reference: every case below compares its AArch64 +output bytes with the generated C on this host and, when the cross tools exist, on +x86-64 under qemu-x86_64. Float constants are also checked against an exact +round-to-nearest-even decimal oracle written with fractions.Fraction. +No GPU, CUDA runtime, driver or hardware access. +""" +import fractions import os import pathlib +import re +import shutil +import struct import subprocess +import sys root = pathlib.Path(__file__).resolve().parents[1] os.chdir(root) b = root / 'build/seeded-float' b.mkdir(parents=True, exist_ok=True) -seed = os.environ['OMEGA_SEEDED_OMC'] +seed = os.environ.get('OMEGA_SEEDED_OMC') +if not seed: + sys.exit('NOT_RUN: set OMEGA_SEEDED_OMC to the pinned e5b32567 compiler') +x86 = shutil.which('x86_64-linux-gnu-gcc') and shutil.which('qemu-x86_64') def run(args, data=None): - return subprocess.run(list(map(str, args)), input=data, capture_output=True, timeout=60) + return subprocess.run(list(map(str, args)), input=data, capture_output=True, timeout=120) def checked(args, data=None): p = run(args, data) assert p.returncode == 0, (args, p.returncode, p.stderr) return p.stdout -source = '''fn calc u uint to uint -x = bitcast f32 u -y = mul x 1.5f32 -z = fabs y -if le z 3.0f32 -ret bitcast uint y +def differential(name, source): + """Native seeded executable bytes == generated C bytes (host and x86-64).""" + f = b / (name + '.om') + f.write_text(source) + native = b / (name + '.native') + native.write_bytes(checked([seed], source.encode())) + native.chmod(0o755) + expected = checked([native]) + c = b / (name + '.c') + c.write_bytes(checked(['sh', 'tools/bridge-seeded', 'c', f])) + checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', c, '-o', b / (name + '.host')]) + assert checked([b / (name + '.host')]) == expected, name + if x86: + checked(['x86_64-linux-gnu-gcc', '-static', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', + c, '-o', b / (name + '.x86')]) + assert checked(['qemu-x86_64', b / (name + '.x86')]) == expected, name + return f, c, expected + +def nearest(text, frac, ebits): + """Exact decimal -> IEEE binary bits, round to nearest, ties to even.""" + q = fractions.Fraction(text) + sign = 1 if text.startswith('-') else 0 + q = abs(q) + bias = (1 << (ebits - 1)) - 1 + if q == 0: + return sign << (frac + ebits) + e = q.numerator.bit_length() - q.denominator.bit_length() + while fractions.Fraction(2) ** e > q: + e -= 1 + while fractions.Fraction(2) ** (e + 1) <= q: + e += 1 + e = max(e, 1 - bias) + m = q * fractions.Fraction(2) ** (frac - e) + n = m.numerator // m.denominator + rest = m - n + if rest > fractions.Fraction(1, 2) or (rest == fractions.Fraction(1, 2) and n % 2): + n += 1 + if n == 1 << (frac + 1): + n >>= 1 + e += 1 + field = 0 if n < 1 << frac else e + bias + assert field < (1 << ebits) - 1, ('overflow fixture', text) + return (sign << (frac + ebits)) | (field << frac) | (n & ((1 << frac) - 1)) + +io = '''fn w64 v ulong to ulong +out = new uchar 8 0 +for i ulong 8 +put out i uchar and shr v mul i 8 255 +end +n = write 1 out 0 8 +ret 0 +end +fn w64s v long to ulong +if lt v 0 +ret w64 sub 18446744073709551615 ulong neg add v 1 +end +ret w64 ulong v +end +''' + +def compares(x, y): + s = 'c = ulong 0\n' + for bit, op in enumerate(['eq', 'ne', 'lt', 'le', 'gt', 'ge']): + s += f'if {op} {x} {y}\nc = or c {1 << bit}\nend\n' + return s + 'r = w64 c\n' + +def grouped(prefix, calls, size=40): + s, names = '', [] + for g in range(0, len(calls), size): + names.append(f'{prefix}{g // size}') + s += f'fn {names[-1]} to ulong\n' + ''.join(f'r = {c}\n' for c in calls[g:g + size]) + 'ret 0\nend\n' + return s, names + +# 1. Arithmetic, comparisons, conversions and bitcasts over edge bit patterns. +F64 = [0, 1 << 63, 0x3ff0000000000000, 0xbff0000000000000, 0x3fb999999999999a, 1, + 0x000fffffffffffff, 0x0010000000000000, 0x7fefffffffffffff, 0x7ff0000000000000, + 0xfff0000000000000, 0x7ff8000000000000, 0x7ff4000000000001, 0xfff8000000000123, + 0x43e0000000000000, 0x43f0000000000000, 0xc3e0000000000000, 0x41dfffffffc00000, + 0x4340000000000001, 0x3fe0000000000000, 0xc08f400000000000, 0x47efffffe0000000, + 0x36a0000000000000, 0x380fffffffffffff, 0xc1e0000000200000] +F32 = [0, 1 << 31, 0x3f800000, 0xbf800000, 0x3dcccccd, 1, 0x007fffff, 0x00800000, 0x7f7fffff, + 0x7f800000, 0xff800000, 0x7fc00000, 0x7fa00001, 0xffc00123, 0x5f000000, 0x5f800000, + 0xdf000000, 0x4effffff, 0x3f000000, 0xcf000000, 0x4f000000] +SIGNED = [0, 1, -1, 9007199254740993, -9007199254740993, 9223372036854775807, + -9223372036854775807, 16777217, -16777217, 2147483647, -2147483647] +source = io + '''fn f64ops a ulong b ulong to ulong +x = bitcast f64 a +y = bitcast f64 b +r = w64 bitcast ulong add x y +r = w64 bitcast ulong sub x y +r = w64 bitcast ulong mul x y +r = w64 bitcast ulong div x y +r = w64 bitcast ulong neg x +r = w64 bitcast ulong fabs x +''' + compares('x', 'y') + '''ret 0 +end +fn f32ops a uint b uint to ulong +x = bitcast f32 a +y = bitcast f32 b +r = w64 ulong bitcast uint add x y +r = w64 ulong bitcast uint sub x y +r = w64 ulong bitcast uint mul x y +r = w64 ulong bitcast uint div x y +r = w64 ulong bitcast uint neg x +r = w64 ulong bitcast uint fabs x +''' + compares('x', 'y') + '''ret 0 +end +fn f64cv a ulong to ulong +x = bitcast f64 a +r = w64 ulong x +r = w64s long x +r = w64s long int x +r = w64s long short x +r = w64s long byte x +r = w64 ulong uint x +r = w64 ulong ushort x +r = w64 ulong uchar x +r = w64 ulong bitcast uint f32 x +r = w64 bitcast ulong mul x 0.5 +r = w64 bitcast ulong f64 a +r = w64 ulong bitcast uint f32 a +r = w64s bitcast long x +ret 0 end -ret bitcast uint z +fn f32cv a uint to ulong +x = bitcast f32 a +r = w64 bitcast ulong f64 x +r = w64 ulong x +r = w64s long x +r = w64s long int x +r = w64 ulong uint x +r = w64 ulong bitcast uint f32 a +r = w64 ulong bitcast uint sub x 1.5 +ret 0 +end +fn sgn s long to ulong +r = w64 bitcast ulong f64 s +r = w64 ulong bitcast uint f32 s +r = w64 bitcast ulong bitcast f64 s +ret 0 +end +fn lit to ulong +r = w64 bitcast ulong f64 1 +r = w64 bitcast ulong f64 -1 +r = w64 bitcast ulong f64 9007199254740993 +r = w64 bitcast ulong f64 9223372036854775807 +r = w64 bitcast ulong f64 -9223372036854775807 +r = w64 ulong bitcast uint f32 16777217 +r = w64 ulong bitcast uint f32 -3 +ret 0 end -fn main to int -out = new uchar 4 0 ''' -for value in [0, 1, 8388607, 8388608, 1065353216, 2139095039, 2139095040, 2143289344, 2147483648]: - source += f'u = calc {value}\nfor i ulong 4\nput out i uchar and shr u uint mul i 8 255\nend\nn = write 1 out 0 4\n' -source += 'ret 0\nend\n' -f = b / 'float.om' -f.write_text(source) -native = b / 'native' -native.write_bytes(checked([seed], source.encode())) -native.chmod(0o755) -expected = checked([native]) -c = b / 'float.c' -c.write_bytes(checked(['sh', 'tools/bridge-seeded', 'c', f])) -checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', c, '-o', b / 'portable']) -assert checked([b / 'portable']) == expected +calls = [f'f64ops {a} {c}' for a in F64 for c in F64] + [f'f32ops {a} {c}' for a in F32 for c in F32] +calls += [f'f64cv {a}' for a in F64] + [f'f32cv {a}' for a in F32] + [f'sgn {s}' for s in SIGNED] + ['lit'] +groups, names = grouped('g', calls) +source += groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n' +f, c, expected = differential('ops', source) +records = (len(F64) ** 2) * 7 + (len(F32) ** 2) * 7 + len(F64) * 13 + len(F32) * 7 + len(SIGNED) * 3 + 7 +assert len(expected) == 8 * records, (len(expected), records) +# Integer literals under a float conversion are typed long and rounded to nearest even (omc SCVTF). +lits = [struct.pack('<d', float(v)) for v in (1, -1, 9007199254740993, 9223372036854775807, -9223372036854775807)] +lits += [struct.pack('<f', float(v)) + bytes(4) for v in (16777217, -3)] +assert expected[-56:] == b''.join(lits), expected[-56:].hex() for target in ['python']: p = run(['sh', 'tools/bridge-seeded', target, f]) assert p.returncode != 0 and not p.stdout @@ -50,15 +203,96 @@ assert p.returncode != 0 and not p.stdout # Compile-time arithmetic-mode refusal is not an ignored warning. p = run(['gcc', '-std=gnu11', '-O2', '-ffast-math', c, '-o', b / 'unsafe']) assert p.returncode != 0 and b'fast math' in p.stderr + +# 2. A constant table beyond the former 32/99 limits, emitted bit-exactly. The significant digits of a +# float literal must fit in 2^63-1 (omc and the converter: error 8), so long literals are kept to 19 digits. +D = ['0.1', '-0.0', '1.0', '3.141592653589793', '2.2250738585072014e-308', '4.9406564584124654e-324', + '2.225073858507201e-308', '1.7976931348623157e308', '9007199254740993.0', '0.30000000000000004', + '1.0e23', '2.2250738585072011e-308', '2.4703282292062327e-324', '2.4703282292062328e-324', + '1.7976931348623158e308', '123456789012345678.9e11', '0.6931471805599453', + '1.5707963267948966', '-2.5e-1', '0.1000000000000000055'] +for k in range(len(D), 100): + D.append(('-' if k % 3 == 0 else '') + f'{(k * 7919) % 100000}.{(k * 104729) % 1000000:06d}e{(k % 61) - 30}') +S = ['0.1', '5.9604645e-8', '3.4028235e38', '1.4e-45', '7.0e-46', '7.1e-46', '1.17549435e-38', + '16777217.0', '16777219.0', '-2.5', '0.0', '-0.0', '3.4028235677e38', '0.33333334', + '1.0000001', '2.7182817'] +for k in range(len(S), 30): + S.append(('-' if k % 2 else '') + f'{(k * 31337) % 10000}.{(k * 7) % 1000:03d}e{(k % 21) - 10}') +consts = 'const NI ulong 7\nconst NS long -3\n' +consts += ''.join(f'const D{i} f64 {t}\n' for i, t in enumerate(D)) +consts += ''.join(f'const S{i} f32 {t}\n' for i, t in enumerate(S)) +calls = [f'w64 bitcast ulong D{i}' for i in range(len(D))] + [f'w64 ulong bitcast uint S{i}' for i in range(len(S))] +calls += ['w64 NI', 'w64s NS', 'w64 bitcast ulong mul D3 D1', 'w64 ulong bitcast uint add S0 S14'] +groups, names = grouped('k', calls) +source = consts + io + groups + 'fn main to int\n' + ''.join(f'r = {n}\n' for n in names) + 'ret 0\nend\n' +f, c, expected = differential('consts', source) +words = [int.from_bytes(expected[i:i + 8], 'little') for i in range(0, len(expected), 8)] +oracle = [nearest(t, 52, 11) for t in D] + [nearest(t, 23, 8) for t in S] +# The converter reproduces omc e5b32567 bit for bit. omc misrounds two of these literals by one ulp +# (aien-dev/omega-mv#1024, checked against an exact rational oracle); any other difference, or a +# change in these two, fails. +OMC_MISROUNDED = {'2.4703282292062328e-324': 0, '6816.702656e-27': 0x3b207b55a6d4a12f} +for t, w, o in zip(D + S, words, oracle): + if t in OMC_MISROUNDED: + assert w == OMC_MISROUNDED[t] and abs(w - o) == 1, (t, hex(w), hex(o)) + else: + assert w == o, (t, hex(w), hex(o)) +assert all(t in D for t in OMC_MISROUNDED) +assert words[len(oracle):len(oracle) + 2] == [7, (1 << 64) - 3] +# Negative control: a one-ulp change to one emitted constant is detected. +text = c.read_text() +lit = str(oracle[0]) +assert lit + 'ULL' in text, 'constant not emitted as its exact bit pattern' +bad = b / 'consts-mutant.c' +bad.write_text(text.replace(lit + 'ULL', str(oracle[0] + 1) + 'ULL', 1)) +checked(['gcc', '-std=gnu11', '-O2', '-Wall', '-Wextra', '-Werror', bad, '-o', b / 'consts-mutant']) +assert checked([b / 'consts-mutant']) != expected + +# 3. Fail-closed converter checks (seeded C frontend only, after the seeded omc accepts). for name, body in { - 'public_float': 'fn root x f32 to f32\nret x\nend\n', - 'float_array': 'fn root x view f32 2 to uint\nret 0\nend\n', - 'float_cast': 'fn root x uint to uint\ny = bitcast f32 x\nret uint y\nend\n', - 'float_add': 'fn root x uint to uint\ny = bitcast f32 x\nz = add y 1.0f32\nret bitcast uint z\nend\n', + 'public_f32': 'fn root x f32 to f32\nret x\nend\n', + 'public_f64': 'fn root x f64 to ulong\nret bitcast ulong x\nend\n', + 'f32_array': 'fn root x view f32 2 to uint\nret 0\nend\n', + 'f64_array': 'fn root x view f64 2 to uint\nret 0\nend\n', }.items(): f = b / (name + '.om') f.write_text(body) for target in ['c', 'h']: p = run(['sh', 'tools/bridge-seeded', target, f]) assert p.returncode != 0 and not p.stdout, (name, target, p.stderr) -print('PASS seeded binary32 byte differential; baseline/Python/public-float/array/cast/op/fast-math refusals') +# Converter-level semantic refusals with their exact error codes (input straight to the converter). +# Each case is also compiled by the seeded omc: where omc refuses, the converter reports omc's code; +# where omc accepts, the converter's refusal must be a capability (24) or capacity (14) code. +many = ''.join(f'const C{i} f64 1.5\n' for i in range(1025)) + 'fn root to ulong\nret 0\nend\n' +for name, body, code in [ + ('int_literal_f64', 'const K f64 1\nfn root to ulong\nret 0\nend\n', 16), + ('float_literal_ulong', 'const K ulong 1.0\nfn root to ulong\nret 0\nend\n', 16), + ('suffix_mismatch', 'const K f64 1.0f32\nfn root to ulong\nret 0\nend\n', 16), + ('suffix_const', 'const K f64 1.0f64\nfn root to ulong\nret 0\nend\n', 16), + ('f32_overflow', 'const K f32 3.4028236e38\nfn root to ulong\nret 0\nend\n', 8), + ('f64_overflow', 'const K f64 1.7976931348623159e308\nfn root to ulong\nret 0\nend\n', 8), + ('float_length', 'const K f64 4.0\nfn root to ulong\na = new uchar K 0\nret len a\nend\n', 16), + ('float_rem', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = rem x x\nret bitcast ulong y\nend\n', 7), + ('float_xor', 'fn root a uint to uint\nx = bitcast f32 a\ny = xor x x\nret bitcast uint y\nend\n', 7), + ('float_shift_count', 'fn root a ulong to ulong\nx = bitcast f64 a\nret shl a x\nend\n', 24), + ('int_literal_operand', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = add x 1\nret bitcast ulong y\nend\n', 7), + ('int_literal_left', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = mul 2 x\nret bitcast ulong y\nend\n', 7), + ('int_literal_long_range', 'fn root to ulong\ny = f64 9223372036854775808\nret bitcast ulong y\nend\n', 8), + ('untyped_float', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = add 1.0 x\nret bitcast ulong y\nend\n', 24), + ('bitcast_int_f32', 'fn root a int to ulong\nx = bitcast f32 a\nret 0\nend\n', 24), + ('bitcast_ulong_f32', 'fn root a ulong to ulong\nx = bitcast f32 a\nret 0\nend\n', 7), + ('bitcast_bool_f64', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = bitcast bool x\nret 0\nend\n', 7), + ('bool_float', 'fn root a ulong to ulong\nx = bitcast f64 a\ny = bool x\nret 0\nend\n', 9), + ('float_of_bool', 'fn root to ulong\nq = true\ny = f64 q\nret 0\nend\n', 7), + ('fabs_int', 'fn root a ulong to ulong\nret fabs a\nend\n', 7), + ('long_significand', 'const K f64 9223372036854775808.0\nfn root to ulong\nret 0\nend\n', 8), + ('consts_1025', many, 14), +]: + p = run(['build/bridge'], ('D' + body).encode()) + assert p.returncode != 0 and not p.stdout, (name, p.returncode) + assert re.search(rb'error ' + str(code).encode() + rb'\b', p.stderr), (name, p.stderr) + o = run([seed], (body + 'fn main to int\nret 0\nend\n').encode()) + assert o.returncode == code if o.returncode else code in (14, 24), (name, o.returncode, code) +print('PASS seeded binary32/binary64 byte differential (native/C' + ('/x86' if x86 else '') + + ', %d constants vs exact oracle, one-ulp mutant detected); baseline/Python/public-float/array/' + 'converter refusals' % (len(D) + len(S) + 2) + ('' if x86 else '; x86 NOT_RUN'))