103 Commits
m4 ... m7
Author SHA1 Message Date
arti 0f7353c21c docs: point the status line at the M7.4 code heads 2026-11-16 02:23:35 +00:00
arti 2157c24ef8 docs: m7 is the repository default branch 2026-11-16 02:23:23 +00:00
arti 1eaabaa6a0 M7.4: align the remaining COFF-repair comments 2026-11-15 15:56:00 +00:00
arti f471ab8c11 M7.4: soften the COFF-repair mechanism wording 2026-11-15 15:54:09 +00:00
arti 2835990a00 M7.4: make the COFF guard fail and correct the suite attribution 2026-11-15 15:46:35 +00:00
arti 3c024b93b9 docs: tick the M7.4 plan 2026-11-15 15:38:02 +00:00
arti 6e7d5bbe92 M7.4: document the final conformance/performance state
Record the full-suite method, settings, pins and exact counts
(c-torture 1692 = 1366/326/0/0; c-testsuite 220 = 210/10/0/0; all
1912 = 1576/336/0/0), the curated skip classes, the 112 honest pass
flips, the i64 DIVU fast path and its MAME frame measurement, the
conformance-loader COFF repair, and the shipped-tier counts.

Mark M7 complete, keep the M7.1/M7.2/M7.3 counts and limitations
(one debug TU, .lib not readable by tms-link, kept-debug not
loadable, hardware DEFERRED), and state the M7/M8 boundary. Add the
M7.1-M7.4 plan links and the M7.4 gate commands, and distinguish the
curated 48/172 c-testsuite tier from the full-corpus 210/10 result.
2026-11-15 15:37:19 +00:00
arti f8651fcb2f M7.4: triage and curate the full conformance suite 2026-11-15 13:39:28 +00:00
arti 65e6a6e6b8 M7.4: add the full-suite conformance driver and baseline 2026-11-15 08:34:25 +00:00
arti 1e3977132d M7.4: fix the i64div perf gate link, layout and result checks
The M4 default link command's 4 KiB prog region cannot hold the perf
driver's ~8.7 KiB .text, and the old markers at 018A8000 were inside that
.text.  Add a gate-local link command (prog = 40000h) and move the eight
markers to 01A20000, free RAM above the 4 KiB entry stack and inside the
declared ram region.

i64div-map-check.py parses both GSPLNK and tms-link maps and fails if the
marker cells overlap .text/.data/.bss, leave the region, or if a section
leaves its region.  The gate runs it on a host tms-link map and on the
GSPA/GSPLNK map from a link-only pass before MAME, with compile-only and
link-only stop modes for the no-DOSBox checks.

Require the exact deterministic phase checksums (fast 00000001:1E6F9AB4,
slow 00000000:007512AE, hosted and independently recomputed), and extend
the in-image self-check with large-magnitude fast cases: 0xFFFFFFFF/7,
-123/7 (-123 % 7 = -4) and INT32_MIN/3, so a wrong 32-bit quotient or
remainder fails before timing.  The gate documents that -O2 is an
optimizer baseline, not the i64 fast-path measurement.
2026-11-15 08:02:54 +00:00
arti e540db3ca9 M7.4: measure the i64 divide fast path in MAME frames
i64div.sh runs two equal-iteration i64 division workloads on the emulated
part: small operands whose high words are zero (the 32-bit DIVU fast path)
and operands with nonzero high words (the 64-step restoring loop).  The
driver's self-check first proves both paths produce the known M6 values;
the checksums are retained as evidence.

i64div-perf-check.lua polls the start and per-phase completion markers
once per MAME frame and requires the fast phase to complete in materially
fewer frames (slow_frames >= 8 * max(fast_frames,1), slow_frames >= 20).
A frame is a fixed emulated-cycle count, so the comparison is
reproducible.  The gate widens the loader budget to 200..4000 frames for
the slow phase; the M7 full-suite settings are untouched.

The script also has a compile-only preflight (tms-clang + llc, no
DOSBox/MAME) that checks the driver asm for the fast blocks, DIVU and the
slow loop.
2026-11-15 07:48:52 +00:00
arti 5f35a75a0a docs: M7.4 scope and plan 2026-11-15 07:34:12 +00:00
arti 54608c0e32 M7.3: keep hardware evidence and document the bootstrap knobs 2026-11-15 07:26:23 +00:00
arti 11693186bc docs: state the M7.3 gate-change scope precisely 2026-11-15 07:26:15 +00:00
arti ff4cf94176 docs: correct the M7.3 symbol table and evidence claims 2026-11-15 07:26:06 +00:00
arti c756b568ae docs: tick the M7.3 plan 2026-11-15 07:18:02 +00:00
arti 7d07fb787b M7.3: document the runtime/hardware state and rebase the JR fixture 2026-11-15 07:17:33 +00:00
arti 98561252ad M7.3: correct the hardware entry and unit assumptions 2026-11-15 05:16:55 +00:00
arti fe78805872 M7.3: add the real-hardware marker gate with MAME acceptance 2026-11-15 05:09:53 +00:00
arti cdf137f64b M7.3: do not write a byte for fputc(EOF) 2026-11-15 04:55:49 +00:00
arti 38fdeb2e28 M7.3: fix the stderr layout and empty-stream contract 2026-11-15 04:52:25 +00:00
arti 5757f056b0 M7.3: capture stderr as a second conformance stream 2026-11-15 03:55:01 +00:00
arti 9586ed21d1 M7.3: correct the xmore marker comments 2026-11-15 02:23:27 +00:00
arti a6379b206b M7.3: make the xmore flags honest (review round 2)
The ROM builders do not set A8, so markers 4 and 10 are no longer
presented as return values:

- property_called=1 and attrs_called=1 are plain post-call flags.  The
  gate requires the flag, states that the property has no server read-back
  (zero X errors is the only runtime check), and keeps the black margin
  as the real CWBackPixel proof.  Marker 14 pins the 160x120 fill
  geometry (0xA00078) so the margin sample cannot become vacuous.
- InternAtom wording: the display marker only proves the connection was
  live before the call; stage 14 cannot distinguish the intended _XSend
  block from a crash/wrong import.  The isolated probe is narrative entry
  evidence, not a gate check.
- XSetWindowAttributes attrs = {0}; replaces the unsigned int * zeroing
  loop.
- Fix the stale image_roundtrip stage-11 comment (text pixels now set
  stage 12).
- GC wording is 'source call sites; runtime entry not proven', not
  'proves call presence'.
2026-11-15 02:21:08 +00:00
arti 5716e3ca35 M7.3: strengthen the xmore gate evidence (review round 1)
Make the wider-Xlib evidence non-vacuous:

- Child starts with background 1; CWBackPixel=0 and a 160x120 fill leave a
  black margin sampled at screen (300,240).  XChangeWindowAttributes now
  returns a marker (10) and the margin is required; the attrs=1 negative
  control turns it white and fails the gate.
- Marker 4 is the XChangeProperty return (nonzero, not a read-back).
  Marker 11 counts the two explicit XChangeGC calls (presence + no X error;
  the ROM entry is a 2-arg cache flush).  XDrawString is proven by counting
  the set pixels of an XGetImage band (marker 12, 67 in the run).
- Marker 13 stores the live Display just before XInternAtom, so the skip
  cannot be a crash/wrong import; the gate/report state that entry is
  evidenced by the isolated probe.
- Zero the XSetWindowAttributes struct.
- Pin the six wider addresses as constants in validate-syms.sh.
- Print parent(...) instead of win(...) (parent-relative, not child).
- Correct the report's configure/p_img justification and add Fix round 1.
- scripts/m4/run.sh prints M7 MAME: PASS for an M7 marker line; M4 output
  is unchanged.
2026-11-15 02:00:32 +00:00
arti 0cab36a2b0 M7.3: wider VT1200 Xlib surface (xmore)
Add and validate XMapSubwindows, XChangeWindowAttributes,
XConfigureWindow, XInternAtom, XChangeProperty and XChangeGC from the
GUI_APPS table, extend x11m4.h with the X11R4 masks/structs and the ROM
call shapes, and add the xmore client plus its MAME gate.

xmore exercises a parent/child window, XMapSubwindows, the fixed-mask
move/resize ConfigureWindow, WM_NAME (predefined atom 39), CWBackPixel,
XChangeGC, XLoadFont/XDrawString, XFillRectangle, and a heap
XCreateImage/XPutImage/XGetImage/XPutImage/XDestroyImage round trip with
XSync.  Markers at 018A8000+n*20 show stage 14, image 0x13F and 0 errors.

XInternAtom is kept as the last call with an explicit 0xFFFFFFFF skip
marker: the ROM _XSend scatter path (0x3F9B44C0) that carries the name
does not complete in the loader harness (the same direct-send limit the
M4 xshow client records).  If it returns, the client uses the atom and
advances to stage 15.  The GC uses the server default font because the
ROM XLoadFont handle is rejected as GCFont (BadFont); XLoadFont itself is
still exercised and marked.

The M4 runner now accepts M4/M7 marker and PASS lines; M4 behavior is
unchanged.
2026-11-15 01:33:41 +00:00
arti e7f8252470 docs: M7.3 scope and plan 2026-11-15 00:31:17 +00:00
arti 3dccc4d188 docs: scope the M7.2 oracle acceptance to the tested M5 objects 2026-11-15 00:24:27 +00:00
arti e35cb154ce docs: tick the M7.2 plan 2026-11-15 00:16:54 +00:00
arti 8b0b0bcd11 m7.2: document the TI-COFF debug writer and tms-link 2026-11-15 00:14:09 +00:00
arti fefb1daba4 m7.2: prove barrier-synthesized !dbg in the debug gate
Extract the final -O0 @debug_ptr body and require !dbg on the
--bitptr/--lower-bitptr chain (mul, shl, ptrtoint, add, inttoptr) and on
every load/store through the computed pointer.  Line-table rows alone could
stay green if the barrier dropped locations only on the instructions it
synthesizes; this IR-level check fails in that case.

Refresh the stale gate header (three functions, -O2 smoke, indexed
.debug_addr, ptr=30) and note that the exact .debug_addr entry list is
deterministic at the current compiler but should be relaxed on a DWARF
emission change.
2026-11-14 23:01:05 +00:00
arti 46417f53ec m7.2: strengthen Task 3 debug/oracle/cinit gates
- debug.sh: add a pointer/array runtime-GEP function (debug_ptr) with
  asserted line rows/low PC, and build the same TU with tms-clang -g -O2
  through --bitptr/opt/--scale/--lower-bitptr/instcombine; require the
  -O2 object's .debug_* sections and dwarfdump its debug.c/function/low PC.
  Read .debug_addr entries by index and assert the CU low/high PC and
  .debug_line file index.
- oracle.sh: load both the GSPLNK and tms-link images in MAME with the same
  markers; require a minimum count and the names the checks depend on, and
  document the absolute/undefined C_EXT exclusion.
- cinit.sh: assert the object relocation (0x10, .bss/_cinit_target base,
  addend 0), compare the 28-byte optional header with GSPLNK, and link
  CINIT.O alone to exercise the synthesized public cinit symbol.
- tmscoff.py: point the order-relaxation comment at the Task 1 lit test that
  still pins the llc section order.
2026-11-14 22:54:19 +00:00
arti 0075e57c0d m7.2: add object/debug end-to-end gates
- oracle.sh: link the M5 native objects with GSPLNK and tms-link, require
  identical allocated bytes/public symbols through the independent reader,
  then run the tms-link image in MAME and decode _native_value with dis34.
- cinit.sh: a C TI .cinit record table (packed u16 count/u32 destination/
  data words) linked by tms-link, the termtris copy loop in MAME, cinit at
  the .cinit origin, the destination resolved to a bit address, and
  bytes/placement equal to GSPLNK.
- longname.sh: a 44-character public function defined in one TU and called
  from another, linked by tms-link, full name in the map, runs in MAME.
- debug.sh: tms-clang -g -> TI-COFF -> tms-link --keep-debug, .debug_*
  wrapped in a minimal ELF32 container and validated with llvm-dwarfdump
  (debug.c, line rows, low PC 0x314000, high_pc byte size, string names),
  plus the stripped image loading in MAME.
- tms-clang: pass -g through to clang; the bit-pointer passes preserve !dbg.
- tms-link: accept GSPA's .text/.data/.bss/.cinit order as well as llc's
  .text/.data/.cinit/.bss order (the real startup cinit.asm shape).
2026-11-14 22:21:03 +00:00
arti 38ab394c8b m7.2: tighten tms-link oracle and reader (fix round 1) 2026-11-14 21:50:03 +00:00
arti b21e762058 m7.2: add tools/tms-link native TI-COFF linker 2026-11-14 21:36:08 +00:00
arti d7209392f2 docs: M7.2 scope and plan 2026-11-14 20:36:32 +00:00
arti e09d85c99f docs: tick the M7.1 plan 2026-11-14 20:33:05 +00:00
arti ad6b39738a m7.1: close the final-review evidence gaps 2026-11-14 20:32:54 +00:00
arti 4110a24c23 m7.1: document the M7.1 state and refresh the generic manifest 2026-11-14 20:08:43 +00:00
arti f79eadfda1 m7.1: gate the odd-offset pointer and wide-integer .data cases 2026-11-14 18:13:16 +00:00
arti b0048b8151 m7.1: add the .data i64/aggregate/bitfield gate 2026-11-14 17:36:33 +00:00
arti 773dd7597e m7.1: cover the union and non-TMS stride controls 2026-11-14 16:55:45 +00:00
arti e1436ba112 m7.1: add the sub-byte stride diagnostic gate 2026-11-14 15:43:54 +00:00
arti b313de480b m7.1: keep narrowing base casts out of the barrier
Fix the fix-round regression: the base matcher stripped any zext/trunc,
so `(unsigned short)(unsigned)p + 24` lost its 16-bit truncation and
became `p + 24` at both -O0 and -O2.  stripWideningCasts now strips only
zext/sext and truncs to at least the 32-bit pointer width; a trunc below
i32 stops the match, leaving the shape unbarriered with its
`and 0xffff`/`and 0xff` intact (the base commit's value).

Allow widening sext on the base as well, closing the signed 64-bit
pointer-int shape: `(char *)((long long)(int)p + 24)` now becomes
`@__tms_bitptr(i32 24, ptr p)` instead of `getelementptr i8, p, 192`.
Use the fixed 32-bit TMS34010 pointer width rather than an absent module
DataLayout's 64-bit default, which misjudged a trunc to i32.

Add @narrow16/@narrow8/@narrow16and/@late64s to bitptr.ll (narrow shapes
must not emit a call), negative tests for the mismatched declaration,
body and non-call use fatal paths, a late64s M0 check with the late
positive scoped to @late itself, and narrow16/narrow8/late64s runtime
markers plus IR checks in the M7 gate.  Update the pointer-o2.sh header.
2026-11-14 13:57:48 +00:00
arti 9cf31b9b9b m7.1: barrier 64-bit pointer-int shapes
Extend --bitptr's raw inttoptr barrier through the zext/trunc clang emits
for a 64-bit pointer-int expression, so
`inttoptr(add(zext(ptrtoint p), i64 24))` becomes
`@__tms_bitptr(i32 24, ptr p)` instead of a post-scale `getelementptr
i8, p, 192`.  The pointer is 32-bit, so the addend is zext/truncated to
the low word.  The matcher also covers the reversed add operand order and
the sub form (negated addend).

Harden getBitPtrFn/lower_bitptr_calls: an existing @__tms_bitptr with a
mismatched signature or body, or a non-CallInst/mismatched use, now fails
loudly instead of leaving an undefined external.

Add @late64 (and sub/reversed/trunc) to bitptr.ll, assert the
nounwind readnone declaration, add a late64 M0 shape check (24, never
192) and a late64 runtime marker to the M7 gate.  Tighten the gate's
one-scale check to reject a second shl i32 in copy_back and to match
SLL 3/SLL 6 exactly (not SLL 31).  Update the stale M6 comments in
bitscale.cpp and the c-torture -O2 comment.
2026-11-14 13:14:56 +00:00
arti d3f411864d m7.1: add the -O2 bit-pointer semantic barrier
Replace the M6 pre-opt --scale with --bitptr: every source GEP (and an
inttoptr of a bit addend over a ptrtoint base) becomes an opaque
@__tms_bitptr(i32 bitoff, ptr base) call (nounwind readnone), so the
optimizer cannot canonicalize an already-bit offset back into a byte GEP
for the post-opt --scale to multiply by 8 again.

tms-clang -O2 is now clang -> --bitptr -> opt default<O2> -> --scale
(optimizer byte GEPs only) -> --lower-bitptr -> opt instcombine.  -O0 is
clang -> --bitptr -> --lower-bitptr.  --lower-bitptr restores
inttoptr(add(ptrtoint base, bitoff)); the final instcombine restores the
M0 int_diff 8/32 folding and the shim's emit_uint64 needs
instcombine<no-verify-fixpoint> for a known zext/nneg non-idempotent
shape.  Constant-expression GEPs keep the inttoptr/add form.

Remove the shim memmove constant-step workaround (natural d += n) and
add the M7 -O2 pointer gate (C driver at -O2, GSPA/GSPLNK, MAME, exact
markers/bytes and one-scale IR/asm evidence).  Update the M0 shape
checks for the final instcombine's bit-index `getelementptr i8, %p, 24`
late form (still 24 bits; the old 192 is rejected).
2026-11-14 12:26:40 +00:00
arti 91d42be168 docs: M7 scope and M7.1 plan 2026-11-14 11:39:14 +00:00
arti 9dc8f28488 docs: m6 is the repository default branch 2026-11-14 11:27:53 +00:00
arti 827d9315dd m6: refresh the lit count after the narrow-load regression
The new TMS34010 CodeGen test brings the M6 head to 103 CodeGen tests
(28 m6-*) and 107 lit tests including MC.
2026-11-14 10:33:16 +00:00
arti e0cf441118 m6: apply the final-review fixes
- spec 4.2/7.4: the caller-allocated hidden return slot (no sret
  pointer), with the 1987 _mkbig/_callbig oracle recorded as binding;
  spec 8 annotates debug info as M7.
- README: qualify the complete-surface headline, name the sub-byte
  stride in the M7 ownership lists, and flag the default -O2 over-scale.
- shim: %c honours width and the '-' flag; a bare %c is unchanged.
- runtime gate: add %c width output and call rts.lib _isascii, checking
  it in the GSPLNK map (587 bytes, 13 markers).
- aggregate gate: return a packed bitfield struct by value and check
  its fields, sign extension and raw word (49 markers).
- tms-clang: default TMS_CLANG/TMS_OPT to build/llvm-clean-build/bin
  and fail clearly when a tool is missing; update the README example.
2026-11-14 09:46:52 +00:00
arti 8d18ab91b2 docs: M6 language, runtime and conformance status 2026-11-14 07:52:03 +00:00
arti 094d2543f7 tests: correct the classifier format-scan comment 2026-11-14 06:16:40 +00:00
arti 2fec10b039 tests: fix M6 conformance review findings 2026-11-14 06:11:33 +00:00
arti bc92886312 tests: expand M6 conformance coverage 2026-11-14 05:33:50 +00:00
arti 3226a84988 docs: clarify the M6 -O2 pointer over-scale limitation 2026-11-14 04:49:39 +00:00
arti 5760a35867 tests: complete M6 printf coverage and document the bit-scale limits 2026-11-14 04:44:17 +00:00
arti 7aab6a6485 tests: fix printf precision edge cases (#, zero with precision 0) 2026-11-14 04:16:41 +00:00
arti 15201f31ba tests: restore the Task 6 bit-scale pipeline and memmove workaround 2026-11-14 03:22:23 +00:00
arti eb44a1aade Revert "tests: run SROA before the bit scale so pointer int casts stay bit-addressed"
This reverts commit 5379cd4629.
2026-11-14 03:22:10 +00:00
arti 5379cd4629 tests: run SROA before the bit scale so pointer int casts stay bit-addressed 2026-11-14 02:46:46 +00:00
arti 2fca960398 tests: scale the tms-clang pipeline once, after opt 2026-11-14 02:28:42 +00:00
arti 3005647f30 tests: M6 runtime, printf/sprintf and the linked flib/rts gate 2026-11-14 02:27:04 +00:00
arti 85c4a1778a tests: clarify the aggregate gate's linked-symbol check 2026-11-14 01:34:59 +00:00
arti 8be4a978cc tests: fix the aggregate gate and the -O0 driver scale 2026-11-14 01:31:11 +00:00
arti 12cb023b3c tests: M6 aggregate gate and late-GEP scaling
Add the M6 aggregate gate (structs/unions by value, 6-byte/5-word returns,
nested and mixed members, exact-copy guards) and scale every optimizer-created
GEP after opt in tms-clang; --normalize treated SROA's aggregate-split byte
offsets as bits.  The generic sweep now passes multiple-return-values-cross-
block-with-invoke.
2026-11-14 00:33:27 +00:00
arti ae73e6b054 tests: correct i64 memory-order comments 2026-11-13 22:39:15 +00:00
arti ded91f2054 tests: pin little-endian i64 memory and the aggregate-copy case 2026-11-13 22:24:59 +00:00
arti e997b3ff22 tests: add 64-bit bitfield containers to the M6 gate 2026-11-13 22:01:01 +00:00
arti 53f0b3c56b tests: M6 bitfield gate and layout oracle 2026-11-13 21:45:33 +00:00
arti b973ccd250 tests: M6 varargs gate and shim 2026-11-13 20:09:55 +00:00
arti 1a62878e93 tests: exercise M6 float branches, f64 select and rejections 2026-11-13 18:53:14 +00:00
arti f18115314c tests: M6 float/double gate 2026-11-13 17:27:56 +00:00
arti 581a264ab3 tests: harden M6 i64 gate and refresh the M5 boundary notes 2026-11-13 15:00:11 +00:00
arti c1d0378212 tests: M6 i64 gate
Adds the M6 i64 MAME gate (scripts/tests/m6/i64.sh, driver and
entry/check/link helpers) and updates the M5 boundary tests: the 64-bit
multiply diagnostic is now a positive inline-MPYS check, the reject-i64
lit fixtures use i128, and the generic expected-fail manifest drops the
tests that the i64 support now compiles (0 crashes, 121 pass).
2026-11-13 13:54:36 +00:00
arti dad0245d5e tests: harden M6 ABI probe compare/conversion/return 2026-11-13 12:38:01 +00:00
arti fa90562bb9 tests: M6 float/i64 ABI probe 2026-11-13 12:18:46 +00:00
arti ea1222001f docs: M6 language/runtime and floats plan 2026-11-13 12:01:40 +00:00
arti 5ee3a6592c tests/docs: final M5 review fixes 2026-11-13 10:14:32 +00:00
arti 1d97b1c5cd tests/docs: M5 native object path and conformance 2026-11-13 08:37:37 +00:00
arti 480f4de4a4 tests: M5 c-testsuite output subset 2026-11-13 07:28:53 +00:00
arti 3d9e6162bf tests: fix M5 c-torture failure accounting 2026-11-13 05:54:47 +00:00
arti cb1032a751 tests: M5 c-torture integer subset 2026-11-13 04:45:19 +00:00
arti 9baa05963c tests: harden M5 generic sweep signal handling 2026-11-13 01:59:59 +00:00
arti e5ee1686d8 tests: tighten M5 generic sweep timeout classification 2026-11-13 01:00:31 +00:00
arti 1869a1f015 tests: M5 CodeGen/Generic no-crash sweep 2026-11-13 00:54:50 +00:00
arti 1d95b99029 tests: fix M5 conformance review findings 2026-11-12 23:46:57 +00:00
arti a3d8070be6 tests: M5 conformance harness and shim 2026-11-12 22:43:04 +00:00
arti 97345c8b46 tests: harden M5 policy and private-name checks 2026-11-12 21:53:43 +00:00
arti 0b245867ab tests: M5 policy and hardening gate 2026-11-12 21:22:34 +00:00
arti cfff7ad14e tests: prove M5 VLA reservation in MAME 2026-11-12 19:31:05 +00:00
arti cdaaee62f3 tests: M5 robustness gate 2026-11-12 19:00:16 +00:00
arti 556df985b9 tests: accept M5 JR forms in the M4 branch gates 2026-11-12 18:08:39 +00:00
arti 8c2c784a41 tests: M5 MMTM/MMFM gate 2026-11-12 17:54:37 +00:00
arti 9b5ee500fc tests: tighten M5 JR coverage
jr.sh now asserts the recorded M3 baseline (882-byte .text, 14 JR branches,
2 zero-displacement absolute branches), checks that every JR is one word and
in range, and probes symbolic JRUC with disp 0, disp -128 (widen) and disp
-127 (stay short) through the MC relaxation path.

dis-roundtrip.sh pins the condition code per function again (_sumto LT and
EQ, _max2 GT, _lt LT) instead of the broken ${op#j[ra]} strip, keeping the
global at-least-one-JR check.

native-link.c's far conditional branch now spans ~279 words instead of ~151,
so a small codegen shrink cannot turn it back into a JR.
2026-11-12 17:11:38 +00:00
arti 1a6833045c tests: M5 JR relaxation gate
Add scripts/tests/m5/jr.sh: the M3 branch.c loop must use JR forms, llc's
asm and object .text must match, a symbolic out-of-range JRUC must relax to
JAUC, the M3 MAME markers must be unchanged, and the linked .text size must
show the saving against the all-JA baseline.

Update the M3 dis34 gate and the native-link gate for the new encoding: the
compiled branches are relative, so accept JR/JA condition codes and keep a
far conditional JA<cc> relocation in native-link.c.
2026-11-12 16:49:52 +00:00
arti d5740974cc tests: M5 native pipeline and M4 regressions 2026-11-12 16:15:20 +00:00
arti 8bbd536717 tests: extend M5 MC gates 2026-11-12 15:35:08 +00:00
arti 73ee5bf308 tests: M5 MC round-trip gate 2026-11-12 15:13:44 +00:00
arti 795515fe3f tests: cover branch and external COFF relocations 2026-11-12 14:30:07 +00:00
arti f098bdc613 tests: M5 native COFF link gate 2026-11-12 14:15:09 +00:00
arti 2636412c0e tests: extend the M5 object smoke gate 2026-11-12 13:43:31 +00:00
arti 719711ea3f tests: M5 native-object smoke gate 2026-11-12 13:31:23 +00:00
arti 74d42cdad6 docs: M5 native object path and conformance plan 2026-11-12 13:16:14 +00:00
183 changed files with 25449 additions and 392 deletions

No files matched your search

+1144 -134
View File
File diff suppressed because it is too large. Load diff
@@ -326,8 +326,8 @@ Compile `layout-ti.c` (the `Display`/`Screen`/`XImage`/`XEvent` offset functions
- [ ] **Step 1: Correct and extend the symbol table**
- `XMapWindow = 0x3FD64F60`; add `XRaiseWindow = 0x3FD645B0` (not `XMapRaised`; the ROM entry sends ConfigureWindow with `CWStackMode=Above`). If a client wants map-and-raise, call `XMapWindow` then `XRaiseWindow`.
- Add the termtris-proven entries: `XSelectInput 0x3FD97D50`, `XCreateGC 0x3F997000`, `XSetForeground 0x3FD99A60`, `XFillRectangle 0x3F99E8F0`, `XDrawString 0x3FDA0000`, `XNextEvent 0x3F9C1CF0`, `XLookupString 0x3F9A9C30`, `XFlush 0x3F9B1030`, `XPending 0x3FD67620`, `XGetInputFocus 0x3FD55210`, `XLoadFont 0x3FD4AE80`, `XCopyArea 0x3FD3E220`, `sleep 0x3FB33A20`.
- Note: `XLoadFont`/`XCopyArea` are **not** in the pinned termtris `xlib.h`; they are ROM-validated by their request builders (OpenFont opcode 45 and CopyArea opcode 62), as `symbols/README.md` records.
- Add the termtris-proven entries: `XSelectInput 0x3FD97D50`, `XCreateGC 0x3F997000`, `XSetForeground 0x3FD99A60`, `XFillRectangle 0x3F99E8F0`, `XDrawString 0x3FDA0000`, `XNextEvent 0x3F9C1CF0`, `XLookupString 0x3F9A9C30`, `XFlush 0x3F9B1030`, `XPending 0x3FD67620`, `XGetInputFocus 0x3FD55210`, `sleep 0x3FB33A20` (all in the pinned termtris `xlib.h`).
- Note: `XLoadFont 0x3FD4AE80` and `XCopyArea 0x3FD3E220` are **not** termtris-proven and are **not** in the pinned termtris `xlib.h`; add them only because they are ROM-validated by their request builders (OpenFont opcode 45 and CopyArea opcode 62), as `symbols/README.md` records.
- Extract/validate the `XImage` entries (`XCreateImage`, `XPutImage`, `XDestroyImage`, optional `XGetImage`) and `XSetErrorHandler`/`XSetIOErrorHandler` from the ROM (Ghidra/`ptr_constants.py`, the `XPutImage`/`XGetImage` strings at `0x3F9D0E80`/`0x3FD567A0`). Do not guess an address; if an entry cannot be validated, report it and use the fallback (the termtris text client) for that part.
- Update `scripts/m3/xhello.c`/the comments to call the true `XMapWindow` (`0x3FD64F60`), the M3 `dis-roundtrip.sh` stub expectation, and the M3 docs. Do not use `0x3FD645B0` as a mapping call. Re-run the M3 MAME/dis34 gates; the window must still appear, and record whether the old `0x3FD645B0` pass depended on server-side create/configure behavior.
@@ -545,4 +545,4 @@ Do not force-push, merge into `m0`, or change the default; the controller update
## Execution Handoff
M4 closes the remaining Xlib path to a real image/event client and a full-game integration. M5 owns the native COFF/MCCodeEmitter, floats, varargs, bitfields, `long long`, the `JR`/branch-relaxation code-size pass, MMTM/MMFM, and deeper libc/runtime coverage. The compiler repo is canonical for target code; this project repo holds the plans, wrappers, symbols and integration tests. The pinned `termtris` tree is test-only (GPLv3), not part of the compiler or project distribution.
M4 closes the remaining Xlib path to a real image/event client and a full-game integration. M5 owns the native TI-COFF/MCCodeEmitter path, `JR`/branch relaxation, MMTM/MMFM, `alloca`/`byval`/narrow returns/mem intrinsics, and the first conformance tier; M6 owns floats, `long long`, general varargs, bitfields, aggregates by value, debug info, the wider Xlib surface and deeper libc/runtime coverage. The compiler repo is canonical for target code; this project repo holds the plans, wrappers, symbols and integration tests. The pinned `termtris` tree is test-only (GPLv3), not part of the compiler or project distribution.
@@ -0,0 +1,641 @@
# TMS34010 M5 — Native COFF Object Path, Code-Size/ABI Robustness, and Conformance Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
>
> **Status note (2026-11-13):** the SDD ledger
> `.superpowers/sdd/2026-11-12-tms34010-m5-native-object-path-and-conformance/progress.md`
> is authoritative. All M5 tasks are complete; the checkboxes below are kept
> as the original plan record. M5 re-scoped floats/bitfields/`long long`/
> general varargs/debug info to M6; `byval` is an M5 form.
**Goal:** `llc -march=tms34010 -filetype=obj` produces TI-COFF objects that GSPLNK links and the existing loader runs, with `JR`/relaxation, `MMTM`/`MMFM`, `alloca`/`byval`/narrow returns, `memcpy`/`memset`, the `-switch-to-lookup=false` policy removed (and the remaining `-replexitval=never` policy documented and verified until i64 arrives), and a pinned conformance tier (LLVM `CodeGen/Generic`, GCC c-torture, c-testsuite) proving integer/control-flow behavior in MAME.
**Architecture:** M5 keeps the M4 assembly path as the oracle and adds the native MC path beside it. The MC layer (`MCCodeEmitter`, `MCAsmBackend`, a TI-COFF `MCObjectWriter`, `MCAsmParser`/`MCDisassembler`) feeds `llc -filetype=obj`; GSPLNK still links, and the existing COFF loader still runs. Code-size/ABI work is layered on the native path: `JR` relaxation, `MMTM`/`MMFM` register-list saves, dynamic `alloca`, `byval`, narrow returns, and `memcpy`/`memset`. A conformance harness compiles pinned external test suites with the M5 pipeline, runs them in MAME through a small entry/`printf`/`exit`/`abort` shim, and classifies unsupported-feature tests explicitly. The `-switch-to-lookup=false` policy is removed by fixing the switch-table GEP normalization; `-replexitval=never` stays as a documented `tms-clang` TMS34010 policy until i64/M6, with an `llc` diagnostic for the unsupported i33 multiply.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m5`), C++17, CMake/Ninja, `llc`, `llvm-mc`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox (oracle/fallback), the dwt COFF loader, MAME, `dis34`, `llvm-lit`/FileCheck, the 1987 TI compiler as a differential oracle, pinned GCC 16.2 c-torture and c-testsuite.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§7, §8, M5); the M4 plan `docs/superpowers/plans/2026-11-12-tms34010-m4-xlib-image-events-and-termtris.md` is the handoff.
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `m5`, created from `m4` at `de5a365596c819a1902e58b989e18be85865219a`. Project work happens in **`tms-c-compiler`**, branch `m5`, created from `m4` at `5d980dc6e3317dd60a725e1188657e9d6a9d1d3e` plus the M5 plan commit. Do not merge `m0`/`m1`/`m2`/`m3`/`m4`; do not change either default branch.
- Use upstream LLVM `llvmorg-23.1.5`; keep the fork minimal against upstream. Use the existing `build/llvm-clean` and `build/llvm-clean-build`.
- The M2–M4 TI ABI is unchanged: A8 return, A13 frame pointer, A14 stack pointer, A15 system stack, `RETS 2/0`, `FS1 = 32`, `FS0 = 16`.
- **Native object path:** `llc -march=tms34010 -filetype=obj` emits TI-COFF objects that GSPLNK 2.00 links; the existing loader runs the linked image. No new linker is added in M5. The M4 asm path (`-filetype=asm` → GSPA/GSPLNK) remains the oracle and fallback until the native path passes the full M4 gates; do not delete GSPA/GSPLNK.
- Every M2/M3/M4 gate must stay green. Add `m5-*` lit tests and `scripts/tests/m5/*` gates. The M4 tests are the acceptance for the native path, not just the hand-written unit tests.
- **M5 scope:** native COFF, `JR`/relaxation, `MMTM`/`MMFM`, `alloca`, `byval`, narrow `i8`/`i16` returns, `memcpy`/`memset`, removal of the `-switch-to-lookup=false` driver policy, a documented `tms-clang` `-replexitval=never` policy plus an `llc` diagnostic (until i64/M6), and the conformance tier.
- **M5 non-goals (M6):** floats/double, `long long`/i64 (and therefore removal of the i33/`-replexitval` workaround), general varargs (`va_list`/`va_start`/`va_arg`; the M4 contiguous `&last_fixed` pattern remains), bitfields, structs/unions by value, `sret`, aggregate returns, debug info, the wider Xlib surface, and real-hardware-only validation.
- **Conformance is test-only:** pin GCC 16.2.0 `gcc.c-torture/execute` (`https://ftp.gnu.org/gnu/gcc/gcc-16.2.0/gcc-16.2.0.tar.xz`, SHA-256 recorded by the fetch script) and c-testsuite commit `5c7275656d751de0e68b2d340a95b5681858ed07`. The GCC version is only the corpus source; the compiler under test is `tms-clang`, and the feature classifier skips tests outside the M5 language subset. Keep their licenses/COPYING; `vendor/conformance` is ignored and never distributed. A feature classifier must skip unsupported features with a recorded reason; no gate may silently pass a skipped test as a pass.
- The native object/relocation model uses **bit addresses** (the TMS34010 program space); every relocation addend is a bit offset. GSPLNK's linked COFF and `dis34` are the format/encoding oracles.
- Do not force-push, merge into `m0`, or change the default. Push `m5` in both repos only after the final gate run and review.
## Review Focus
1. **TI-COFF relocation/symbol/bit-addend correctness.** A wrong section index, symbol value, or bit addend links plausible but wrong code. The tests are the GSPLNK link plus the loader/MAME run for a cross-section `MOVI`/`CALLA` (Task 2) and the full M4 programs through the native path (Task 4).
2. **MC encoding exactness.** A wrong `.td` encoding or operand order is silent in the object. The tests are `llvm-mc -show-encoding` and a `dis34` round-trip over the full supported instruction table, compared with the GSPA encodings (Task 3).
3. **`JR`/branch relaxation.** Relaxing a branch can change reach or direction. The tests are short/long branch cases, the M3 loop in MAME, and a code-size measurement (Task 5).
4. **`MMTM`/`MMFM` frame save/restore.** A wrong register list corrupts the callee's A14/A15 or a saved A register. The tests are callee-save/args/nested-call cases and the M2/M3 MAME gates (Task 6).
5. **Conformance classifier, shim, and expected results.** A skip for the wrong reason, a `printf` bug, or a vacuous output compare hides real failures. The tests are known-pass/known-fail/skip controls and an output-mismatch control (Tasks 9–12).
---
### Task 1: M5 branches and the native-object smoke
**Files:**
- Create: `build/llvm-clean/llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCCodeEmitter.cpp`, `TMS34010MCCodeEmitter.h`, `TMS34010MCAsmBackend.cpp`, `TMS34010MCAsmBackend.h`, `TMS34010MCObjectWriter.cpp`, `TMS34010MCObjectWriter.h`
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/MCTargetDesc/CMakeLists.txt`, `MCTargetDesc/TMS34010MCTargetDesc.cpp`
- Test: `build/llvm-clean/llvm/test/CodeGen/TMS34010/m5-object-smoke.ll`, `scripts/tests/m5/object-smoke.sh`
**Interfaces:**
- Consumes: `TMS34010MCInstLower`, `TMS34010MCAsmInfo`, the M4 `.td` encodings.
- Produces: `MCCodeEmitter *createTMS34010MCCodeEmitter(const MCInstrInfo &MII, const MCRegisterInfo &MRI)`, `MCAsmBackend *createTMS34010MCAsmBackend(const Target &T)`, and `TMS34010MCAsmBackend::createObjectWriter(raw_pwrite_stream &OS)` returning a TI-COFF writer.
- [ ] **Step 1: Write the failing smoke test**
`m5-object-smoke.ll`:
```llvm
; RUN: llc -march=tms34010 -filetype=obj < %s -o %t.o
; RUN: test -s %t.o
; RUN: llc -march=tms34010 -filetype=asm < %s -o %t.s
; RUN: grep -q 'RETS 2' %t.s
define i32 @f(i32 %a) {
%r = add i32 %a, 1
ret i32 %r
}
```
`scripts/tests/m5/object-smoke.sh` builds the same IR with `llc -filetype=obj`, extracts the `.text` bytes using the COFF header the implementer writes, and compares them with the GSPA-assembled `.text` from `scripts/m4/run.sh`-style assembly. The script must fail if the object is empty, if the `.text` bytes differ, or if `llc` exits nonzero.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llc -march=tms34010 -filetype=obj /tmp/m5-smoke.ll -o /tmp/m5-smoke.o`
Expected: `llc: error: createMCCodeEmitter failed`.
- [ ] **Step 3: Implement the minimal MC layer**
Add a `TMS34010MCCodeEmitter` using the TableGen `getBinaryCodeForInstr` for `RETS`, `MOVI`, `MOVE`, `ADDI`, and `SETF`; a `TMS34010MCAsmBackend` with `getFixupKindInfo`, `applyFixup`, `writeNopData`, and `createObjectWriter`; and a `TMS34010COFFObjectWriter` that writes a minimal TI-COFF header, a `.text` section, one symbol, and no relocations. Register the emitter and backend in `LLVMInitializeTMS34010TargetMC`.
The TI-COFF header/section fields must match the GSPA object for this smoke function (machine, section count, optional-header size 0, section flags, raw-data size); the object writer is the only new format code. Do not invent a new object format.
- [ ] **Step 4: Run the smoke test green**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m5-object-smoke.ll
scripts/tests/m5/object-smoke.sh
```
Expected: both PASS; the object is non-empty and the `.text` bytes match GSPA.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010/MCTargetDesc llvm/test/CodeGen/TMS34010/m5-object-smoke.ll
git -C build/llvm-clean commit -m "tms34010: add the minimal MC object path"
git add scripts/tests/m5/object-smoke.sh
git commit -m "tests: M5 native-object smoke gate"
```
### Task 2: TI-COFF sections, symbols, relocations, and GSPLNK link
**Files:**
- Modify: `TMS34010MCObjectWriter.cpp/.h`, `TMS34010MCAsmBackend.cpp`
- Create: `scripts/m5/native-link.c`, `scripts/m5/native-entry.asm`, `scripts/m5/native-link.cmd`, `scripts/tests/m5/native-link.sh`
- Test: `scripts/tests/m5/native-link.sh`
**Interfaces:**
- Consumes: Task 1's writer/encoder.
- Produces: a TI-COFF object with `.text`/`.data`/`.bss` sections, a symbol table, and absolute/bit-addend relocations that GSPLNK 2.00 links into the existing loader image.
- [ ] **Step 1: Write the failing native-link test**
`native-link.c`:
```c
int native_value(void) { return 42; }
```
`native-entry.asm` sets FS0/FS1, A14/A13, calls `_native_value`, stores A8 at `0x018A8000`, and `rets`. The test runs:
```sh
scripts/tms-clang -O0 -o build/m5-native/native-link.ll scripts/m5/native-link.c
build/llvm-clean-build/bin/llc -march=tms34010 -O0 -filetype=obj build/m5-native/native-link.ll -o build/m5-native/native-link.o
# assemble the entry with GSPA, then GSPLNK native-link.o + entry.o
# load the linked COFF in MAME and require 0x018A8000 == 42
```
The first run must fail at GSPLNK (unknown/malformed object) or at the loader (wrong relocation).
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/native-link.sh`
Expected: GSPLNK/loader failure on the object, not a `llc` encoding failure.
- [ ] **Step 3: Implement sections, symbols, and relocations**
Write the TI-COFF section headers and raw data for `.text`/`.data`/`.bss`; emit the symbol table entries for `_native_value`, `_native_entry`, and the section symbols; record relocations for `CALLA`/`MOVI` symbol operands as **bit-address** addends. Match the GSPA/GSPLNK COFF conventions (machine, flags, relocation types, symbol value/section fields). The existing `build/m3/m3.coff`/`m4` COFFs and the loader parser are the format oracle.
- [ ] **Step 4: Run the native-link test green**
Run: `scripts/tests/m5/native-link.sh`
Expected: GSPLNK links; the loader reports `status=0`; MAME reads `0x018A8000 == 42`; `dis34` decodes the linked `_native_value`.
- [ ] **Step 5: Add the cross-section relocation case**
Extend `native-link.c` with a `const char *msg = "native";` and a function that returns `msg[0]`/calls a second function, so the object needs a `.data` symbol relocation and a cross-section `CALLA`. Require the MAME marker / `dis34` to prove the linked bit addresses, then commit.
- [ ] **Step 6: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010/MCTargetDesc
git -C build/llvm-clean commit -m "tms34010: linkable TI-COFF objects"
git add scripts/m5/native-link.c scripts/m5/native-entry.asm scripts/m5/native-link.cmd scripts/tests/m5/native-link.sh
git commit -m "tests: M5 native COFF link gate"
```
### Task 3: Full MC emitter, assembler, disassembler, and `llvm-mc` round-trip
**Files:**
- Modify: `TMS34010MCCodeEmitter.cpp/.h`, `TMS34010InstrInfo.td`, `TMS34010.td`, `MCTargetDesc/CMakeLists.txt`, `MCTargetDesc/TMS34010MCTargetDesc.cpp`
- Create: `MCTargetDesc/TMS34010AsmParser.cpp/.h`, `MCTargetDesc/TMS34010Disassembler.cpp/.h`, `llvm/test/MC/TMS34010/*.s`, `scripts/tests/m5/mc-roundtrip.sh`
- Test: `llvm/test/MC/TMS34010/encodings.s`, `scripts/tests/m5/mc-roundtrip.sh`
**Interfaces:**
- Consumes: Task 1/2's emitter/backend; the M4 instruction set.
- Produces: `llvm-mc -triple=tms34010` encoding/decoding for every supported instruction, with `-show-encoding` matching GSPA/`dis34`.
- [ ] **Step 1: Write the failing encoding test**
`encodings.s` contains one instruction per supported mnemonic/operand shape with the expected GSPA/`dis34` encoding:
```asm
; RUN: llvm-mc -triple=tms34010 -show-encoding %s | FileCheck %s
; CHECK: add a0, a1
; CHECK-NEXT: encoding: [0x00,0x00]
; ... RETS, MOVI, MOVE, MOVB, ADDI, CMPI, JAUC, CALL, CALLA, SETF, MMTM, MMFM, JR
```
`mc-roundtrip.sh` also assembles with `llvm-mc -filetype=obj`, extracts the `.text`, and requires `dis34` to reproduce the source mnemonics/operands.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-mc -triple=tms34010 -show-encoding build/llvm-clean/llvm/test/MC/TMS34010/encodings.s`
Expected: `llvm-mc` missing or `unable to create target`.
- [ ] **Step 3: Implement the full emitter and parser/disassembler**
Add the TableGen `-gen-asm-matcher`/`-gen-disassembler` outputs to `MCTargetDesc/CMakeLists.txt`; implement `TMS34010AsmParser` (operand parsing for A/B registers, immediates, symbol/bit-address expressions), `TMS34010Disassembler` (the inverse of the `.td` encodings), and the full `TMS34010MCCodeEmitter`. Build `llvm-mc` in `build/llvm-clean-build`.
The M4 asm text/GSPA listing and `dis34` are the encodings oracle. Do not change an existing M2–M4 instruction encoding to make the parser easier; fix the parser or the `.td` operand shape.
- [ ] **Step 4: Run the MC gate green**
```sh
ninja -C build/llvm-clean-build llvm-mc
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010
scripts/tests/m5/mc-roundtrip.sh
```
Expected: PASS for the full supported table; `dis34` round-trip for the object bytes.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010/MCTargetDesc llvm/lib/Target/TMS34010/TMS34010.td llvm/lib/Target/TMS34010/TMS34010InstrInfo.td llvm/test/MC/TMS34010
git -C build/llvm-clean commit -m "tms34010: full MC assembler/encoder/disassembler"
git add scripts/tests/m5/mc-roundtrip.sh
git commit -m "tests: M5 MC round-trip gate"
```
### Task 4: Native object pipeline and the M4 regressions
**Files:**
- Create: `scripts/m5/native.sh`, `scripts/tests/m5/native.sh`
- Modify: `scripts/m4/run.sh` (add `M4_NATIVE=1`, default unchanged)
- Test: `scripts/tests/m5/native.sh`
**Interfaces:**
- Consumes: Tasks 1–3; the M4 `run.sh` harness.
- Produces: the M4 xshow and termtris programs built with `llc -filetype=obj` + GSPLNK, linked by the existing loader, passing the same MAME markers. The asm path remains the default.
- [ ] **Step 1: Write the failing native-pipeline test**
`scripts/tests/m5/native.sh` builds `scripts/m4/xshow.c` + `xgfix.c` and the termtris six TUs with `M4_NATIVE=1` (object path), links with GSPLNK, runs the M4 MAME checks, and requires the same markers (`xerrors=0`, key, focus; termtris loops/events/quit/focus). The first run must fail because the object path cannot yet link the full programs.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/native.sh`
Expected: the object/link step fails on an unsupported relocation/section (not on an asm encoding).
- [ ] **Step 3: Extend the object path for the full programs**
Add the `.cinit` section, common/weak symbols if needed, the `MOVI`/`CALLA`/`CALL`/`MMTM`/`MMFM`/`.bss` relocations, and the `scripts/m5/native.sh` compile/link driver. Keep the GSPA/GSPLNK asm path byte-identical; add a `dis34` comparison of the native and asm linked `.text` where feasible.
- [ ] **Step 4: Run the native M4 gates green**
```sh
scripts/tests/m5/native.sh
scripts/tests/m4/run.sh
scripts/tests/m4/termtris.sh
```
Expected: the native xshow/termtris markers match the asm path; the M4 default gates still pass.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010
git -C build/llvm-clean commit -m "tms34010: native object path for M4 programs"
git add scripts/m5/native.sh scripts/tests/m5/native.sh scripts/m4/run.sh
git commit -m "tests: M5 native pipeline and M4 regressions"
```
### Task 5: `JR` and branch relaxation
**Files:**
- Modify: `TMS34010InstrInfo.td` (`JR`), `TMS34010InstrInfo.cpp/.h`, `TMS34010MCAsmBackend.cpp`
- Test: `llvm/test/CodeGen/TMS34010/m5-jr.ll`, `scripts/tests/m5/jr.sh`
- Reuse: the M3 branch/loop MAME gate.
**Interfaces:**
- Consumes: Task 4's native path.
- Produces: relative `JR` for in-range local branches and `JAUC`/`JA<cc>` for out-of-range/absolute branches; the MC backend relaxes iteratively.
- [ ] **Step 1: Write the failing test**
`m5-jr.ll` has a short loop whose body fits the `JR` range and a function with a far branch. Check `JR` in the short body and `JAUC` in the far body; `scripts/tests/m5/jr.sh` runs the M3 `branch.c` loop in MAME and records the linked `.text` size.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m5-jr.ll`
Expected: no `JR` selection / relaxation failure.
- [ ] **Step 3: Implement `JR` and relaxation**
Add the `JR` encoding/operand (signed bit displacement), select it for local conditional/unconditional branches, and implement `TMS34010MCAsmBackend::mayNeedRelaxation`/`relaxInstruction` to widen to `JA*` when the displacement is out of range. Update `getInstSizeInBytes`. Keep the M3 `JAcc` labels/branch behavior; the `LBB` labels remain GSPA-safe.
- [ ] **Step 4: Run the JR gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m5-jr.ll
scripts/tests/m5/jr.sh
scripts/tests/m3/run.sh
```
Expected: PASS; the short loop uses `JR`; the far branch uses `JA`; the M3 MAME values are unchanged; the code size is recorded.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m5-jr.ll
git -C build/llvm-clean commit -m "tms34010: JR branches and relaxation"
git add scripts/tests/m5/jr.sh
git commit -m "tests: M5 JR relaxation gate"
```
### Task 6: `MMTM`/`MMFM` register-list saves
**Files:**
- Modify: `TMS34010FrameLowering.cpp`, `TMS34010InstrInfo.td`, `TMS34010RegisterInfo.cpp/.h`
- Test: `llvm/test/CodeGen/TMS34010/m5-mmtm.ll`, `scripts/tests/m5/mmtm.sh`
- Reuse: `m2-callee-save.ll`, the M2/M3 MAME calls.
**Interfaces:**
- Consumes: Task 4's native path.
- Produces: prologue/epilogue `MMTM SP, ...`/`MMFM SP, ...` for callee-saved A registers, with the same A14/A15 old-STK and `RETS 2` ABI as the per-register pushes.
- [ ] **Step 1: Write the failing test**
`m5-mmtm.ll` has a callee that uses A0/A1/A3/A5 and is called from a function that keeps values live across it. Require `MMTM SP, ...`/`MMFM SP, ...` and the ABI's old-STK/`RETS 2`; `mmtm.sh` runs the M2 `caller`/`callee` and M3 `xhello` in MAME.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m5-mmtm.ll`
Expected: per-register pushes, no `MMTM`/`MMFM`.
- [ ] **Step 3: Implement the register-list saves**
Emit the callee-save set as one `MMTM SP, ...` in the prologue and `MMFM SP, ...` in the epilogue, keeping the old-STK layout and the A8 return. The register list must be ascending/valid for the `.td` encoding; use the existing `.td` `MMTM`/`MMFM` definitions or add them. Do not change the ABI-visible order of the old-STK/FP slots.
- [ ] **Step 4: Run the MMTM gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m5-mmtm.ll
scripts/tests/m5/mmtm.sh
scripts/tests/m2/run.sh
scripts/tests/m3/run.sh
```
Expected: PASS; the M2/M3 returned values and ABI markers are unchanged; `dis34` shows the register list.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m5-mmtm.ll
git -C build/llvm-clean commit -m "tms34010: MMTM/MMFM register-list saves"
git add scripts/tests/m5/mmtm.sh
git commit -m "tests: M5 MMTM/MMFM gate"
```
### Task 7: `alloca`, `byval`, narrow returns, and `memcpy`/`memset`
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010FrameLowering.cpp`, `TMS34010InstrInfo.td`
- Test: `llvm/test/CodeGen/TMS34010/m5-alloca.ll`, `m5-byval.ll`, `m5-narrow-ret.ll`, `m5-memintrin.ll`, `scripts/tests/m5/robust.sh`
- Reuse: the M2/M3 MAME harness.
**Interfaces:**
- Consumes: Task 4's native path; the M4 `i8`/`i16` argument support.
- Produces: dynamic `alloca` (A14 adjustment/restore), `byval` argument copies, `i8`/`i16` returns in A8 with the correct extension, and `memcpy`/`memset` lowered to the ROM/`rts.lib` entries or a byte/word loop.
- [ ] **Step 1: Write the failing tests**
- `m5-alloca.ll`: `alloca i32, i32 %n` in a loop, store/load, return a checksum.
- `m5-byval.ll`: `byval` struct argument, callee reads the fields.
- `m5-narrow-ret.ll`: `define zeroext i8 @f()` / `signext i16`, caller compares the value.
- `m5-memintrin.ll`: `llvm.memcpy`/`llvm.memset` of known sizes.
Run the focused lit tests red; the expected failures are the current `Cannot select`/rejection diagnostics.
- [ ] **Step 2: Run them red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m5-(alloca|byval|narrow-ret|memintrin).ll`
Expected: the current limitations (dynamic alloca, byval, narrow returns, memintrin) fail.
- [ ] **Step 3: Implement the lowering**
Add dynamic stack allocation/restore (A14 and the frame), `byval` stack copies, narrow return extension/truncation in A8, and `memcpy`/`memset` selection (the validated ROM `blit_copy`/`memset` entries or an inline loop). Keep the M4 argument/locals ABI and the M2/M3 frames. Add MAME markers for the checksums/bytes.
- [ ] **Step 4: Run the robustness gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010 --filter='m5-(alloca|byval|narrow-ret|memintrin)'
scripts/tests/m5/robust.sh
scripts/tests/m2/run.sh
scripts/tests/m3/run.sh
```
Expected: PASS; the alloca/byval/narrow-return/memintrin markers are correct; the M2/M3 gates are unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010
git -C build/llvm-clean commit -m "tms34010: alloca, byval, narrow returns and mem intrinsics"
git add scripts/tests/m5/robust.sh
git commit -m "tests: M5 robustness gate"
```
### Task 8: Remove `-switch-to-lookup`, pin `-replexitval`, and harden the deferred edges
**Files:**
- Modify: `scripts/tms-clang`, `TMS34010ISelLowering.cpp/.h`, `TMS34010TargetMachine.cpp`, `tools/tms-bitaddr` (the switch-table GEP)
- Modify: `build/llvm-clean/llvm/test/CodeGen/TMS34010/m3-cmpi.ll`, `scripts/m3/dis-roundtrip.sh` (tighten the M3 carry-forward tests)
- Test: `scripts/tests/m5/policy.sh`, `llvm/test/CodeGen/TMS34010/m5-policy.ll`, `m5-reject-static-vararg.ll`
**Interfaces:**
- Consumes: the M4 `-replexitval=never`/`-switch-to-lookup=false` policies; the static-variadic gap; the private-label token.
- Produces: an ordinary `tms-clang -O2` that compiles the M4 **switch** without the driver flag; a documented `tms-clang` TMS34010 `-replexitval=never` policy with an `llc` diagnostic for an i33 multiply reached through the raw pipeline; a diagnostic for static variadic definitions at `-O2`; a long-private-name two-TU link test; the tightened `m3-cmpi` MOVI order and the M3 push-register check.
- [ ] **Step 1: Write the failing policy test**
`policy.sh` compiles the M4 `switch.c` and a static variadic function with the **default** `tms-clang -O2` after removing `-switch-to-lookup=false` from the wrapper (temporarily or via a copy), and separately runs the raw `opt -passes='default<O2>'` + `llc` path on an i33 loop without `-replexitval=never`. Require the switch to compile without a byte-indexed table, the static variadic definition to be rejected/kept correctly, and the raw i33 path to fail with a clear target diagnostic (not `Cannot select`/an assertion).
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/policy.sh`
Expected: the byte-indexed switch-table miscompile, the static variadic miscompile, or the raw i33 `Cannot select`.
- [ ] **Step 3: Implement the target/verifier fixes**
Fix the switch-table GEP in `tms-bitaddr`/the target's GEP normalization so a `getelementptr i8, ptr @switch.table, i32 %idx` after `--scale` is not treated as a bit offset; remove `-switch-to-lookup=false` from `scripts/tms-clang` and prove the M4 `switch.c`/termtris board still pass. Keep `-replexitval=never` in `tms-clang` as a documented TMS34010 policy (i64/M6 will remove it); add an `llc`/target diagnostic for the i33/`umul_lohi` shape reached through the raw pipeline. Add the static-variadic `-O2` diagnostic (reject `static` variadic definitions or keep `...` through the optimizer). Tighten `m3-cmpi.ll` with `CHECK`/`CHECK-NEXT` MOVI order and replace the M3 nine-argument push-register check with the M4-style operand parsing. Add the long-private-name two-TU link test.
- [ ] **Step 4: Run the policy/hardening gate green**
```sh
scripts/tests/m5/policy.sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
scripts/tests/m4/run.sh
```
Expected: the switch compiles without the flag; the raw i33 path fails with a clear diagnostic; the M3/M4 gates remain green.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m3-cmpi.ll
git -C build/llvm-clean commit -m "tms34010: remove switch-to-lookup; pin replexitval edges"
git add scripts/tms-clang tools/tms-bitaddr scripts/tests/m5/policy.sh scripts/m3/dis-roundtrip.sh
git commit -m "tests: M5 policy and hardening gate"
```
### Task 9: Conformance harness, shim, manifest, and feature classifier
**Files:**
- Create: `scripts/fetch-conformance.sh`, `scripts/tests/m5/conformance/run.sh`, `shim.c`, `entry.asm`, `classify.sh`, `manifest.tsv`, `skip.tsv`, `c-torture.sh`, `c-testsuite.sh`
- Create: `vendor/conformance` (ignored; pinned GCC 16.2.0 c-torture and c-testsuite `5c7275656d751de0e68b2d340a95b5681858ed07`)
- Test: `scripts/tests/m5/conformance/selftest.sh`
**Interfaces:**
- Consumes: Tasks 4–8's native/asm pipeline; the M4 contiguous varargs; the ROM `blit_copy`/`rts.lib`.
- Produces: a runner that compiles one test, links the shim/entry, runs it in MAME, captures a status/output buffer, and compares the expected result. The manifest row format is `test_id<TAB>suite<TAB>expected<TAB>features<TAB>skip_reason`.
- [ ] **Step 1: Write the failing selftest**
`selftest.sh` contains three tiny C cases:
```c
/* pass */ int main(void) { return 0; }
/* fail */ int main(void) { return 7; }
/* print */ int main(void) { printf("ok\n"); return 0; }
```
The first run must fail because the runner/shim/log capture does not exist.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/conformance/selftest.sh`
Expected: missing runner/shim or an unreadable result.
- [ ] **Step 3: Implement the shim and runner**
`shim.c` defines `printf`/`putchar`/`puts` with the M4 contiguous `&fmt` walk, writing to a fixed output buffer; `exit`/`abort` set the status/marker; `entry.asm` calls `main(1, argv)`, stores the output buffer/status at the M4 marker addresses, and returns. `run.sh` compiles the test + shim + entry, links (native if available, asm fallback), runs MAME, reads the status/output, and compares the manifest/expected. `classify.sh` scans a source for unsupported features (`float`, `double`, `long long`, `int64`, `bitfield`, `va_list`, `va_start`, `va_arg`, `alloca`, `setjmp`, `signal`, `wchar`, `%f`, `%e`, `%g`, `%ll`, `%L`, files) and emits a skip reason.
`fetch-conformance.sh` pins GCC 16.2.0 (`gcc-16.2.0.tar.xz`, SHA-256 checked) and the c-testsuite commit; it preserves `COPYING`, uses `vendor/conformance`, and never writes into the repo.
- [ ] **Step 4: Run the selftest green**
Run: `scripts/tests/m5/conformance/selftest.sh`
Expected: PASS for the pass/print cases, FAIL (expected) for the fail case, and the output compare catches a mismatch.
- [ ] **Step 5: Commit**
```sh
git add scripts/fetch-conformance.sh scripts/tests/m5/conformance
git commit -m "tests: M5 conformance harness and shim"
```
### Task 10: `CodeGen/Generic` no-crash sweep
**Files:**
- Create: `scripts/tests/m5/generic.sh`, `generic-allowlist.txt`, `generic-expected-fail.txt`
- Test: `scripts/tests/m5/generic.sh`
**Interfaces:**
- Consumes: Task 9's manifest/classifier; the LLVM `test/CodeGen/Generic` 200 files.
- Produces: a curated allowlist gate and a broad no-crash report; every failure is classified as unsupported/known/unexpected.
- [ ] **Step 1: Write the failing generic gate**
`generic.sh` runs `llc -march=tms34010 -filetype=asm -O0` on the allowlist (integer/control/load-store/call/PHI; no floats/vectors/atomics/i64/varargs/aggregates) and requires exit 0 and a non-empty asm; the broad sweep runs all 200 and writes `generic-report.txt` with `pass`/`unsupported`/`crash`. The first run must fail because the allowlist is empty/nonexistent.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/generic.sh`
Expected: `no allowlist` or a known crash.
- [ ] **Step 3: Seed the allowlist and expected-fail manifest**
Start with a small allowlist (the stress/PHI/load-store/bitcast tests that the M5 target can select) and record each broad-sweep failure with a reason. Do not put a crash in the expected-fail list; crashes are regressions.
- [ ] **Step 4: Run the generic gate green**
Run: `scripts/tests/m5/generic.sh`
Expected: allowlist PASS; broad sweep has no `crash` rows; `unsupported` rows have diagnostics.
- [ ] **Step 5: Commit**
```sh
git add scripts/tests/m5/generic.sh scripts/tests/m5/generic-allowlist.txt scripts/tests/m5/generic-expected-fail.txt
git commit -m "tests: M5 CodeGen/Generic no-crash sweep"
```
### Task 11: GCC 16.2 c-torture `execute` subset
**Files:**
- Create: `scripts/tests/m5/c-torture.sh`, `c-torture.list`
- Test: `scripts/tests/m5/c-torture.sh`
**Interfaces:**
- Consumes: Task 9's runner/shim/classifier; the pinned GCC c-torture `execute`.
- Produces: a curated allowlist of integer/control/array/pointer tests that return 0 or `abort`; the runner requires `main` 0 and no abort, in MAME.
- [ ] **Step 1: Write the failing c-torture gate**
`c-torture.sh` compiles each name in `c-torture.list` with `tms-clang -O0` (and a second `-O2` pass where supported), links the shim/entry, runs MAME, and requires `main` 0/no abort. The first run must fail because the list is empty.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/c-torture.sh`
Expected: `no c-torture.list` or the first test fails.
- [ ] **Step 3: Seed the list**
Select tests with the classifier (`int-control` only; no floats/i64/bitfields/varargs/aggregates/alloca/setjmp/signals/files), verify they compile on the host, and commit the list. Keep the list small enough to run in the M5 gate (target 40–60 tests); put the broader scan in a report mode.
- [ ] **Step 4: Run the c-torture gate green**
Run: `scripts/tests/m5/c-torture.sh`
Expected: PASS for the list; the report records skipped tests and reasons.
- [ ] **Step 5: Commit**
```sh
git add scripts/tests/m5/c-torture.sh scripts/tests/m5/c-torture.list
git commit -m "tests: M5 c-torture integer subset"
```
### Task 12: c-testsuite `single-exec` subset
**Files:**
- Create: `scripts/tests/m5/c-testsuite.sh`, `c-testsuite.list`, `c-testsuite.skip`
- Test: `scripts/tests/m5/c-testsuite.sh`
**Interfaces:**
- Consumes: Task 9's runner/shim/classifier; the pinned c-testsuite `single-exec` `.c`/`.expected`/`.tags`.
- Produces: a curated set whose stdout/stderr equals the `.expected` file; the official `tests/single-exec/*.c` interface; a skip list for unsupported features.
- [ ] **Step 1: Write the failing c-testsuite gate**
`c-testsuite.sh` runs each name in `c-testsuite.list` through the `single-exec` runner interface and compares the captured output with `.expected`. The first run must fail because the list is empty.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m5/c-testsuite.sh`
Expected: `no c-testsuite.list` or the first output mismatch.
- [ ] **Step 3: Seed the list and skip file**
Select `single-exec` tests tagged portable/integer/control/string that the classifier accepts; add the rest to `c-testsuite.skip` with a reason. The `printf` shim must handle the formats these tests use; a `%f`/`%ll`/wide test is skipped, not silently passed.
- [ ] **Step 4: Run the c-testsuite gate green**
Run: `scripts/tests/m5/c-testsuite.sh`
Expected: PASS for the list; skipped tests are reported with reasons; an output mismatch fails.
- [ ] **Step 5: Commit**
```sh
git add scripts/tests/m5/c-testsuite.sh scripts/tests/m5/c-testsuite.list scripts/tests/m5/c-testsuite.skip
git commit -m "tests: M5 c-testsuite output subset"
```
### Task 13: Docs, full gates, and push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `symbols/README.md` (if the native path adds symbols)
- Test: the full M5/M4/M3/M2 gate list
- [ ] **Step 1: Update the docs**
Document the native TI-COFF path (`llc -filetype=obj` → GSPLNK → loader), the MC/assembler/disassembler, `JR`/relaxation, `MMTM`/`MMFM`, `alloca`/`byval`/narrow returns/mem intrinsics, the removed driver policies, the conformance tiers (Generic/c-torture/c-testsuite, the classifier, the shim), the pinned test versions, and the M5/M6 boundary. Correct the plan's `XLoadFont`/`XCopyArea` note, the `xshow` right-edge wording, and the private-label GSPA 31-character caveat in the project docs.
- [ ] **Step 2: Run every gate**
```sh
ninja -C build/llvm-clean-build llc llvm-mc
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010 --filter='(m2|m3|m4|m5)-'
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010
scripts/tests/m5/object-smoke.sh
scripts/tests/m5/native-link.sh
scripts/tests/m5/mc-roundtrip.sh
scripts/tests/m5/native.sh
scripts/tests/m5/jr.sh
scripts/tests/m5/mmtm.sh
scripts/tests/m5/robust.sh
scripts/tests/m5/policy.sh
scripts/tests/m5/conformance/selftest.sh
scripts/tests/m5/generic.sh
scripts/tests/m5/c-torture.sh
scripts/tests/m5/c-testsuite.sh
scripts/tests/m4/run.sh
scripts/tests/m4/dis-roundtrip.sh
scripts/tests/m4/layout.sh
scripts/tests/m4/symbols.sh
scripts/tests/m4/termtris.sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
scripts/tests/m2/run.sh
tools/tms-bitaddr/tests/run.sh
```
All green; the conformance report has no unexpected crashes; skipped tests have reasons.
- [ ] **Step 3: Commit and push**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010 llvm/test/MC/TMS34010 TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M5 native object path, code-size and conformance"
git -C build/llvm-clean push origin m5
git add README.md symbols scripts/m5 scripts/tests/m5 scripts/tms-clang scripts/m3
git commit -m "tests/docs: M5 native object path and conformance"
git push origin m5
```
Do not force-push, merge into `m0`–`m4`, or change the default. The controller updates the default to `m5` after the final review only if the user asks.
---
## Execution Handoff
M5 delivers the native object path and the first external conformance tier while keeping the M4 asm path as the oracle. M6 owns floats/double, `long long`, general varargs (`va_list`), bitfields, structs by value, aggregate returns, debug info, the wider Xlib surface, and the full external suites. The compiler repo is canonical for target code; this project repo holds the plan, harness, pins, and integration tests. The pinned GCC/c-testsuite trees are test-only (GPL) and are not part of the compiler or project distribution.
@@ -0,0 +1,447 @@
# TMS34010 M6 — Floats, 64-bit Integers, General Varargs, Bitfields, and Aggregates Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** The compiler supports the TI C language surface that M5 deferred — `float`/`double`/`long double`, `long long`/i64, general `va_list`/`va_start`/`va_arg`, bitfields, and structs/unions by value with `sret`/aggregate returns — using the validated `flib.lib`/`rts.lib` runtime, with the conformance tier expanded to the newly supported features.
**Architecture:** M6 keeps the M5 native TI-COFF/GSPLNK path, the all-stack TI ABI, and the M5 asm oracle. The 64-bit and floating-point ABI follows the TI C guide: arguments are pushed on the program stack and widened to 32 bits; a `float`/`double`/`long long` return is written into a caller-allocated stack slot (the same hidden-return rule as struct returns); `long long` occupies two 32-bit slots. Float/double arithmetic and conversions lower to `FS$*`/`FD$*` calls in the TI `flib.lib`; the `rts.lib` supplies the remaining runtime. Bitfields use Clang's packed record layout (the target already sets `PackStruct=1`); aggregates use the M5 `byval`/hidden-return machinery. The conformance shim/classifier gain general varargs and drop the M6 feature skips.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m6`), C++17, CMake/Ninja, `llc`, `llvm-mc`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the TI `flib.lib`/`flibc.lib`/`rts.lib` (1990 SDK), the dwt COFF loader, MAME, `dis34`, `llvm-lit`/FileCheck, the 1987 TI compiler as a differential oracle, pinned GCC 16.2.0 c-torture and c-testsuite.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§4.2, §7.4–§7.5, §8; M6); the M5 plan `docs/superpowers/plans/2026-11-12-tms34010-m5-native-object-path-and-conformance.md` is the handoff.
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `m6`, created from `m5` at `f9c593ddd5bca0dc30cc2273c05a995100e576f3`. Project work happens in **`tms-c-compiler`**, branch `m6`, created from `m5` at `5ee3a6592c7d09e8c58635490077df0ef2d7fc99` plus the M6 plan commit. Do not merge into `m0`–`m5`; do not change the default (`m5`).
- Use upstream LLVM `llvmorg-23.1.5`; keep the fork minimal. Use the existing `build/llvm-clean` and `build/llvm-clean-build`.
- The M2–M5 TI ABI is unchanged: A8 scalar return, A13 FP, A14 STK, A15 system stack, `RETS 2/0`, `FS1 = 32`, `FS0 = 16` with the field-extension bit set (`SETF 16,1,0`).
- **Stack ABI:** all arguments are pushed on the program stack and widened to 32 bits; structs by value are rounded to 16 bits. `float`/`double`/`long long` and aggregate returns use a **caller-allocated program-stack slot** (the callee copies the result there), so the call site uses the old-STK save and `RETS 2`.
- **i64 ABI (to be confirmed by Task 1):** `long long` arguments occupy two 32-bit stack slots (low word first at the lower address, matching the TI endianness); the return is an 8-byte caller-allocated slot. If the 1990 C guide or `rts.lib` evidence shows a different TI 64-bit convention, Task 1 records the ruling and adjusts these rules before Tasks 2/6 use them.
- **Float/double:** arguments are 32-bit-widened stack slots (`float` one, `double` two); the return is the caller-allocated stack slot; arithmetic/compare/conversion lowers to the validated `FS$*`/`FD$*` entries in `flib.lib` (or a target sequence for a missing entry). Use the exact TI library names; do not invent libcalls.
- **General varargs:** the M4 contiguous `&last_fixed` pattern remains supported; M6 adds a real `va_list`/`va_start`/`va_arg` for the TI ABI. External variadic definitions (`sprintf`/`printf`) are supported at `-O2`; the M5 static-variadic restriction is lifted once the optimizer no longer drops `...`.
- **Bitfields:** the TI packed structure rules (fully packed; only the first object in an array is 16-bit aligned); Clang's target already sets `PackStruct=1`; verify/adjust the target record layout against the M4 `_Static_assert` offsets and the TI C guide.
- **Aggregates:** structs/unions by value use the 16-bit-rounded stack slots and the hidden return slot; `sret`/`byval`/aggregate returns are M6 (the M5 `byval` slot rule is 16-bit). Keep the M5 `alloca`/memcpy/memmove behavior.
- **Native object path:** TI COFF linked by GSPLNK; the existing loader. The asm path (`-filetype=asm` → GSPA/GSPLNK) remains the oracle; do not delete it.
- Every M2–M5 gate stays green; add `m6-*` lit tests and `scripts/tests/m6/*`. The M5 conformance harness/classifier/lists are the base; the M6 features remove their skips.
- **M6 non-goals (M7):** debug info, a native linker, the wider Xlib surface, real-hardware-only validation, and the full GCC/LLVM suites beyond the supported subset. Document the boundary. Ruling: the spec's M5 re-scope lists debug info as M6, but this plan splits it into M7 as an independent object/debug subsystem; the M6 language/runtime surface is already a complete milestone. Cost if wrong: debug info arrives one milestone later.
- No force-push, no merge into `m0`–`m5`, no default change. Push `m6` after the final gate run and review.
## Review Focus
1. **Float/double/i64 ABI.** A wrong stack/hidden-return layout corrupts every call and return. The tests are Task 1's ABI probe, Task 2's two-slot i64 call/return, and Task 3's float/double call/return in MAME.
2. **Bitfield packed layout.** A wrong bitfield offset or signedness silently reads/writes the wrong bits. The tests are Task 5's TI-offset static asserts and MAME bitfield checks.
3. **General varargs.** A wrong `va_list`/`va_arg` walk corrupts `printf`/`sprintf` output. The tests are Task 4's multi-format output and the expanded c-torture/c-testsuite output.
4. **Aggregates/sret.** A wrong hidden-return pointer or copy size corrupts struct returns. The tests are Task 6's by-value/sret MAME cases.
5. **Soft-float libcalls/constants.** A wrong `FS$`/`FD$` name, argument order, or constant pool entry produces wrong values. The tests are Task 3's `fadd`/`fmul`/`fcmp`/conversion MAME cases and Task 7's runtime.
---
### Task 1: M6 branches, ABI rules, and the soft-float/i64 probe
**Files:**
- Create: `scripts/m6/spike-probe.asm` (hand-written `FS$ADD`/`FD$ADD` and i64 stack probes), `scripts/m6/spike-entry.asm`, `scripts/m6/spike-check.lua`, `scripts/tests/m6/spike.sh`
- Create: `scripts/m6/flib-extract.sh` (or the equivalent extraction into `build/m6-sdk`)
- Modify: `build/llvm-clean/TMS34010.md` (the M6 ABI note), `README.md` (the M6 section)
- Test: `scripts/tests/m6/spike.sh`
**Interfaces:**
- Consumes: the M5 native TI-COFF/GSPLNK harness, the 1990 SDK `flib.lib`/`rts.lib`, the TI C guide.
- Produces: a written/committed ABI rule for i64/float/double args and hidden returns; a linked `flib.lib` probe proving the `FS$`/`FD$` ABI; the exact library symbol list and link line.
- [ ] **Step 1: Write the failing ABI probe**
`spike-probe.asm` pushes the `FS$ADD` float operands (1.5, 2.5) and the i64 two-slot operands on A14, calls the library entries, and stores the results at the M4 markers; `spike-entry.asm` sets FS0/FS1, A14/A13 and calls the probe. The C target does not support float/i64 yet (Tasks 2/3), so this probe is hand-written asm, not a C float call. `scripts/tests/m6/spike.sh` assembles/links with the 1990 `flib.lib`/`rts.lib` and runs the COFF in MAME. The first run must fail because the float/i64 ABI and the `flib` link are not wired.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/spike.sh`
Expected: a link/ABI failure (missing `FS$ADD`/`FD$ADD`, wrong hidden-return slot, or the `$` symbol rejected by GSPA).
- [ ] **Step 3: Extract and validate the library/ABI**
`flib-extract.sh` extracts `flib.lib`/`flibc.lib`/`rts.lib` from the 1990 SDK into `build/m6-sdk` and records the exact symbols (`FS$ADD`, `FS$SUB`, `FS$MUL`, `FS$DIV`, `FS$NEG`, `FS$EQ`…, `FD$ADD`, …, the conversion entries) and the `flib` stack ABI (operands on A14, result pushed); verify the `$` symbol handling with GSPA/GSPLNK and record the link line. Confirm the i64 two-slot/hidden-return and float/double hidden-return rules from the C guide/`flib` source.
- [ ] **Step 4: Write the ABI note and run the probe green**
Add the i64/float/double ABI rule to `TMS34010.md`/README (the exact stack order, hidden-return slot, `RETS 2`, library names). Run:
```sh
scripts/tests/m6/spike.sh
```
Expected: the `FS$ADD` result (e.g. 1.5+2.5 == 4.0) and the i64 sum are correct in MAME; the link line and symbol list are recorded.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M6 64-bit/float ABI notes"
git add scripts/m6 scripts/tests/m6/spike.sh README.md
git commit -m "tests: M6 float/i64 ABI probe"
```
### Task 2: `long long` / i64 arguments, returns, and arithmetic
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010InstrInfo.td`, `TMS34010FrameLowering.cpp`
- Test: `llvm/test/CodeGen/TMS34010/m6-i64.ll`, `scripts/tests/m6/i64.sh`
- Reuse: the M5 `byval`/hidden-return stack machinery.
**Interfaces:**
- Consumes: Task 1's i64 ABI rule; the M5 stack/frame.
- Produces: i64 formal/call arguments as two 32-bit slots; an 8-byte caller-allocated return slot; add/sub/and/or/xor/shift/compare and mul/div/rem (sequences or `flib`/`rts` helpers) with correct endianness; `RETS 2`.
- [ ] **Step 1: Write the failing i64 test**
`m6-i64.ll` defines `long long addll(long long, long long)`, `subll`, `mull`, `divll`, `remll`, shifts, and compares; checks the two-slot argument/return shape and the library/sequence. `i64.sh` runs `addll(0x12345678, 0x9ABCDEF0)`, `mull`, `divll`, `remll`, and signed shifts in MAME.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-i64.ll`
Expected: the M5 `only i32/pointer returns`/argument rejection.
- [ ] **Step 3: Implement i64**
Extend `CanLowerReturn`/`LowerReturn`/`LowerFormalArguments`/`LowerCall` for i64 with the Task 1 ABI (two slots, hidden 8-byte return, `RETS 2`). Implement the i64 arithmetic with the 32-bit halves (`ADD`/`ADDC`/`SUBB`, shifts, compares) and the validated helpers/sequences for mul/div/rem. Keep the endianness fixed and documented.
- [ ] **Step 4: Run the i64 gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-i64.ll
scripts/tests/m6/i64.sh
scripts/tests/m2/run.sh
scripts/tests/m3/run.sh
scripts/tests/m4/run.sh
```
Expected: PASS; the MAME values are correct; the M2–M4 gates are unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-i64.ll
git -C build/llvm-clean commit -m "tms34010: i64 arguments, returns and arithmetic"
git add scripts/tests/m6/i64.sh
git commit -m "tests: M6 i64 gate"
```
### Task 3: `float`/`double` soft-float via `flib.lib`
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010TargetMachine.cpp` (libcall names), `TMS34010InstrInfo.td` (constant pool/loads), `TMS34010AsmPrinter.cpp` (float constants), `TMS34010Subtarget`/TTI as needed
- Test: `llvm/test/CodeGen/TMS34010/m6-float.ll`, `scripts/tests/m6/float.sh`
- Reuse: Task 1's `flib` ABI/link.
**Interfaces:**
- Consumes: Task 1's `FS$`/`FD$` list and stack ABI; Task 2's hidden-return/stack slots.
- Produces: `f32`/`f64` arguments/returns, `FADD`/`FSUB`/`FMUL`/`FDIV`/`FNEG`, comparisons, and int↔float conversions via the exact `FS$`/`FD$` libcalls; constant-pool emission for float/double literals.
- [ ] **Step 1: Write the failing float test**
`m6-float.ll` defines `float fadd(float,float)`, `double dadd(double,double)`, `fmul`, `fdiv`, `fcmp`, and conversions; checks the libcall names, the stack/hidden-return shape, and the constant pool. `float.sh` runs `fadd(1.5,2.5)=4.0`, `fmul`, `fdiv`, `fcmp`, and conversions in MAME, linking `flib.lib`.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-float.ll`
Expected: float/double rejection or a missing libcall/constant pool.
- [ ] **Step 3: Implement the soft-float lowering**
Set the float/double operation actions to `LibCall` and the exact `FS$*`/`FD$*` names; lower float/double args/returns via the Task 1/A2 stack rules; add the constant pool for `f32`/`f64` literals (bit-exact `.long` pairs, 16-bit-aligned); implement the comparisons/conversions through the `flib` entries. Do not hardcode a library address or guess a symbol name.
- [ ] **Step 4: Run the float gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-float.ll
scripts/tests/m6/float.sh
scripts/tests/m6/spike.sh
```
Expected: PASS; the MAME float/double values are correct; the constant pool is bit-exact.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-float.ll
git -C build/llvm-clean commit -m "tms34010: float/double soft-float lowering"
git add scripts/tests/m6/float.sh
git commit -m "tests: M6 float/double gate"
```
### Task 4: General varargs (`va_list`, `va_start`, `va_arg`)
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010FrameLowering.cpp`
- Modify: `scripts/tests/m5/conformance/shim.c` (a real `va_list`-based `printf`/`sprintf` path)
- Test: `llvm/test/CodeGen/TMS34010/m6-varargs.ll`, `scripts/tests/m6/varargs.sh`
**Interfaces:**
- Consumes: the M5 contiguous `&last_fixed` pattern; the M4 `sprintf`/shim; the all-stack ABI.
- Produces: a `va_list` type and `va_start`/`va_arg` lowering for the TI stack layout; external variadic definitions/calls at `-O2`; the M4 contiguous pattern remains.
- [ ] **Step 1: Write the failing varargs test**
`m6-varargs.ll` defines an external variadic `printf`-shaped function and a `va_start`/`va_arg` walk over `int`, `long`, `char *`, `double`; C `varargs.sh` prints `%d %s %f` and compares the output. The first run must fail on the `va_start`/local variadic restriction.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-varargs.ll`
Expected: `Cannot select: va_start`/`vastart` or the M5 local-variadic rejection.
- [ ] **Step 3: Implement the varargs lowering**
Add the `va_list` representation, `va_start`/`va_arg`/`va_end`/`va_copy` lowering, and the external variadic call/definition ABI; keep the contiguous M4 pattern working. Let the static-variadic `-O2` path through once `va_start` keeps `...`; update the M5 diagnostic/tests accordingly. Extend the shim to use the real `va_list` where supported.
- [ ] **Step 4: Run the varargs gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-varargs.ll
scripts/tests/m6/varargs.sh
scripts/tests/m4/varargs.sh
```
Expected: the `%d %s %f` output is exact; the M4 contiguous pattern still passes.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-varargs.ll
git -C build/llvm-clean commit -m "tms34010: general varargs"
git add scripts/tests/m6/varargs.sh scripts/tests/m5/conformance/shim.c
git commit -m "tests: M6 varargs gate and shim"
```
### Task 5: Bitfields
**Files:**
- Modify: `build/llvm-clean/clang/lib/Basic/Targets/TMS34010.cpp/.h` (record/bitfield layout as needed)
- Modify: `TMS34010ISelLowering.cpp` (bitfield load/store masks) if the DAG needs target help
- Test: `llvm/test/CodeGen/TMS34010/m6-bitfield.ll`, `scripts/tests/m6/bitfield.sh`
**Interfaces:**
- Consumes: the Clang `PackStruct=1` target, the M4 packed-struct `_Static_assert` offsets, the TI C guide.
- Produces: TI-compatible packed bitfield offsets/signedness and correct masked loads/stores for `unsigned`/`signed` fields of 1..32 bits, including cross-byte/cross-word fields.
- [ ] **Step 1: Write the failing bitfield test**
`m6-bitfield.ll`/C defines packed structs with adjacent/signed/unsigned/cross-word bitfields and static asserts the TI offsets; `bitfield.sh` reads/writes every field and checks the observed bits in MAME against the TI layout. The first run must fail on a layout/shift/mask mismatch.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-bitfield.ll` / `scripts/tests/m6/bitfield.sh`
Expected: wrong offsets/masks or an unsupported bitfield shape.
- [ ] **Step 3: Implement the layout/adjustments**
Make the Clang record layout match the TI packed rules and the M4 offsets; adjust the target load/store lowering for the signed/unsigned field extraction and insertion if the generic DAG is wrong. Keep ordinary packed structs/arrays unchanged.
- [ ] **Step 4: Run the bitfield gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-bitfield.ll
scripts/tests/m6/bitfield.sh
scripts/tests/m4/layout.sh
```
Expected: the TI offsets and every MAME field value match; the M4 layout is unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add clang/lib/Basic/Targets/TMS34010.cpp clang/lib/Basic/Targets/TMS34010.h llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-bitfield.ll
git -C build/llvm-clean commit -m "tms34010: TI packed bitfields"
git add scripts/tests/m6/bitfield.sh
git commit -m "tests: M6 bitfield gate"
```
### Task 6: Aggregates by value, `sret`, and aggregate returns
**Files:**
- Modify: `TMS34010ISelLowering.cpp/.h`, `TMS34010CallingConv.td`, `TMS34010FrameLowering.cpp`
- Test: `llvm/test/CodeGen/TMS34010/m6-aggregate.ll`, `scripts/tests/m6/aggregate.sh`
- Reuse: the M5 `byval`/hidden-return/`memcpy` machinery.
**Interfaces:**
- Consumes: Task 1/2's hidden-return slot; the M5 `byval` 16-bit slots; the memcpy/`alloca`.
- Produces: structs/unions by value with 16-bit-rounded slots, `sret`/aggregate returns via the caller-allocated slot, and correct copies; `byval` remains supported.
- [ ] **Step 1: Write the failing aggregate test**
`m6-aggregate.ll`/C defines a 6-byte struct by value, a larger struct by value, a struct return, a union by value, and an `sret` call; static-asserts the offsets/sizes and checks the fields in MAME. The first run must fail on the current sret/aggregate rejection or a copy/size mismatch.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v .../m6-aggregate.ll` / `scripts/tests/m6/aggregate.sh`
Expected: `sret`/aggregate return rejection or a wrong slot/copy.
- [ ] **Step 3: Implement the aggregate lowering**
Extend `LowerCall`/`LowerFormalArguments`/`CanLowerReturn`/`LowerReturn` for `sret`, structs/unions by value, and aggregate returns using the 16-bit-rounded stack slots and the hidden return pointer; use `memcpy`/the exact object size. Keep the M5 `byval` and scalar ABI.
- [ ] **Step 4: Run the aggregate gate green**
```sh
build/llvm-clean-build/bin/llvm-lit -v .../m6-aggregate.ll
scripts/tests/m6/aggregate.sh
scripts/tests/m5/robust.sh
scripts/tests/m2/run.sh
```
Expected: the MAME fields/sizes match; the M5 byval/robust gate is unchanged.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m6-aggregate.ll
git -C build/llvm-clean commit -m "tms34010: aggregates by value and sret"
git add scripts/tests/m6/aggregate.sh
git commit -m "tests: M6 aggregate gate"
```
### Task 7: Runtime/libc breadth (`flib`/`rts`, `printf`/`sprintf`)
**Files:**
- Modify: `scripts/m6/link.cmd` / the M6 harness to link `flib.lib`/`rts.lib`; `scripts/tests/m5/conformance/shim.c`
- Test: `scripts/tests/m6/runtime.sh`, `llvm/test/CodeGen/TMS34010/m6-runtime.ll` if needed
**Interfaces:**
- Consumes: Tasks 3/4's float/varargs; the M5 sandbox.
- Produces: a linked runtime with `flib`/`rts` and a `printf`/`sprintf` that handles the M6 formats; the M6 conformance tests reuse it.
- [ ] **Step 1: Write the failing runtime test**
`runtime.sh` builds a C program using `printf("%d %s %f %lld")`, `sprintf`, `memcpy`/`memmove`, and the `flib` arithmetic; the first run must fail on the missing libcall/format.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/runtime.sh`
Expected: a missing `FS$`/`FD$` link or a format/output failure.
- [ ] **Step 3: Implement the runtime link/shim**
Wire `flib.lib`/`rts.lib` in the M6 link command; extend the shim/`printf` to the M6 formats (`%f`, `%lld`, `%llu`, width/precision) using the real `va_list`; keep the M5 `printf`/`sprintf` behavior. Do not bypass the `flib`/`rts` where the ABI requires it.
- [ ] **Step 4: Run the runtime gate green**
```sh
scripts/tests/m6/runtime.sh
scripts/tests/m5/robust.sh
scripts/tests/m5/native.sh
```
Expected: the output/values match; the M5 native path stays green.
- [ ] **Step 5: Commit**
```sh
git add scripts/m6/link.cmd scripts/tests/m6/runtime.sh scripts/tests/m5/conformance/shim.c
git commit -m "tests: M6 runtime and printf/sprintf"
```
### Task 8: Conformance expansion
**Files:**
- Modify: `scripts/tests/m5/conformance/classify.sh`, `skip.tsv`, `scripts/tests/m5/c-torture.list`, `c-testsuite.list`
- Create: `scripts/tests/m6/c-torture.sh`, `scripts/tests/m6/c-testsuite.sh` (the M6 wrappers over the M5 runner/expanded lists)
- Test: the expanded gates and reports
**Interfaces:**
- Consumes: Tasks 1–7; the pinned GCC 16.2/c-testsuite corpora.
- Produces: the M6 classifier/allowlists that no longer skip the supported float/i64/varargs/bitfield/aggregate tests; the full supported-suite report and the curated M6 gate; the `printf` output comparison.
- [ ] **Step 1: Write the failing conformance test**
Extend the c-torture/c-testsuite lists with the newly supported tests and remove the corresponding skip rows. The first run must fail because the classifier still skips them or the output/float libcall is missing.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m6/c-torture.sh` / `c-testsuite.sh` (or the expanded M5 scripts)
Expected: skips for now-supported features or a missing `flib` link.
- [ ] **Step 3: Expand the classifier/lists**
Remove the M6 feature skips; keep the genuinely unsupported (debug info, wider Xlib, etc.); add the `printf` output tests; record the full supported-suite counts and reasons. Keep the curated gate runtime bounded (target 40–60 per suite) and the full `--scan` as a report.
- [ ] **Step 4: Run the expanded gates green**
```sh
scripts/tests/m6/c-torture.sh
scripts/tests/m6/c-testsuite.sh
scripts/tests/m5/generic.sh
scripts/tests/m5/conformance/selftest.sh
```
Expected: the expanded lists pass; skipped tests have reasons; the Generic no-crash report still has no crashes.
- [ ] **Step 5: Commit**
```sh
git add scripts/tests/m5/conformance/classify.sh scripts/tests/m5/conformance/skip.tsv scripts/tests/m5/c-torture.list scripts/tests/m5/c-testsuite.list scripts/tests/m6/c-torture.sh scripts/tests/m6/c-testsuite.sh
git commit -m "tests: expand M6 conformance coverage"
```
### Task 9: Docs, full gates, and push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `symbols/README.md` (if runtime symbols are added)
- Test: the full M6/M5/M4/M3/M2 gate list
- [ ] **Step 1: Update the docs**
Document the M6 i64/float/double ABI, the `flib`/`rts` runtime, general varargs/`printf`, packed bitfields, aggregates/sret, the expanded conformance counts/pins, and the M6/M7 boundary (debug info, native linker, wider Xlib, real hardware). Correct the M5 stale notes.
- [ ] **Step 2: Run every gate**
```sh
ninja -C build/llvm-clean-build llc llvm-mc
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010 --filter='(m2|m3|m4|m5|m6)-'
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010
scripts/tests/m6/spike.sh
scripts/tests/m6/i64.sh
scripts/tests/m6/float.sh
scripts/tests/m6/varargs.sh
scripts/tests/m6/bitfield.sh
scripts/tests/m6/aggregate.sh
scripts/tests/m6/runtime.sh
scripts/tests/m6/c-torture.sh
scripts/tests/m6/c-testsuite.sh
scripts/tests/m5/object-smoke.sh
scripts/tests/m5/native-link.sh
scripts/tests/m5/native.sh
scripts/tests/m5/jr.sh
scripts/tests/m5/mmtm.sh
scripts/tests/m5/robust.sh
scripts/tests/m5/policy.sh
scripts/tests/m5/conformance/selftest.sh
scripts/tests/m5/generic.sh
scripts/tests/m4/run.sh
scripts/tests/m4/dis-roundtrip.sh
scripts/tests/m4/layout.sh
scripts/tests/m4/symbols.sh
scripts/tests/m4/termtris.sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
scripts/tests/m2/run.sh
tools/tms-bitaddr/tests/run.sh
```
All green; the conformance report has no unexpected crashes; skips have reasons.
- [ ] **Step 3: Commit and push**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010 llvm/test/MC/TMS34010 clang/lib/Basic/Targets/TMS34010.cpp clang/lib/Basic/Targets/TMS34010.h TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M6 floats, i64, varargs, bitfields and aggregates"
git -C build/llvm-clean push origin m6
git add README.md symbols scripts/m6 scripts/tests/m6 scripts/tests/m5 scripts/m3
git commit -m "tests/docs: M6 language/runtime coverage"
git push origin m6
```
Do not force-push, merge into `m0`–`m5`, or change the default. The controller updates the default to `m6` after the final review only if the user asks.
---
## Execution Handoff
M6 closes the TI language surface: float/double/i64 ABI, soft-float `flib`, general varargs, packed bitfields, aggregates/sret, and the expanded conformance tier. M7 owns debug info, the native linker, the wider Xlib surface, real-hardware validation, and the full external suites beyond the curated supported subset. The compiler repo is canonical for target code; this project repo holds the plan, harness, pins, and integration tests. The pinned GCC/c-testsuite trees are test-only (GPL) and are not part of the compiler or project distribution.
@@ -0,0 +1,103 @@
# TMS34010 M7.1 — Correctness and ABI Residuals Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Remove the remaining M6 correctness residuals: the `-O2` pointer over-scale, the sub-byte array/nested stride divergence, and the `.data` i64/aggregate/bitfield initializer gap, while keeping every M2–M6 gate green.
**Architecture:** The IR pipeline keeps the proven pre-opt bit scale, but replaces the scaled GEPs with opaque `@__tms_bitptr` calls so the optimizer cannot re-canonicalize them into already-bit GEPs. The post-opt pass scales only optimizer-created byte GEPs; a lowering pass then replaces the calls with `inttoptr(add(ptrtoint,...))` and a final instcombine restores the M0 folding. The sub-byte stride is diagnosed at compile time rather than silently byte-rounded. `.data` emission becomes recursive (i64, structs, unions, arrays, bitfields) in both raw and object modes.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `clang`, `tms-bitaddr`, `tms-clang`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §4.1–§4.2, §8 (M7.1), and the M6 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean`, branch `m7` (from m6 `bdc16ab8d4b6`); project work in `tms-c-compiler`, branch `m7` (from m6 `9dc8f28`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the native TI-COFF/GSPLNK path, the asm oracle, the `dwt` loader, and every M2–M6 gate green.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD for every task; commit per task; no push until the M7.1 final review is clean, then push `m7`.
- i64 `.data` words are little-endian (LSW first); the i64 argument/hidden-slot order stays MSW-first.
- Do not silently byte-round a sub-byte record stride: the diagnostic must be loud (default-on warning/error).
- Keep the narrow-load/store nonzero-offset guard from `bdc16ab8d4b6`.
## Review Focus
1. **The bitptr barrier.** Does the optimizer see opaque calls (no folding through them), does the post-opt pass scale only byte GEPs, does the lowering restore the M0 `int_diff = 8/32` shape, and is `p += n` correct at the default `-O2` with one scale?
2. **Sub-byte stride.** Does the diagnostic fire for the 1987 oracle `struct s arr[2]`/`struct nest`, not for byte-multiple records, and is the message actionable?
3. **`.data` exactness.** i64 word order, packed struct/bitfield bytes, unions/arrays, relocations, raw and object modes; no over-read/write; unsupported shapes stay loud.
4. **No M2–M6 regression** and the shim `memmove` workaround removed with the runtime gate proving the natural `d += n`.
---
### Task 1: The `-O2` bit-pointer semantic barrier
**Files:**
- Modify: `tools/tms-bitaddr/bitscale.cpp` (`--bitptr`, `--lower-bitptr`, tests)
- Modify: `tools/tms-bitaddr/tests/run.sh`, add `tests/bitptr.ll`
- Modify: `scripts/tms-clang` (pipeline)
- Modify: `scripts/tests/m5/conformance/shim.c` (remove the `memmove` workaround)
- Create: `scripts/tests/m7/pointer-o2.sh` (C gate)
- Test: `scripts/tests/m0/run.sh`, `scripts/tests/m6/runtime.sh`, the full M2–M6 gates
**Interfaces:**
- Consumes: the M6 pre-opt `--scale` + post-opt `--scale` pipeline and the known `p += n` over-scale.
- Produces: `@__tms_bitptr(i32 bitoff, ptr base)` (nounwind/readnone), `--bitptr`/`--lower-bitptr`, a pipeline that keeps opaque calls through `opt`, scales only post-opt byte GEPs, lowers the calls, and restores the M0 folding.
- [x] **Step 1: Write the failing tests.** Add `tests/bitptr.ll` to the `tms-bitaddr` suite: `--bitptr` turns `getelementptr i8, p, n` into a `@__tms_bitptr` call with the bit offset; `--lower-bitptr` turns it back into `inttoptr(add(ptrtoint p, n*8))`. Add `scripts/tests/m7/pointer-o2.sh`: a C driver with `char *p; p += n; *p = ...;` and the `memmove` overlap shape, compiled at `-O2`, linked with GSPA/GSPLNK, run in MAME, checking the correct bytes.
- [x] **Step 2: Run it red.** The current pipeline double-scales (`%bit.off = shl n,3` twice / `p + n*64` bits) and/or the shim workaround is required; the new gate fails.
- [x] **Step 3: Implement the barrier.** Add the `--bitptr`/`--lower-bitptr` modes; update `tms-clang` to clang → `--bitptr` → `opt` → `--scale` (post-opt byte GEPs) → `--lower-bitptr` → `opt -passes=instcombine` → output (at `-O0`: clang → `--bitptr` → `--lower-bitptr`); remove the shim `memmove` workaround (natural `d += n`).
- [x] **Step 4: Run green.** `scripts/tests/m7/pointer-o2.sh`, `scripts/tests/m0/run.sh` (`int_diff` 8/32, `late` 24), `scripts/tests/m6/runtime.sh` both levels, the full TMS34010 lit suite, and the M2–M6 gates.
- [x] **Step 5: Commit.** `tms-bitaddr` + `tms-clang` + shim + the gate.
### Task 2: Sub-byte array/nested stride diagnostic
**Files:**
- Modify: `clang/lib/Basic/Targets/TMS34010.cpp/.h` (target hook/flag if needed)
- Modify: `clang/lib/Sema/SemaType.cpp` / `SemaDecl.cpp` and `clang/include/clang/Basic/DiagnosticSemaKinds.td`
- Create: `clang/test/Sema/tms34010-subbyte-stride.c` (or the target test location)
- Create: `scripts/tests/m7/stride.sh`
- Test: the oracle `struct s { unsigned a:3; unsigned b:5; int c:4; unsigned d:20; unsigned e:4; }` and `struct nest { struct s a; int b; }`
**Interfaces:**
- Consumes: the M4/M6 packed record layout (36-bit content, 5-byte `sizeof`).
- Produces: a default-on diagnostic for arrays/nested members of records whose bit content is not a byte multiple, naming the byte-rounded and TI bit strides; no warning for byte-multiple records.
- [x] **Step 1: Write the failing test.** `stride.c` with `struct s arr[2];`, `struct nest n;`, and a byte-multiple control (e.g. `struct cross`); compile with `-Werror=tms34010-subbyte-stride`; the first run has no diagnostic (red).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Compute the record bit content (last field bit offset + width, recursively for nested fields) and diagnose an array element/nested field whose content is not a byte multiple. A warning is the acceptance; an implementation of the bit-content stride is optional only if sound.
- [x] **Step 4: Run green.** `stride.sh`; the Sema test; M4/M5/M6 layout/bitfield/aggregate gates.
- [x] **Step 5: Commit.**
### Task 3: `.data` i64/aggregate/bitfield initializers
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010AsmPrinter.cpp` (raw and object initializers)
- Create: `llvm/test/CodeGen/TMS34010/m7-data-initializers.ll`
- Create: `scripts/tests/m7/data.sh` (C + MAME, raw bytes)
- Test: the M5 object/native gates and the M6 runtime/conformance subset
**Interfaces:**
- Consumes: the M5 `.data` emitter (integers ≤32, f32/f64, pointers, byte arrays, zero).
- Produces: recursive struct/union/array/aggregate-zero emission and i64 two-word LSW-first emission in raw and object modes, with relocations; the existing unsupported-type diagnostics stay.
- [x] **Step 1: Write the failing test.** `m7-data-initializers.ll` and `data.sh` with `long long x = 0x1122334455667788;`, a packed struct, a bitfield struct, a union, an array of structs, and a pointer field; the current emitter rejects them (`M2 .data ...`).
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.** Extend `emitDataInitializer` and `emitDataInitializerObject` recursively; i64 LSW-first; exact packed sizes; relocations; keep vectors/i128/unsupported loud.
- [x] **Step 4: Run green.** `data.sh` (raw bytes/MAME), the object path, `m5/native.sh`, `m5/object-smoke.sh`, the M6 runtime/conformance gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.1
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M2–M7.1 gate list
- [x] **Step 1: Update the docs** for the bitptr barrier, the stride diagnostic, `.data` coverage and the new gate counts; keep the M7.2–M7.4 boundary.
- [x] **Step 2: Run every gate** (M2–M6 full list + `scripts/tests/m7/*`; lit; conformance; generic).
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.1 removes the default-`-O2` correctness risk and the M6 `.data`/stride gaps. M7.2 owns debug info and the native linker; M7.3 the wider Xlib/stderr/hardware; M7.4 the full external suites and performance. The compiler repo is canonical; the project holds the harness, plans and gates.
@@ -0,0 +1,119 @@
# TMS34010 M7.2 — Object/Debug (Native Linker and TI-COFF Debug Info) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close the M7.2 object/debug residuals: emit real debug information in the native TI-COFF object, and replace the GSPLNK dependency for the native path with `tools/tms-link`, including `.cinit` and public names longer than GSPA's 31-character limit, while keeping the GSPLNK output as the oracle.
**Architecture:** The MC object writer becomes a small TI-COFF **linker input** producer: optional `.cinit`, optional non-allocated `.debug_*` sections with long names, and the existing `.text`/`.data`/`.bss`. `llc` gains DWARF emission by setting `SupportsDebugInformation`; the asm path is unchanged because the compiler only emits debug for object output and existing IR has no `!dbg`. A new Python linker (`tools/tms-link`) reads those objects, lays out the four sections, resolves symbols and R-RELLONG fixups, and writes a position-dependent linked image the existing dwt loader accepts. Debug sections are stripped from the load image by default and kept with `--keep-debug` for `llvm-dwarfdump`.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), C++17, Ninja, `llc`, `llvm-dwarfdump`, TI COFF, GSPA/GSPLNK 2.00 under DOSBox, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.2), §4.1–§4.2 (ABI) and §7.8 (tooling); the M7.1 plan/README boundary.
## Global Constraints
- Compiler work in `build/llvm-clean` (branch `m7`, base the M7.1 push `065998da6f3c`); project work in `tms-c-compiler` (branch `m7`, base `e09d85c`). No force-push, no merge into `m0`–`m6`, no default change.
- Keep the TI all-stack ABI, the asm oracle (GSPA/GSPLNK), the dwt loader, and every M2–M7.1 gate green.
- The default native gate must keep linking the M5/M6 objects with GSPLNK until the `tms-link` oracle gate proves byte equality; then the gates may link with `tms-link` where they exercise it, while at least one gate keeps GSPLNK as the oracle each run.
- `.cinit` is the TI init-record table (`u16 word count`, `u32 destination`, data words), not a raw image. Do not invent a second format.
- Debug info is object-path only. `-filetype=asm` must not gain `.loc`/`.debug_*` output that GSPA cannot assemble.
- Public names are not truncated on the object path; GSPA's 31-character truncation stays an asm-path limitation.
- MAME + the loader are the acceptance environment; real hardware is M7.3 and deferred.
- Red/green TDD; commit per task; no push until the M7.2 final review is clean.
## Review Focus
1. **TI-COFF exactness.** Section order, bit sizes, long names (`/offset`), `.cinit` flags, `.debug_*` flags 0, relocations in debug sections, optional header fields. Existing three-section objects must be byte-identical when no `.cinit`/debug is present.
2. **Debug validity.** `llvm-dwarfdump` reads the kept `.debug_*` sections after linking; line tables name the source and lines; low-PC values equal the linked addresses; the default image is stripped.
3. **Linker correctness.** Relocation addends (same-section `0xFFFF`, section-symbol and undefined-external forms), alignment/placement, duplicate/undefined symbols, long names, `.cinit` placement, map, and loader acceptance.
4. **Oracle equality.** `tms-link` vs GSPLNK: allocated section bytes and symbol addresses identical for the M5/M6 objects; no gate silently drops one side.
5. **No M2–M7.1 regression** and no asm-output change.
---
### Task 1: TI-COFF writer: `.cinit`, debug sections, long names
**Files:**
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCObjectWriter.{h,cpp}`
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCAsmInfo.cpp` (`SupportsDebugInformation`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (explicit `.cinit` section lowering if needed)
- Create: `llvm/test/CodeGen/TMS34010/m7-cinit-section.ll`, `m7-debug-info.ll`
- Test: the full TMS34010 lit suite; the M5 object/native gates unchanged
**Interfaces:**
- Consumes: the M7.1 writer (three sections, `/`-less names, bit sizes, R-RELLONG).
- Produces: optional `.cinit` (data flags `0x40`, after `.data`, only when non-empty), optional `.debug_*` sections (flags `0`, long names via the COFF string table), long section names in headers, and DWARF emission from `llc -filetype=obj` when the module has `!dbg`.
- [x] **Step 1: Write failing tests.** `m7-cinit-section.ll`: a global in `section ".cinit"` plus a normal function; `llc -filetype=obj` must produce a fourth section named `.cinit` with the correct bytes/relocation. `m7-debug-info.ll`: a function with `!dbg` locations; `llc -filetype=obj` must produce `.debug_line`/`.debug_info` (long names). A small parser (the project `coff.py` or a new `tools/tms-link/tmscoff.py`) asserts the sections; the current writer fails (`.cinit` has no representation; debug unknown).
- [x] **Step 2: Run red.** Both objects fail as expected; the three-section objects stay unchanged.
- [x] **Step 3: Implement.**
- Make the section list dynamic: `.text`, `.data`, `.cinit` (if present), `.bss`; emit section symbols/aux for each used section; keep `.text` required only when the module has code.
- Section headers: names >8 bytes become `/` + decimal string-table offset; build the string table before writing headers (symbols already share it). The string table starts with its own 4-byte size.
- Debug: set `SupportsDebugInformation = true`; accept non-empty sections whose names start with `.debug_` (and `.debug_*` from the DwarfDebug path), flags 0, with R-RELLONG relocations; keep unknown non-debug sections loud. Omit empty debug sections so existing objects stay three sections.
- Keep `-filetype=asm` free of DWARF: the asm path has no `!dbg` in every existing gate; document that debug is object-only. If AsmPrinter emits `.loc` with debug IR in asm mode, gate it off (target AsmPrinter check) rather than weakening GSPA acceptance.
- `.cinit` explicit section: ensure `__attribute__((section(".cinit")))` and `section ".cinit"` IR lower to an MC section named `.cinit`.
- [x] **Step 4: Run green.** New lit tests; full lit (107 + new); `m5/object-smoke.sh`, `m5/native.sh`, `m5/native-link.sh`; `m7/data.sh` (byte-identical objects); the three-section assertion in `m5/native-link.sh` stays.
- [x] **Step 5: Commit** (compiler + any project test parser).
### Task 2: `tools/tms-link` native linker
**Files:**
- Create: `tools/tms-link/tms-link` (Python 3 CLI), `tools/tms-link/tmscoff.py` (reader/writer)
- Create: `tools/tms-link/tests/run.sh` (+ fixtures)
- Create: `scripts/tests/m7/link.sh` (linker unit/self-test gate)
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` opt-in path; default GSPLNK)
**Interfaces:**
- Consumes: one or more relocatable TI-COFF objects (Task 1), the entry object, and the M4/M5 defaults (`.text` `018A0000`, `.bss` `01A00000`, `prog`/`ram`).
- Produces: `tms-link -o OUT [--map MAP] [--entry SYM] [--text ADDR] [--data ADDR] [--cinit ADDR] [--bss ADDR] [--keep-debug|--strip-debug] OBJ...`; a linked position-dependent COFF (`nreloc=0`, optional header populated), a map (`%08x %s` lines + `ENTRY POINT SYMBOL: "..."`), symbol resolution for long public names, `.cinit` placement after `.data`, and loud duplicate/undefined/unsupported-relocation errors.
- [x] **Step 1: Write failing tests.** Feed it two tiny relocatable objects produced by `llc` (one defining a global/function, one referencing it) plus a `.cinit` object; assert the linked section addresses, resolved fields, map lines, and `nreloc=0`. Feed it a duplicate definition, an undefined external and an R-RELWORD and require loud failures.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Reader: mirror `vendor/vt1200/dwt/loader/coff.py` (header, sections, long names, symbols with aux, relocations).
- Layout: `.text` at the text origin; `.data` immediately after (`align 16` bits); `.cinit` after `.data`; `.bss` at the bss origin. Sections are word-aligned; sizes stay in bits; `.bss` is virtual.
- Symbols: section symbols get the output paddr; defined globals get paddr + section-relative value; undefined externals resolve to the unique definition; locals are resolved from their section. Public long names are preserved byte-for-byte.
- Relocations: for each R-RELLONG, read the 32-bit field (the bit addend), resolve `S` from the symbol index (`0xFFFF` = the section base), write `S + addend`. Leave no relocations in the output.
- Optional header: magic `0x0108`, vstamp `199`, text/data/bss sizes and starts, entry symbol; match GSPLNK's shape.
- Debug: strip `.debug_*` by default; `--keep-debug` copies them with their relocations resolved against the linked addresses. Refuse more than one debug-bearing object in M7.2 with a clear message.
- Map: section allocation and global symbol addresses in a stable,
greppable form. Source-line ranges are the kept `.debug_*` data (`.debug_line`)
validated with `llvm-dwarfdump` in Task 3; the linker does not parse DWARF
for the text map.
- [x] **Step 4: Run green.** `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`; link `scripts/m5/native-link.c` + the GSPA entry object and compare allocated bytes/symbol addresses with GSPLNK.
- [x] **Step 5: Commit** (project; plus the `M4_LINKER` hook).
### Task 3: End-to-end object tests and the GSPLNK oracle
**Files:**
- Create: `scripts/tests/m7/oracle.sh` (both linkers, byte/symbol comparison, MAME)
- Create: `scripts/tests/m7/cinit.sh`, `scripts/m7/cinit-entry.asm`, `scripts/m7/cinit.c`
- Create: `scripts/tests/m7/longname.sh`, `scripts/m7/longname-a.c`, `scripts/m7/longname-b.c`
- Create: `scripts/tests/m7/debug.sh`, `scripts/m7/debug.c`, `scripts/m7/elf-debug-wrap.py` (test-only ELF wrapper for `llvm-dwarfdump`)
- Modify: `scripts/tms-clang` (`-g` pass-through) if needed
**Interfaces:**
- Consumes: Task 1's debug objects, Task 2's linker and `M4_LINKER` hook.
- Produces: gates that prove (a) `tms-link` == GSPLNK on the allocated image, (b) `.cinit` records are placed/relocated and the entry copies them in MAME, (c) a 40-character public function links and runs across two TUs, (d) the kept debug image validates with `llvm-dwarfdump` and the default image is stripped.
- [x] **Step 1: Write the failing gates.** `oracle.sh` links the M5 native objects both ways and requires identical `.text`/`.data`/`.bss` bytes and symbol values, plus the existing MAME markers. `cinit.sh` builds a C `.cinit` table, links with `tms-link`, and requires the entry's copy loop to write the expected words in MAME. `longname.sh` defines/calls a >31-character public symbol across two TUs. `debug.sh` compiles with `-g`, links `--keep-debug`, wraps the `.debug_*` sections in a minimal ELF container, and runs `llvm-dwarfdump` for the filename/line/address; it also asserts the default link has no debug sections and the image runs.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement the gates and any missing plumbing** (`tms-clang -g`, `M4_LINKER`, the ELF wrapper, the entry/cinit fixture). Keep each gate runnable alone and serial with MAME.
- [x] **Step 4: Run green.** All four gates, the M5 object/native gates and the M7.1 gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.2
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.2 list
- [x] **Step 1: Update the docs** for the debug format and validation path, the native linker (CLI, layout, map, `.cinit`, long names, strip/keep debug), the oracle comparison, the single-debug-TU limit, and the new counts. Correct the M6/M7.1 `.cinit`/debug/native-linker limitation text.
- [x] **Step 2: Run every gate** (M0, M2–M7.2; lit CodeGen + MC + clang Sema/CodeGen; GSPLNK oracle). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.2 makes the native path self-contained: `llc` objects carry `.cinit` and debug data, `tms-link` replaces GSPLNK for linking, and the GSPLNK image is the permanent oracle. M7.3 owns the wider Xlib surface, stderr capture and hardware; M7.4 the full external suites, performance and the final boundary. The compiler repo is canonical; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,113 @@
# TMS34010 M7.3 — Runtime and Hardware (Wider Xlib, stderr, Hardware Harness) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Widen the validated VT1200 Xlib surface and exercise it in MAME, add real stderr capture to the conformance harness, and deliver the real-hardware marker harness with its MAME-equivalent acceptance while the unit is unavailable.
**Architecture:** The Xlib surface stays ROM-import based: each new entry is validated against the v2.2 image with `validate-syms.sh`, declared in `scripts/m4/x11m4.h`, and used by a new client (`xmore`) that MAME runs through the existing loader. The conformance shim gains a second sink and length cell for `stderr`, with the runner/check-lua comparing it exactly. The hardware harness is a thin wrapper around the already-proven `dwt/loader/hostload.py --marker` path: it links the marker client at the real-unit origins, validates the same marker cells in MAME, and invokes hostload only when `VT1200_HOST` is set.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, GSPA/GSPLNK 2.00 under DOSBox, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.3), §7.7 (Xlib/ROM imports), §7.9; the M7.2 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.2 push `3dccc4d`); compiler unchanged (`3c39d1d82190`) unless a real target bug appears.
- Keep every M2–M7.2 gate green, the TI all-stack ABI, the asm oracle, the native path, and the default `m6` branch.
- New Xlib addresses must pass `scripts/m4/validate-syms.sh` (ROM range, 16-bit aligned, real prologue) and come from the Ghidra/dis34 table; never guess.
- stderr is a second stream: stdout bytes/markers stay byte-identical for existing tests; an empty stderr is the default.
- The hardware run is **DEFERRED**: the gate must pass without a unit (MAME-equivalent acceptance) and must not mark the milestone blocked. `VT1200_HOST` enables the real run.
- MAME + the loader are the acceptance environment. Run MAME gates serially.
- Red/green TDD; commit per task; no push until the M7.3 final review is clean.
## Review Focus
1. **Xlib correctness:** each new symbol address is justified and validated; the client uses the correct X11R4 argument shapes; markers prove the calls actually ran (not just returned); no X errors; existing xshow/termtris unchanged.
2. **stderr exactness:** separate buffer/length/magic, no aliasing with stdout, truncation semantics, runner comparison (`--expect-stderr` and `;stderr=`), empty default, and the selftest red cases.
3. **Hardware harness honesty:** the COFF uses the proven hardware origins, the marker cells match `hostload.py`, the MAME check reads the same cells, and the deferred path is explicit and non-blocking.
4. **No M2–M7.2 regression** and no change to the default linker/ABI.
---
### Task 1: Wider Xlib surface
**Files:**
- Modify: `symbols/vt1200-v22.syms` (new validated entries)
- Modify: `scripts/m4/x11m4.h` (prototypes/structs)
- Create: `scripts/m7/xmore.c`, `scripts/m7/xmore-check.lua`
- Create: `scripts/tests/m7/xlib.sh`
- Test: `scripts/m4/validate-syms.sh`, the existing xshow/termtris gates
**Interfaces:**
- Consumes: the v2.2 ROM import table and the M4 Xlib ABI (`Display`, `XImage`, events).
- Produces: validated `XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`, `XInternAtom`, `XChangeProperty`, `XChangeGC` entries (addresses from `vendor/vt1200/dwt/notes/GUI_APPS.md`), prototypes, and an `xmore` client whose markers prove subwindow mapping, configure, atom/property changes, GC change, text (`XLoadFont`/`XDrawString`), drawing, and a heap `XCreateImage`/`XGetImage`/`XPutImage`/`XDestroyImage` round trip with no X errors.
- [x] **Step 1: Write the failing gate.** `xlib.sh` compiles `xmore.c` with `tms-clang`/`llc`, links via the M4 harness, loads it in MAME, and requires markers (window, child, GC, atom, property, configure, image, errors=0) plus a screenshot pixel check; `validate-syms.sh` currently rejects the new symbols.
- [x] **Step 2: Run red.** `validate-syms.sh` fails on the missing entries; `xmore` does not link.
- [x] **Step 3: Implement.**
- Add the six addresses with the GUI_APPS evidence; run `validate-syms.sh`.
- Declare the prototypes (`XWindowChanges`/`CW*` bits, `XInternAtom`, `XChangeProperty`, `XChangeGC` values) in `x11m4.h` without disturbing the existing ABI assertions.
- Write `xmore.c`: one parent + child, `XMapSubwindows`, `XConfigureWindow` (move/resize), `XInternAtom("WM_NAME")`, `XChangeProperty`, `XChangeWindowAttributes` (background), `XChangeGC` (foreground), `XLoadFont`/`XDrawString`, draw a rectangle/image, `XCreateImage` on the heap, `XGetImage` a small region, `XPutImage`, `XDestroyImage`, `XSync`; markers at `0x018A8000 + n*0x20`; error handler counts X errors.
- If a call is genuinely unusable (e.g. `XGetImage` blocks on the emulated server), keep it in the surface/test with a documented skip marker rather than silently dropping it.
- [x] **Step 4: Run green.** `xlib.sh`, `validate-syms.sh`, the M4 xshow/termtris/symbols gates, and the M7.2/M6/M5 gates touched by the harness.
- [x] **Step 5: Commit.**
### Task 2: stderr capture
**Files:**
- Modify: `scripts/tests/m5/conformance/shim.c` (stderr stream, fprintf/fputs/fputc/fwrite)
- Modify: `scripts/tests/m5/conformance/conformance-check.lua` (err_len/err buffer)
- Modify: `scripts/tests/m5/conformance/run.sh` (`--expect-stderr`, `;stderr=` parsing/comparison)
- Modify: `scripts/tests/m5/conformance/selftest.sh` (empty/formatted/truncated stderr cases)
- Test: the conformance selftest, c-testsuite/c-torture smoke, the M6 runtime gate
**Interfaces:**
- Consumes: the shim's `CONF_OUT`/`CONF_LEN`/`CONF_MAGIC` result block.
- Produces: `stderr` as a real `FILE *` target with `fprintf`/`vfprintf`/`fputs`/`fputc`/`fwrite`, a second buffer (`01B30000`, 16 KiB) and length (`01B00060`), runner expectation support, and selftests proving exact comparison and truncation rejection.
- [x] **Step 1: Write failing tests.** Add selftest sources that write `fprintf(stderr, ...)`; the runner rejects `--expect-stderr` (unknown option) and the shim has no stderr.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Represent `stdout`/`stderr` as distinct sink descriptors; `printf` continues the stdout stream; stderr has its own buffer/length and the same 16 KiB cap.
- Implement the write surface (return value = untruncated length, bytes capped) and `fprintf` via the existing formatter; declare `stderr` in the shim and any headers.
- Extend the check lua to read `ERRLEN`/`ERR` and write `errlen=`/`err=`; extend the runner's spec parser and comparison, preserving `stdout` defaults.
- Selftests: empty stderr passes; expected formatted stderr passes/fails correctly; `errlen >= CAP` is rejected as truncation.
- [x] **Step 4: Run green.** conformance selftest, the c-testsuite/c-torture gates (no changed stdout), the M6 runtime gate.
- [x] **Step 5: Commit.**
### Task 3: Real-hardware harness with MAME-equivalent acceptance
**Files:**
- Create: `scripts/m7/hwmark.c` (or `.s`), `scripts/m7/hw-entry.asm`
- Create: `scripts/tests/m7/hardware.sh`, `scripts/m7/hw-check.lua`
- Test: the M4/M5 loader path; `dwt/loader/hostload.py` dry contract; no real unit required
**Interfaces:**
- Consumes: the proven hardware origins (`.text 018C0000`, `.data 018D0000`, `.bss 018D8000`) and `hostload.py`'s `MARKER_CELLS` (`018E0000` start, `018E0020` data=0xDEADBEEF, `018E0040` data2=0x12345678, `018E0060` bss=0, `018E0080` live counter).
- Produces: a marker COFF (linked with `tms-link` or GSPLNK), a MAME run that checks the same cells through the loader, and a guarded real-hardware invocation: `VT1200_HOST=... scripts/tests/m7/hardware.sh` runs `hostload.py --marker --coff ...`; without it the gate prints `HARDWARE: DEFERRED` and passes on the MAME evidence.
- [x] **Step 1: Write the failing gate.** `hardware.sh` requires the marker cells in MAME and prints the deferred marker; no marker client exists yet.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Build the marker client at the hardware origins (entry sets STK/FP, calls `_main`, writes the sentinels and a live counter; `.data` holds the sentinels).
- MAME: link/load/run the same COFF (loader.lua + `hw-check.lua`), assert the five cells and loader status 0.
- Real path: invoke `dwt/loader/hostload.py` with `--coff`, `--marker`, `--host "$VT1200_HOST"`, and an evidence directory; propagate its failures. Do not fake a hardware pass; without the host, `HARDWARE: DEFERRED`.
- Document the unit's MAC/IP/host assumptions and the deferred status.
- [x] **Step 4: Run green.** `hardware.sh` (MAME + deferred), the M4/M5 native gates.
- [x] **Step 5: Commit.**
### Task 4: Docs, full gates, final review, push M7.3
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`
- Test: the full M0/M2–M7.3 list
- [x] **Step 1: Update the docs** for the wider Xlib table and client, the stderr protocol (`01B00060`/`01B30000`), the hardware harness/origins/deferred status, and the new gate counts.
- [x] **Step 2: Run every gate** (M0, M2–M7.3; lit; clang; conformance; generic; validate-syms; xshow/termtris). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.3 completes the runtime surface and makes the hardware campaign reproducible while the unit is away. M7.4 owns the full external suites, performance and the final M7 boundary. The compiler repo is canonical for target code; this project repo holds the Xlib table, harness, plans and gates.
@@ -0,0 +1,97 @@
# TMS34010 M7.4 — Conformance, Performance and the M7 Boundary Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax.
**Goal:** Close M7 with the full pinned external corpora, an i64 divide/remainder fast path with measured evidence, and the final M7 docs/counts/limitations/M8 boundary.
**Architecture:** A full-suite driver runs every file in the two pinned corpora through the existing conformance classifier and runner with the fast native loader settings, records per-test pass/skip/failure-category, and proves no unclassified crashes. The i64 division outliner gains a branch: when both operands' high words are zero it uses one 32-bit `DIVU`/`DIVS` (via i32 div/rem in IR) instead of the 64-step restoring loop; signed forms reuse the absolute-value normalization. A frame/cycle-based gate measures the small-divisor workload against the loop path.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m7`), `tms-clang`, `llc`, `tms-link`, TI COFF, the dwt loader, MAME, `dis34`, Python 3, `llvm-lit`/FileCheck, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M7.4), §7.9; the M7.3 plan/README boundary.
## Global Constraints
- Project work in `tms-c-compiler` (branch `m7`, base the M7.3 push `54608c0`); compiler work in `build/llvm-clean` (branch `m7`, `bbec928ba807`).
- Keep every M2–M7.3 gate green, the TI all-stack ABI, the native path, the asm oracle, and the default `m6` branch.
- Full-suite runs use the pinned corpora under `vendor/conformance` and the fast loader settings (`LOADER_AT=200`, `LOADER_END=1000`) in `native` mode; the default conformance gates keep their existing settings.
- A test that is classifier-supported but fails must get an honest per-test skip reason or a recorded failure category; never count a skip as a pass. No MAME/loader crash.
- The i64 fast path must preserve every M6 i64 semantic (signed truncation, remainder sign, divide-by-zero undefined) and the existing `m6-i64.ll` checks.
- No push until the M7.4 final review is clean; default stays `m6`.
## Review Focus
1. **Full-suite honesty:** all 1,692 + 220 files accounted for; classifier-supported pass/skip/failure categories exact; no crash counted as pass; the report/log retained.
2. **Fast path correctness:** the high-word check, zero divisor, signed normalization, 64-bit results, and the slow path unchanged; `m6-i64` and the runtime gate green.
3. **Measurement:** the perf gate compares the fast path against a genuine slow-path workload, not a compile-time constant fold; the metric is reproducible.
4. **No regression** and the final docs/boundary are accurate.
---
### Task 1: Full-suite harness and baseline run
**Files:**
- Create: `scripts/tests/m7/full-suite.sh` (driver + report)
- Create: `scripts/tests/m7/full-suite.skip` (generated/triaged skip reasons; Task 3 fills failures)
- Test: the existing conformance runner/classifier; c-testsuite/c-torture smoke
**Interfaces:**
- Consumes: `vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute/*.c` (1,692) and `vendor/conformance/c-testsuite/tests/single-exec/*.c` (220), `scripts/tests/m5/conformance/{run.sh,classify.sh}`.
- Produces: `full-suite.sh [--corpus c-torture|c-testsuite|all] [--jobs 1]` with `LOADER_AT=200 LOADER_END=1000`, `--mode native`, per-test `pass/skip/fail:<category>` rows, a summary (`total/pass/skip/fail/crash`), and a retained log/report; a nonzero exit only on a crash or an unclassified failure.
- [x] **Step 1: Write the failing driver.** It builds sorted full lists, runs the runner with `--classify --mode native --expect-status 0 --ignore-output` (c-torture) and the `.expected` comparison (c-testsuite), and prints a summary. The first run has no triage file and fails on the known failing tests.
- [x] **Step 2: Run a bounded sample red.** Pick 20 c-torture files and show pass/skip/fail; the failing ones are the red evidence.
- [x] **Step 3: Implement.** Run tests serially (MAME); classify skips; categorize failures (compile/diagnostic, loader status, mismatch, timeout) into a stable `fail:<category>` form; write `full-suite-results.tsv`, `full-suite-report.txt`, and the per-test logs under a work directory; never treat a skip as a pass. Keep the default conformance gates untouched.
- [x] **Step 4: Run the full c-testsuite (220) and start/complete the full c-torture (1,692).** Record exact counts; the run may take hours, so retain the log and resume from completed rows if interrupted (idempotent per id).
- [x] **Step 5: Commit** the driver (and the initial results summary).
### Task 2: i64 divide/remainder fast path
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`TMS34010LowerI64::lowerDivRem`)
- Modify: `llvm/test/CodeGen/TMS34010/m6-i64.ll` (fast-path checks) or create `m7-i64div-fast.ll`
- Create: `scripts/m7/i64div-perf.c`, `scripts/m7/i64div-perf-check.lua`, `scripts/tests/m7/i64div.sh`
- Test: `scripts/tests/m6/i64.sh`, the M6 runtime gate, `m6-i64.ll`
**Interfaces:**
- Consumes: the inline restoring-division outliner (`lowerDivRem`, 64 iterations) and the target `DIVU`/`DIVS`.
- Produces: a pre-check `(N >> 32) == 0 && (D >> 32) == 0`; on that path, `zext(udiv/urem (trunc N), (trunc D))` (32-bit `DIVU`) for unsigned, and for signed after the absolute-value normalization, with the same sign correction; the loop otherwise unchanged. A perf gate that measures a small-divisor workload (fast path) against a high-word-divisor workload (loop) using MAME frames/cycles or an equivalent instrumented counter.
- [x] **Step 1: Write failing tests.** `m7-i64div-fast.ll` requires the 32-bit `DIVU`/`DIVS` fast path (and the loop label still present); the perf gate requires the small-divisor workload to complete in materially fewer frames/iterations than the slow path. Current output has only the loop.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement** the fast path in `lowerDivRem`, keeping the zero-divisor undefined behavior, signed truncation and remainder sign; verify the IR/asm.
- [x] **Step 4: Run green.** The new lit test, the perf gate, `m6/i64.sh`, `m6/runtime.sh`, the M7.2/M7.3 gates.
- [x] **Step 5: Commit** (compiler + project).
### Task 3: Full-suite triage, skip curation and exact counts
**Files:**
- Modify: `scripts/tests/m7/full-suite.skip` (per-test honest reasons)
- Modify: `scripts/tests/m7/full-suite.sh` (summaries/categories)
- Create: `scripts/tests/m7/full-suite-report.txt` (retained)
- Test: the full-suite driver (idempotent resume), no crashes
**Interfaces:**
- Consumes: Task 1's per-test results.
- Produces: every failing test either fixed or skipped with a feature/curation reason; exact total/pass/skip/fail-category counts for both corpora; a retained report reproducible from the pins.
- [x] **Step 1: Triage** the failures by root cause; fix cheap target/driver issues; otherwise add a per-test `full-suite.skip` reason (one line each) and re-run only those.
- [x] **Step 2: Verify** the full results: no crash, no unclassified failure, every skip has a reason and is classifier-consistent.
- [x] **Step 3: Record the exact counts** and anomalies in the report.
- [x] **Step 4: Commit.**
### Task 4: Final M7 docs, full gates, final review, push M7.4/M7
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (M7 status)
- Test: the full M0/M2–M7.4 list
- [x] **Step 1: Update the docs** for the full-suite method/counts/skips, the i64 fast path and measurement, the complete M7 counts/limitations, and the M7/M8 boundary. Mark M7 complete (M8 owns multi-TU DWARF merging, `.lib` linking, hardware completion, remaining performance).
- [x] **Step 2: Run every gate** (M0, M2–M7.4; lit; clang; conformance; full suites; perf; generic). Record exact counts.
- [x] **Step 3: Commit, final whole-branch review, then push `m7`.** No default change.
---
## Execution Handoff
M7.4 closes the conformance and performance surface and freezes the M7 boundary. M8 owns the remaining object/debug depth (multi-TU DWARF), `.lib` linking, the hardware run once the unit returns, and any further performance work.
@@ -71,21 +71,28 @@ early GEP-scaling pass.
- Registers: A0–A12 general, A8 return value, A13 FP, A14 STK (program stack),
A15 system stack. B0–B14 are unused by TI's C compiler.
- Caller: if arguments are passed or a float/double is returned, push the old
STK on the system stack (`MOVE STK,-*SP`); push arguments on the program
stack in reverse order, widened to 32 bits; structs by value rounded to
16 bits; struct return address pushed on the program stack; call with
`CALLA` (direct) or `CALL Rs` (indirect).
- Caller: if arguments are passed or a float/double/`i64`/aggregate is
returned, push the old STK on the system stack (`MOVE STK,-*SP`); reserve
the hidden return slot (if any) at the top of the program stack **before**
saving STK; push arguments on the program stack in reverse order, widened
to 32 bits; structs by value rounded to 16 bits; call with `CALLA` (direct)
or `CALL Rs` (indirect). There is no `sret` pointer argument in the TI
ABI.
- Callee: save used A registers except A8 on the system stack (`MMTM SP,…`);
set `FP = STK`; `ADDI frame_size,STK`; locals at positive FP offsets, first
argument at `FP(-32)`; restore STK from `*SP(offset)`; `MMFM`; `RETS 2` if
arguments or stack return, `RETS 0` otherwise.
- `FS1` must be 32 inside C code and `FE0` must be 0; `FS0` may be changed
without restoring. Xlib clobbers the field-size state, so FS1 must be
re-established after every call.
- Struct return: caller allocates, pushes the address; callee copies. Float/
double return: caller allocates space on the program stack, callee copies.
(C guide §5.3.)
- `FS1` must be 32 inside C code and `FS0` must be 16 with its field-extension
bit set (`SETF 16,1,0`, sign-extending); both must be re-established after
every call because Xlib may change the field-size state.
- Hidden returns: the caller reserves `alignTo(size,2)` bytes at the top of
the program stack (before saving STK) for a struct/union, `float`/`double`
or `i64` result; the callee copies the object bytes to `saved_STK-size`
(the top of the slot) and ends `RETS 2`; the caller copies the bytes out
and releases the slot. The caller does not push a return address. Float/
double and `i64` use the same rule with a 4/8-byte object. (The 1987
`_mkbig`/`_callbig` oracle in the plan and `TMS34010.md` binds this form;
it supersedes the earlier sret wording in this document.)
- Symbols use a leading underscore (`_main`); sections are `.text`, `.data`,
`.bss`; code is position-dependent and linked at fixed bit addresses.
@@ -263,16 +270,22 @@ non-constant pointer expression by 8×.
- Custom calling convention `CC_TMS34010`.
- `LowerFormalArguments` / `LowerCall` / `LowerReturn` implement the caller and
callee rules in §4.2 exactly; `sret` and `byval` follow the TI layout.
callee rules in §4.2 exactly; `byval` follows the TI layout. An explicit
`sret` pointer is rejected: aggregate returns use the hidden slot above.
- **Explicit arguments**: pushed on the program stack (A14) in reverse order,
each widened to 32 bits. The first explicit argument is at `FP(-32)`, the
second at `FP(-64)`, etc.
- **Struct return**: the caller pushes the return-space address **after** the
explicit arguments, so it is the top program-stack slot: the callee reads it
at `FP(-32)` and the first explicit argument is at `FP(-64)`.
- **Hidden return slot**: for a struct/union, `float`/`double` or `i64`
result, the caller reserves `alignTo(size,2)` bytes at the top of its own
frame **before** saving STK and passes no return pointer. The callee
writes the object at `saved_STK-size` (= `FP-(argbytes+size)`) and ends
`RETS 2`; the caller copies the bytes out and releases the slot with
`ADDI -size,STK`. This is the 1987 `_mkbig`/`_callbig` form and supersedes
the earlier sret wording; an explicit `sret` argument is rejected.
- **Old STK**: the caller saves A14 on the system stack only when it passes
arguments or the callee returns a float/double. A no-argument function with
locals has no saved old STK; the callee restores STK from FP before `RETS 0`.
arguments or the callee returns a `float`/`double`/`i64`/aggregate through
the hidden slot. A no-argument function with locals has no saved old STK;
the callee restores STK from FP before `RETS 0`.
- **System stack layout** (grows down), after the callee's `MMTM` of `n`
registers:
@@ -324,7 +337,7 @@ non-constant pointer expression by 8×.
MAME, and the byte-exact ROM round-trip.
- Loads/stores: misaligned accesses allowed; `MOVB` for i8, `MOVE` with FS0 for
i16, `MOVE` with FS1 for i32/pointers; i64 as two 32-bit accesses. Ensure
FS1 is 32; use FS0 for 16-bit.
FS1 is 32 and FS0 is 16 sign-extending; use FS0 for 16-bit.
- `memcpy`/`memmove`/`memset`: lower to byte/word loops; lengths are bytes,
addresses bits; overlap semantics for `memmove`.
- `alloca`/VLA: size ×8; 16-bit alignment for standalone objects.
@@ -434,7 +447,132 @@ appears in MAME (real unit when available).
no X errors.
**M5 — robustness and native path.** `memcpy`, `alloca`, `byval`, varargs
(`sprintf`), floats, bitfields, `long long`; native COFF and debug info.
(`sprintf`), floats, bitfields, `long long`; native COFF and debug info
(debug info was re-scoped to M6 below, then moved to **M7** by the M6
plan/ledger ruling).
> **M5 re-scoped (2026-11-13):** floats/double, bitfields, `long long`/i64 and
> general varargs (`va_list`/`va_start`/`va_arg` beyond the contiguous
> `sprintf` form) are **M6**. M5 delivers the integer/pointer native object
> path, `alloca`/`byval`/narrow returns, `memcpy`/`memset`/`memmove`,
> `JR`/`MMTM`, and the curated conformance tier. **Debug info is M7** per
> the M6 plan and ledger ruling (`progress.md`), not M6.
### M7 — correctness residuals, object/debug, hardware, conformance
M7 closes the M6 boundary in four sequential sub-milestones. Each has its own
design/plan, subagent-driven execution, task reviews, final whole-branch
review, and a push of the `m7` branch (default unchanged unless the user
asks). M2–M6 remain binding.
- **M7.1 — correctness and ABI residuals.** (a) The `-O2` bit-pointer
semantic barrier: `tms-clang` scales GEPs to calls to an opaque
`@__tms_bitptr(i32 bitoff, ptr base)` before the optimizer, scales only the
optimizer-created byte GEPs afterwards, then lowers the bitptr calls to
`inttoptr(add(ptrtoint,...))` and runs a final instcombine. This removes the
`p += n` over-scale while preserving the M0 `int_diff = 8/32` contract; the
shim `memmove` workaround is removed. (b) The sub-byte array/nested-record
stride: emit a loud, default-on diagnostic for arrays and nested members of
records whose bit content is not a byte multiple (TI advances by the bit
content; Clang's byte-rounded `sizeof` would silently diverge), or implement
the bit-content stride if a sound lowering is found. (c) `.data`
initializers for i64, aggregates/unions and bitfield globals, including the
object path and relocations; i64 words are little-endian/least-significant
first. (d) Keep the nonzero byte-offset narrow-load/store guard.
- **M7.2 — object/debug.** (a) Debug info in the native TI-COFF object:
`llc -march=tms34010 -filetype=obj` on a module with `!dbg` metadata emits
DWARF line/source sections (`.debug_info`, `.debug_abbrev`, `.debug_line`,
`.debug_str`, and the auxiliary sections LLVM produces) as non-allocated
COFF sections; long section names use the COFF `/offset` string-table form.
The native linker resolves their relocations and, by default, strips them
from the load image; `--keep-debug` retains them for tools. M7.2 supports one
debug-bearing object per link (multi-TU DWARF merging is loud, M8); the
`tms-link --map` output includes the section allocation and global symbol
map; source-line information lives in the kept `.debug_line` sections and is
dumped/validated with `llvm-dwarfdump` (Task 3), not parsed by the linker. (b) `tools/tms-link`
is a native TI-COFF linker: it reads relocatable objects, resolves public
symbols including names longer than GSPA's 31-character limit, lays out
`.text`/`.data`/`.cinit` in the `prog` region and `.bss` in `ram`, applies
the R-RELLONG fixups, and emits a position-dependent linked COFF with
`nreloc = 0`, an optional header (entry, text/data/bss start and size) and a
map. `.cinit` is a first-class section (TI init-record table: u16 word count,
u32 destination, data words), placed after `.data`; the linker defines the
public `cinit` symbol. (c) Object-path gates compare `tms-link` output with
GSPLNK for the same objects (byte-identical allocated sections, identical
symbol addresses, same MAME markers) and cover `.cinit`, >31-character
public names, and a `llvm-dwarfdump`-validated debug image.
M7.2 acceptance: `llc -filetype=obj` emits a debug-bearing TI-COFF whose
`.debug_*` sections validate with `llvm-dwarfdump` after the linker keeps them;
the default linked image is debug-stripped and the loader/MAME acceptance is
unchanged; `tms-link` links the M5 native objects with allocated-section
bytes and symbol addresses equal to GSPLNK (the M6 gates continue to link
with GSPLNK; both use the same object writer); a C `.cinit` table is placed,
relocated and processed by an entry in MAME; two TUs with a 40-character public
function link and run; every M2–M7.1 gate stays green.
- **M7.3 — runtime and hardware.** (a) The wider Xlib surface: add the
remaining ROM-validated entries from the Ghidra/dis34 table
(`XMapSubwindows`, `XChangeWindowAttributes`, `XConfigureWindow`,
`XInternAtom`, `XChangeProperty`, `XChangeGC`), extend `x11m4.h`, and add a
client (`xmore`) that exercises them together with text (`XLoadFont`,
`XDrawString`), drawing, and a heap image (`XCreateImage`/`XGetImage`/
`XPutImage`/`XDestroyImage`), with MAME markers and no X errors;
`scripts/m4/validate-syms.sh` validates every added address. (b) stderr
capture: the conformance shim exposes a distinct `stderr` stream
(`fprintf`/`fputs`/`fputc`/`fwrite`) into a second buffer/length cell, the
runner and MAME check compare it (`--expect-stderr`/`;stderr=`), and
selftests cover empty, non-empty and truncated stderr. (c) Real-hardware
validation for the VT1200: a harness builds the marker client at the proven
hardware origins (`018C0000`/`018D0000`/`018D8000`), runs the same COFF in
MAME (the permanent acceptance), and, with `VT1200_HOST` set, drives
`dwt/loader/hostload.py --marker` over rdebug against the real unit. The
unit is unavailable for the first two weeks, so the hardware run is
**DEFERRED** and does not block M7; the harness and its MAME-equivalent
acceptance are delivered now.
M7.3 acceptance: `xmore` runs in MAME with the expected markers and no X
errors, and every added Xlib address passes `validate-syms`; the stderr
selftests prove empty, formatted and truncated stderr; the hardware gate
passes its MAME marker check and reports `HARDWARE: DEFERRED` without a unit
(the same command runs `hostload.py --marker` when `VT1200_HOST` is set); every
M2–M7.2 gate stays green.
- **M7.4 — conformance and performance.** (a) Full external suites: run the
pinned GCC 16.2.0 `gcc.c-torture/execute` corpus (1,692 files) and the
c-testsuite `single-exec` corpus (220) beyond the curated lists, at `-O0`
with the conformance classifier; every test is pass, an honest
feature/curation skip with a reason, or a recorded failure category — never
an unclassified crash. The bounded `-O2` subsets stay as the optimization
smoke tier. (b) Performance: an i64 divide/remainder fast path that, after
the signed absolute-value normalization, uses one 32-bit `DIVU` when both
normalized high words are zero instead of the 64-step restoring loop (the
signed forms divide magnitudes, so they also select `DIVU`), with the same
quotient/remainder sign fixup, unit/asm coverage, the M6 i64 gate, and a
cycle/frame-based measurement gate. (c) Final M7
docs, exact counts, known limitations, and the M7/M8 boundary (M8 owns
multi-TU DWARF merging, `.lib` linking, the real VT1200 run if still
deferred, and any remaining performance work).
M7.4 acceptance (met, M7 complete): the full pinned corpora account for
**1,912** files — c-torture **1,692 = 1,366 pass / 326 skip / 0 fail / 0
crash** and c-testsuite **220 = 210 pass / 10 skip / 0 fail / 0 crash** —
with every skip carrying a classifier or curation reason and the 272 curated
rows re-run without skips (272/272 still failed). The i64 fast path uses one
32-bit `DIVU` when both normalized operands' high words are zero; the
implementation divides magnitudes for the signed forms as well, so `DIVU` is
emitted and `DIVS` is not (this matches the M6 loop's unsigned
compare/subtract). The MAME measurement is `fast_frames=90 slow_frames=2424
ratio=26.9` for the same 16,384 iterations, status `600D600D`, checksums
`000000011E6F9AB4`/`00000000007512AE`. Every M2–M7.3 gate stays green; lit is
**118/118** (114 CodeGen + 4 MC) and the shipped c-testsuite tier remains the
curated 48 pass / 172 skip. The real VT1200 run is still **DEFERRED**; M8
owns multi-TU DWARF merging, `.lib` linking under `tms-link`, the hardware
run, the remaining conformance classes and further performance work.
M7.1 acceptance: the `p += n` shape is correct at the default `-O2` with one
scale; M0 `int_diff` 8/32; the stride diagnostic fires for the oracle shapes
and not for byte-multiple records; `.data` i64/aggregate/bitfield globals
assemble/link/load with exact bytes; every M2–M6 gate stays green; MAME and
the dwt loader are the acceptance environment.
## 9. Risks and mitigations
+134
View File
@@ -0,0 +1,134 @@
#!/bin/sh
# Fetch the pinned external conformance corpora into vendor/conformance.
#
# scripts/fetch-conformance.sh [DEST]
# scripts/fetch-conformance.sh --gcc-only [DEST]
# scripts/fetch-conformance.sh --c-testsuite-only [DEST]
#
# DEST defaults to vendor/conformance (ignored by git). Nothing in the
# tracked tree is written.
#
# Pins:
# GCC 16.2.0 https://ftp.gnu.org/gnu/gcc/gcc-16.2.0/gcc-16.2.0.tar.xz
# SHA-256 e6738e29597f733270731aa90600f37ffdc045079dfc27ec7e8192cc81085c3e
# (only gcc/testsuite/gcc.c-torture and COPYING* are extracted)
# c-testsuite 5c7275656d751de0e68b2d340a95b5681858ed07
# https://github.com/c-testsuite/c-testsuite
#
# The corpus licences are preserved in each extracted tree (COPYING*). The
# tests are test-only and are not part of the compiler or project
# distribution.
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
GCC_VERSION=16.2.0
GCC_TOP=gcc-$GCC_VERSION
GCC_URL=https://ftp.gnu.org/gnu/gcc/$GCC_TOP/$GCC_TOP.tar.xz
GCC_SHA256=e6738e29597f733270731aa90600f37ffdc045079dfc27ec7e8192cc81085c3e
CTEST_REPO=https://github.com/c-testsuite/c-testsuite
CTEST_COMMIT=5c7275656d751de0e68b2d340a95b5681858ed07
DO_GCC=1
DO_CTEST=1
DEST=
while [ $# -gt 0 ]; do
case $1 in
--gcc-only) DO_CTEST=0; shift ;;
--c-testsuite-only) DO_GCC=0; shift ;;
-h|--help)
sed -n '2,/^set -eu/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'
exit 0
;;
-*) echo "fetch-conformance: unknown option: $1" >&2; exit 2 ;;
*)
[ -z "$DEST" ] || { echo "fetch-conformance: more than one DEST" >&2; exit 2; }
DEST=$1
shift
;;
esac
done
DEST=${DEST:-$ROOT/vendor/conformance}
mkdir -p "$DEST"
DEST=$(cd "$DEST" && pwd)
fail() {
echo "fetch-conformance: FAIL: $*" >&2
exit 1
}
download() {
url=$1
out=$2
if command -v curl >/dev/null 2>&1; then
curl -fL --retry 3 --connect-timeout 30 -o "$out.part" "$url"
elif command -v wget >/dev/null 2>&1; then
wget -O "$out.part" "$url"
else
fail "need curl or wget to download $url"
fi
mv "$out.part" "$out"
}
if [ "$DO_GCC" -eq 1 ]; then
TAR=$DEST/downloads/$GCC_TOP.tar.xz
mkdir -p "$DEST/downloads"
if [ ! -f "$TAR" ]; then
echo "== download $GCC_URL"
download "$GCC_URL" "$TAR"
fi
echo "== verify $GCC_TOP.tar.xz"
printf '%s %s\n' "$GCC_SHA256" "$TAR" | sha256sum -c - \
|| fail "SHA-256 mismatch for $TAR"
if [ ! -d "$DEST/$GCC_TOP/gcc/testsuite/gcc.c-torture/execute" ]; then
echo "== extract gcc.c-torture and COPYING*"
tar -xJf "$TAR" -C "$DEST" --wildcards \
"$GCC_TOP/gcc/testsuite/gcc.c-torture/*" \
"$GCC_TOP/COPYING*"
else
echo "== gcc.c-torture already extracted"
fi
[ -d "$DEST/$GCC_TOP/gcc/testsuite/gcc.c-torture/execute" ] \
|| fail "extraction produced no gcc.c-torture/execute"
ls "$DEST/$GCC_TOP"/COPYING* >/dev/null 2>&1 \
|| fail "extraction preserved no COPYING file"
fi
if [ "$DO_CTEST" -eq 1 ]; then
CTEST=$DEST/c-testsuite
if [ ! -d "$CTEST/.git" ]; then
echo "== clone $CTEST_REPO"
mkdir -p "$(dirname "$CTEST")"
git clone --filter=blob:none --no-checkout "$CTEST_REPO" "$CTEST"
fi
echo "== checkout c-testsuite $CTEST_COMMIT"
git -C "$CTEST" fetch --depth 1 origin "$CTEST_COMMIT" 2>/dev/null || true
git -C "$CTEST" checkout --detach "$CTEST_COMMIT"
REV=$(git -C "$CTEST" rev-parse HEAD)
[ "$REV" = "$CTEST_COMMIT" ] \
|| fail "c-testsuite is at $REV, want $CTEST_COMMIT"
[ -d "$CTEST/tests/single-exec" ] \
|| fail "c-testsuite checkout has no tests/single-exec"
if [ -f "$CTEST/COPYING" ]; then
:
elif [ -f "$CTEST/LICENSE" ]; then
:
else
fail "c-testsuite checkout preserved no COPYING/LICENSE"
fi
fi
{
printf 'gcc_version\t%s\n' "$GCC_VERSION"
printf 'gcc_url\t%s\n' "$GCC_URL"
printf 'gcc_sha256\t%s\n' "$GCC_SHA256"
printf 'c_testsuite_repo\t%s\n' "$CTEST_REPO"
printf 'c_testsuite_commit\t%s\n' "$CTEST_COMMIT"
} > "$DEST/PINS"
echo "== pinned conformance corpora at $DEST"
du -sh "$DEST" 2>/dev/null || true
+1 -1
View File
@@ -21,7 +21,7 @@
.globl _start
_start:
setf 32, 0, 1 ; FS1 = 32 for 32-bit MOVE
setf 16, 0, 0 ; FS0 = 16, for any i16 code
setf 16, 1, 0 ; FS0 = 16, for any i16 code
movi 20, a0
movi 22, a1
calla _add
+12 -5
View File
@@ -268,7 +268,7 @@ expect_seq "$TMP/keep.txt" \
'move[[:space:]]+a14,[[:space:]]*-\*sp,[[:space:]]*1' \
'move[[:space:]]+[^,]+,[[:space:]]*\*a14\+,[[:space:]]*1' \
'calla' \
'setf[[:space:]]+16,[[:space:]]*0,[[:space:]]*0' \
'setf[[:space:]]+16,[[:space:]]*1,[[:space:]]*0' \
'setf[[:space:]]+32,[[:space:]]*0,[[:space:]]*1' \
'move[[:space:]]+\*sp\(0x[0-9a-f]+\),[[:space:]]*a14,[[:space:]]*1' \
'rets[[:space:]]+2([[:space:]]*(;|$))'
@@ -291,8 +291,15 @@ check_stk() {
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
tolower($0) ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
{ low = tolower($0) }
low ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
low ~ /mmtm[[:space:]]+sp,/ {
line = low
sub(/^.*mmtm[[:space:]]+sp,[[:space:]]*/, "", line)
sub(/[[:space:]]*;.*$/, "", line)
n += split(line, regs, ",")
}
low ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
' "$TMP/func.txt")
[ -n "$_pushes" ] || fail "$_label has no SETFP (MOVE A14,A13)"
_operand=$(grep -Eio '\*sp\(0x[0-9a-f]+\)' "$TMP/func.txt" | head -1 \
@@ -301,8 +308,8 @@ check_stk() {
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes pushes need $_want bits"
echo " ok $_label: $_pushes pushes -> *SP($(printf '0x%x' "$_want")), A14, 1"
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes saved slots need $_want bits"
echo " ok $_label: $_pushes saved slots -> *SP($(printf '0x%x' "$_want")), A14, 1"
}
check_stk "_add2" "$ADD2"
check_stk "_first" "$FIRST"
+1 -1
View File
@@ -11,7 +11,7 @@
.globl _start
_start:
setf 32, 0, 1
setf 16, 0, 0
setf 16, 1, 0
movi _cstack, a14
move a14, a13
+70 -56
View File
@@ -12,7 +12,8 @@
# _XCreateSimpleWindow (arguments 1,0,2,200,400,100,100,root,
# display in that order, display pushed last), 2 -> _XMapWindow,
# 2 -> _XSync, each followed by the ABI's SETF 16/32 pair
# branch code: CMP, JALT, JAGT, JAEQ, JAUC and LBB… labels (never .LBB)
# branch code: CMP plus relative JR/JR<cc> branches (absolute JA* only for a
# zero-displacement or out-of-range target) and LBB… labels (never .LBB)
# .data: 30 3A 3A 30 00 ("0::0")
# old-STK restore offsets: *SP((pushes+1)*32),A14
#
@@ -290,59 +291,44 @@ P4=$(count_between "$TMP/xhello.txt" "calla[[:space:]]+l${XMAP_L}" \
echo " ok argument pushes: XOpenDisplay=1 XCreateSimpleWindow=9 XMapWindow=2 XSync=2"
# Counting pushes is not enough: the nine words must reach the callee in the
# ABI order. build/m3/m3.lst records background 1, border 0, border width 2,
# height 200, width 400, y 100, then x 100 (x reuses y's register, so there are
# six MOVIs for the seven constants), followed by the root (A2) and display
# (A0) pushes. Assert the immediates and push registers as one sequence, so a
# swapped pair fails even though the count stays nine, and require the final
# push before CALLA to be the display register.
# ABI order. Parse the linked assembly the way the M4 dis34 gate does: record
# each MOVI's register/value pair, then map every push register to the last
# value loaded into it. The root (A2) and display (A0) are named explicitly.
# x reuses y's register, so there are six MOVIs for the seven constants. This
# fails a swapped immediate or register while keeping the exact nine-argument
# order 1,0,2,200,400,100,100,root,display and the display pushed last.
awk '
tolower($0) ~ /calla[[:space:]]+l'"$XOPEN_L"'/ { on = 1; next }
tolower($0) ~ /calla[[:space:]]+l'"$XCREATE_L"'/ { exit }
/^[[:space:]]*CALLA[[:space:]]+_XOpenDisplay/ { on = 1; next }
/^[[:space:]]*CALLA[[:space:]]+_XCreateSimpleWindow/ { exit }
!on { next }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*-\*sp,[[:space:]]*1/ { started = 1; next }
!started { next }
tolower($0) ~ /movi[[:space:]]+/ {
/^[[:space:]]*MOVI[[:space:]]/ {
line = $0
sub(/^[^:]*:[[:space:]]+movi[[:space:]]+/, "", line)
sub(/.*MOVI[[:space:]]+/, "", line)
sub(/[[:space:]]*;.*/, "", line)
sub(/[[:space:]]+/, " ", line)
split(line, p, /,[[:space:]]*/)
printf "IMM %s %s\n", tolower(p[1]), tolower(p[2])
gsub(/[[:space:]]/, "", p[1])
gsub(/[[:space:]]/, "", p[2])
val[p[2]] = p[1]
next
}
tolower($0) ~ /move[[:space:]]+a[0-9]+,[[:space:]]*\*a14\+,[[:space:]]*1/ {
/^[[:space:]]*MOVE[[:space:]]+A[0-9]+,[[:space:]]*\*A14\+,/ {
line = $0
sub(/^[^:]*:[[:space:]]+move[[:space:]]+/, "", line)
sub(/.*MOVE[[:space:]]+/, "", line)
sub(/,.*/, "", line)
printf "PUSH %s\n", tolower(line)
next
v = val[line]
if (line == "A2") v = "root"
if (line == "A0") v = "display"
print v
}
' "$TMP/xhello.txt" > "$TMP/xcreate.seq"
cat > "$TMP/xcreate.want" <<'EOF'
IMM 0x1 a1
PUSH a1
IMM 0x0 a1
PUSH a1
IMM 0x2 a3
PUSH a3
IMM 0xc8 a3
PUSH a3
IMM 0x190 a3
PUSH a3
IMM 0x64 a3
PUSH a3
PUSH a3
PUSH a2
PUSH a0
EOF
if ! cmp -s "$TMP/xcreate.want" "$TMP/xcreate.seq"; then
' "$ASM" > "$TMP/xcreate.vals"
printf '%s\n' 1 0 2 200 400 100 100 root display > "$TMP/xcreate.want"
if ! cmp -s "$TMP/xcreate.want" "$TMP/xcreate.vals"; then
{
echo "M3 dis34 round-trip: FAIL: XCreateSimpleWindow argument order"
echo " expected (background,border,border_width,height,width,y,x,root,display):"
sed 's/^/ /' "$TMP/xcreate.want"
echo " got:"
sed 's/^/ /' "$TMP/xcreate.seq"
sed 's/^/ /' "$TMP/xcreate.vals"
} >&2
exit 1
fi
@@ -354,7 +340,7 @@ awk '
/^_xhello:/ { on = 1; next }
on && /-- End function/ { exit }
on && /^[[:space:]]*CALLA/ { pending = 1; next }
on && pending && /SETF[[:space:]]+16,[[:space:]]*0,[[:space:]]*0/ { saw16 = 1; next }
on && pending && /SETF[[:space:]]+16,[[:space:]]*1,[[:space:]]*0/ { saw16 = 1; next }
on && pending && saw16 && /SETF[[:space:]]+32,[[:space:]]*0,[[:space:]]*1/ {
n++; pending = 0; saw16 = 0; next
}
@@ -363,7 +349,7 @@ awk '
SETF_COUNT=$(cat "$TMP/setf_count")
[ "$SETF_COUNT" -eq 4 ] \
|| fail "found $SETF_COUNT post-call SETF 16/32 pairs in _xhello, want 4"
echo " ok four post-call SETF 16,0,0 + SETF 32,0,1 pairs"
echo " ok four post-call SETF 16,1,0 + SETF 32,0,1 pairs"
# _xhello takes no arguments of its own (the nine-argument call is inside it),
# so it returns with RETS 0; the argument-taking branch functions use RETS 2.
@@ -377,6 +363,9 @@ for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
done
echo "== check the branch code"
# A compiled local branch uses the one-word relative JR/JR<cc> form when the
# displacement fits; far or zero-displacement branches keep JAUC/JA<cc>. The
# condition code must survive either encoding.
for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
addr=${pair%%:*}
label=${pair##*:}
@@ -385,11 +374,11 @@ for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no CMP"
fi
if ! grep -Eiq '\bjauc\b' "$TMP/fn.txt"; then
if ! grep -Eiq '\bj[ra](uc|eq|ne|lt|le|gt|ge|lo|ls|hi|hs|p|n|v|nv|nn)\b' "$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no JAUC"
fail "$label has no branch"
fi
echo " ok $label: CMP + JAUC"
echo " ok $label: CMP + branch"
done
for pair in "$XHELLO:_xhello"; do
addr=${pair%%:*}
@@ -407,14 +396,32 @@ for callee in _sumto _max2 _lt _layout_screens _layout_root; do
|| fail "_branch_test does not call $callee"
done
echo " ok _branch_test calls sumto, max2, lt, layout_screens, layout_root"
# Conditional branch opcodes emitted by this compiled image. JALE/JALO/JAHI
# coverage lives in the m3-loop/m3-unsigned/m3-cmpi lit tests; this image has
# the signed compare, loop-exit and smax branches.
for op in jalt jagt jaeq; do
grep -Eiq "^[0-9a-f]+:[[:space:]]+$op([[:space:]]|;|$)" "$TMP/dis34.txt" \
|| fail "no $op instruction in the linked .text"
echo " ok $op present"
done
# Conditional branch conditions, pinned per function: _sumto has the loop exit
# (signed LT) and the result check (EQ), _max2 is smax (GT) and _lt is signed
# LT. JALE/JALO/JAHI coverage lives in the m3-loop/m3-unsigned/m3-cmpi lit
# tests. The condition code must survive whichever encoding the relaxation
# selected.
pin_cond() {
_addr=$1
_label=$2
_cc=$3
func_body "$_addr" > "$TMP/fn.txt"
if ! grep -Eiq "^[0-9a-f]+:[[:space:]]+j[ra]${_cc}([[:space:]]|;|$)" \
"$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$_label has no J*${_cc} branch"
fi
echo " ok $_label: J*${_cc} branch"
}
pin_cond "$SUMTO" _sumto lt
pin_cond "$SUMTO" _sumto eq
pin_cond "$MAX2" _max2 gt
pin_cond "$LT" _lt lt
# At least one branch must have taken the one-word relative form; otherwise the
# relaxation silently did nothing and the code-size claim is meaningless.
grep -Eqio "^[0-9a-f]+:[[:space:]]+jr(uc|eq|ne|lt|le|gt|ge|lo|ls|hi|hs|p|n|v|nv|nn)([[:space:]]|;|$)" \
"$TMP/dis34.txt" || fail "no JR branch in the linked .text"
echo " ok JR relative branches present"
# GSPA rejects dotted .L labels; the harness gives each TU an LBB prefix.
grep -q 'LBB' "$ASM" || fail "linked assembly has no LBB block labels"
@@ -429,8 +436,15 @@ check_stk() {
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
tolower($0) ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
{ low = tolower($0) }
low ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
low ~ /mmtm[[:space:]]+sp,/ {
line = low
sub(/^.*mmtm[[:space:]]+sp,[[:space:]]*/, "", line)
sub(/[[:space:]]*;.*$/, "", line)
n += split(line, regs, ",")
}
low ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
' "$TMP/func.txt")
[ -n "$_pushes" ] || fail "$_label has no SETFP (MOVE A14,A13)"
_operand=$(grep -Eio '\*sp\(0x[0-9a-f]+\)' "$TMP/func.txt" | head -1 \
@@ -439,8 +453,8 @@ check_stk() {
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes pushes need $_want bits"
echo " ok $_label: $_pushes pushes -> *SP($(printf '0x%x' "$_want")), A14, 1"
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes saved slots need $_want bits"
echo " ok $_label: $_pushes saved slots -> *SP($(printf '0x%x' "$_want")), A14, 1"
}
check_stk "_sumto" "$SUMTO"
check_stk "_max2" "$MAX2"
+1 -1
View File
@@ -14,7 +14,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+236
View File
@@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Validate (and repair) a linked TI-COFF image for the VT1200 loader.
GSPLNK 2.00 has two observed output shapes that the loader rejects:
* when the test object has no initialised .data, it writes a fully zeroed
20-byte file header + 28-byte optional header, while the section table at
byte 48 is valid (loader status 3, "bad COFF magic");
* an odd-length .bss makes the section's bit size not a whole word (loader
status 4, "section size not whole words").
This helper validates the magic, the section table and the section sizes. With
--repair it reconstructs the zeroed header/optional header from the intact
section table and the linker map entry point, and rounds only .bss up to a
16-bit word. It never touches .text/.data contents or the entry point.
Usage: coff-check.py [--repair] [--entry HEX] FILE
"""
import argparse
import struct
import sys
FILE_MAGIC = 0x0090
OPT_MAGIC = 0x0108
OPT_VERSION = 0x00C7
FILE_FLAGS = 0x0103
OPT_HDR_SIZE = 28
ZERO_HEADER_SIZE = 20 + OPT_HDR_SIZE
def u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def put_u16(data, off, value):
struct.pack_into("<H", data, off, value)
def put_u32(data, off, value):
struct.pack_into("<I", data, off, value)
def section_at(data, off):
raw = data[off:off + 8]
name = raw.split(b"\0", 1)[0].decode("ascii", "replace")
return {
"off": off,
"name": name,
"paddr": u32(data, off + 8),
"size": u32(data, off + 16),
"scnptr": u32(data, off + 20),
"flags": u32(data, off + 36),
}
def parse(data):
if len(data) < 20:
raise ValueError("file is shorter than the 20-byte COFF header")
magic = u16(data, 0)
nscns = u16(data, 2)
opt = u16(data, 16)
return {
"magic": magic,
"nscns": nscns,
"opthdr": opt,
"optmagic": u16(data, 20) if opt else 0,
"entry": u32(data, 20 + 16) if opt else 0,
"textstart": u32(data, 20 + 20) if opt else 0,
}
def scan_recoverable_sections(data):
"""Recover the section table of GSPLNK's zero-header shape.
GSPLNK always leaves the 20-byte file header and 28-byte optional header
(48 bytes) zero, then writes the section table at byte 48. Stop at the
first entry whose name does not start with '.', so a trailing symbol table
is not mistaken for a section.
"""
if len(data) < ZERO_HEADER_SIZE + 40:
raise ValueError("no room for a recovered section table")
sections = []
off = ZERO_HEADER_SIZE
while off + 40 <= len(data) and len(sections) < 96:
sec = section_at(data, off)
if not sec["name"].startswith("."):
break
sections.append(sec)
off += 40
if not sections:
raise ValueError("zero header and no section table at byte 48")
return sections
def validate(data, sections, label):
bad = []
for sec in sections:
name = sec["name"]
size = sec["size"]
if not name:
bad.append("empty section name")
if size % 16 != 0 and name != ".bss":
bad.append(f"{name}: bit size {size} is not a whole word")
if name == ".bss" and size % 16 != 0:
bad.append(".bss: bit size %d is not a whole word" % size)
# scnptr points at raw bytes for non-.bss sections; the file must
# contain size/8 bytes there. .bss has no file payload.
if name != ".bss" and sec["scnptr"]:
need = sec["scnptr"] + (size + 7) // 8
if need > len(data):
bad.append(f"{name}: payload ends past EOF ({need} > {len(data)})")
if bad:
raise ValueError(f"{label}: " + "; ".join(bad))
def repair(data, entry):
header_zero = data[:20] == b"\0" * 20
opt_zero = data[20:ZERO_HEADER_SIZE] == b"\0" * OPT_HDR_SIZE
changed = []
if header_zero and opt_zero:
sections = scan_recoverable_sections(data)
names = {sec["name"]: sec for sec in sections}
for required in (".text", ".data", ".bss"):
if required not in names:
raise ValueError(f"recoverable header lacks {required}")
text = names[".text"]
dat = names[".data"]
bss = names[".bss"]
bss_size = (bss["size"] + 15) & ~15
if bss_size != bss["size"]:
put_u32(data, bss["off"] + 16, bss_size)
changed.append(f".bss size {bss['size']} -> {bss_size} bits")
# File header: magic, section count, timestamp, symbol pointer/count,
# optional-header size, flags.
put_u16(data, 0, FILE_MAGIC)
put_u16(data, 2, len(sections))
put_u32(data, 4, 0)
put_u32(data, 8, 0)
put_u32(data, 12, 0)
put_u16(data, 16, OPT_HDR_SIZE)
put_u16(data, 18, FILE_FLAGS)
# Optional header: magic, version, text/data/bss bits, entry and the
# text/data origins.
put_u16(data, 20, OPT_MAGIC)
put_u16(data, 22, OPT_VERSION)
put_u32(data, 24, text["size"])
put_u32(data, 28, dat["size"])
put_u32(data, 32, bss_size)
put_u32(data, 36, entry)
put_u32(data, 40, text["paddr"])
put_u32(data, 44, dat["paddr"])
changed.append("reconstructed zeroed file/optional header")
return changed, sections
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}, want {FILE_MAGIC:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
for sec in sections:
if sec["name"] == ".bss" and sec["size"] % 16 != 0:
new_size = (sec["size"] + 15) & ~15
put_u32(data, sec["off"] + 16, new_size)
# Keep the optional header's bss-size field consistent.
put_u32(data, 32, new_size)
changed.append(f".bss size {sec['size']} -> {new_size} bits")
sec["size"] = new_size
return changed, sections
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--repair", action="store_true",
help="repair the observed GSPLNK header/.bss shapes")
ap.add_argument("--entry", default="018A0000",
help="entry bit address for a reconstructed header")
ap.add_argument("file")
args = ap.parse_args()
try:
entry = int(args.entry, 16) if not args.entry.startswith("0x") else int(args.entry, 0)
except ValueError:
print(f"coff-check: bad --entry {args.entry}", file=sys.stderr)
return 2
try:
data = bytearray(open(args.file, "rb").read())
except OSError as exc:
print(f"coff-check: {exc}", file=sys.stderr)
return 1
try:
info = parse(data)
zero_header = info["magic"] == 0 and info["nscns"] == 0
if zero_header and not args.repair:
raise ValueError("zeroed file/optional header (GSPLNK shape); rerun with --repair")
if args.repair:
changed, sections = repair(data, entry)
if changed:
with open(args.file, "wb") as out:
out.write(data)
for item in changed:
print(f"coff-check: repaired {item}")
info = parse(data)
if info["magic"] != FILE_MAGIC:
raise ValueError(f"bad COFF magic {info['magic']:#06x}")
if info["nscns"] == 0 or info["opthdr"] != OPT_HDR_SIZE:
raise ValueError(
f"invalid header nscns={info['nscns']} opthdr={info['opthdr']}")
base = 20 + info["opthdr"]
if base + info["nscns"] * 40 > len(data):
raise ValueError("section table runs past EOF")
sections = [section_at(data, base + i * 40) for i in range(info["nscns"])]
validate(data, sections, "post-repair")
except ValueError as exc:
print(f"coff-check: FAIL: {exc}", file=sys.stderr)
return 1
names = ",".join(sec["name"] for sec in sections)
print(f"coff-check: OK sections={len(sections)} [{names}] entry={info['entry']:#010x}")
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -257,7 +257,7 @@ awk '
low ~ /^[[:space:]]*;/ { next }
!on { next }
expect == 1 {
if ($0 ~ /SETF 16, 0, 0/) { expect = 2 }
if ($0 ~ /SETF 16, 1, 0/) { expect = 2 }
else { bad++; expect = 0 }
next
}
@@ -273,7 +273,7 @@ read CALLS SETF_OK SETF_BAD < "$TMP/setf.count"
[ "$CALLS" -gt 0 ] || fail "linked assembly has no calls"
[ "$SETF_BAD" -eq 0 ] || fail "$SETF_BAD calls lack the SETF 16/32 pair"
[ "$SETF_OK" -eq "$CALLS" ] || fail "$CALLS calls but $SETF_OK post-call SETF 16/32 pairs"
echo " ok $CALLS calls each followed by SETF 16,0,0 + SETF 32,0,1"
echo " ok $CALLS calls each followed by SETF 16,1,0 + SETF 32,0,1"
# Old-STK: on_error saves 3 registers; its epilogue restores A14 from
# *SP((3+1)*32) = *SP(0x80). The prologue pushes A13, A0 and A1.
+1 -1
View File
@@ -7,7 +7,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+1 -1
View File
@@ -5,7 +5,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+1 -1
View File
@@ -5,7 +5,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+1 -1
View File
@@ -5,7 +5,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+307 -43
View File
@@ -15,10 +15,35 @@
# M4_LLC_OPT=-O0 llc optimization level (default: -O0)
# M4_ROM_SYMBOLS=1 append the per-ROM import stubs from symbols
# M4_EXTRA_ASM="/a.asm /b.asm" extra assembly to concatenate
# M4_EXTRA_INCLUDES="-I dir" extra tms-clang include flags
# M4_EXTRA_CFLAGS="-std=..." extra tms-clang language flags (default empty;
# the conformance sweep uses this for c-torture's
# gnu89 dialect; shipped gates pass nothing)
# M4_NATIVE=1 compile with llc -filetype=obj and link the
# objects with GSPLNK (the default is GSPA text)
# M4_NATIVE_SKIP_ASM=1 in native mode, do not also emit .s for a TU
# whose raw GSPA form is intentionally rejected
# (for example an odd-offset pointer record)
# M4_NATIVE_RTS=1 add `-l rts.lib` to the native link
# M4_NATIVE_LIBS="a b" add `-l a -l b` to the native link (library
# files must already be in the SDK directory; the
# conformance shim uses flib.lib/rts.lib for %f)
# M4_NATIVE_PROG_LEN=8000h native program region length (bits)
# M4_NATIVE_RAM_LEN=80000h native RAM region length (bits)
# M4_LINK_CMD=/path/link.cmd asm-path GSPLNK command file (default link.cmd)
# M4_LINKER=tms-link native-mode opt-in: link the GSPA entry/extras
# objects with tools/tms-link instead of GSPLNK
# (default: gsplnk). Requires M4_NATIVE=1 and no
# M4_NATIVE_LIBS/M4_NATIVE_RTS yet.
# M4_SKIP_MAME=1 stop after a clean GSPA/GSPLNK link
# M4_COFF_REPAIR=1 validate the linked COFF magic/section sizes and
# repair GSPLNK's observed zero-header and
# odd-.bss shapes (default 1; set 0 to validate
# only and fail on the defect)
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT LOADER_END
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC TMS_LINK MAME DOSBOX
# DOSBOX_CONF SDK_IMG M4_WORK M4_COFF M4_SDK M4_SYMS LOADER_AT
# LOADER_END M4_COFF_REPAIR
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
@@ -29,6 +54,7 @@ TMS_CLANG=${TMS_CLANG:-$LLVM_BIN/clang}
TMS_OPT=${TMS_OPT:-$LLVM_BIN/opt}
TMS_BITADDR=${TMS_BITADDR:-$ROOT/tools/tms-bitaddr/tms-bitaddr}
TMS_LLC=${TMS_LLC:-$LLVM_BIN/llc}
TMS_LINK=${TMS_LINK:-$ROOT/tools/tms-link/tms-link}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
@@ -50,6 +76,17 @@ ENTRY=${M4_ENTRY:-$DIR/entry.asm}
CHECK_LUA=${M4_CHECK_LUA:-$DIR/m4-check.lua}
CLANG_OPT=${M4_CLANG_OPT:--O0}
LLC_OPT=${M4_LLC_OPT:--O0}
EXTRA_INCLUDES=${M4_EXTRA_INCLUDES:-}
EXTRA_CFLAGS=${M4_EXTRA_CFLAGS:-}
NATIVE=${M4_NATIVE:-0}
NATIVE_SKIP_ASM=${M4_NATIVE_SKIP_ASM:-0}
NATIVE_RTS=${M4_NATIVE_RTS:-0}
NATIVE_LIBS=${M4_NATIVE_LIBS:-}
NATIVE_PROG_LEN=${M4_NATIVE_PROG_LEN:-8000h}
NATIVE_RAM_LEN=${M4_NATIVE_RAM_LEN:-80000h}
LINK_CMD=${M4_LINK_CMD:-$DIR/link.cmd}
LINKER=${M4_LINKER:-gsplnk}
COFF_REPAIR=${M4_COFF_REPAIR:-1}
fail() {
echo "m4: $*" >&2
@@ -59,6 +96,16 @@ fail() {
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
case $LINKER in
gsplnk|tms-link) ;;
*) fail "M4_LINKER must be 'gsplnk' or 'tms-link', got '$LINKER'" ;;
esac
if [ "$LINKER" = tms-link ]; then
[ "$NATIVE" = 1 ] || fail "M4_LINKER=tms-link requires M4_NATIVE=1"
[ -x "$TMS_LINK" ] || fail "missing tms-link: $TMS_LINK"
[ -z "$NATIVE_LIBS" ] && [ "$NATIVE_RTS" != 1 ] \
|| fail "M4_LINKER=tms-link does not read libraries yet; unset M4_NATIVE_LIBS/M4_NATIVE_RTS"
fi
[ -f "$ENTRY" ] || fail "missing entry: $ENTRY"
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
@@ -66,14 +113,33 @@ mkdir -p "$(dirname "$COFF")"
echo "== compile and select ($CLANG_OPT / llc $LLC_OPT)"
export TMS_CLANG TMS_OPT TMS_BITADDR
export TMS_CLANG_EXTRA_FLAGS="$EXTRA_CFLAGS"
for name in $SOURCES; do
src=$DIR/$name.c
case $name in
*/*) src=$name ;;
*) src=$DIR/$name.c ;;
esac
base=$(basename "$src" .c)
[ -f "$src" ] || fail "missing source: $src"
"$ROOT/scripts/tms-clang" "$CLANG_OPT" -o "$ASM/$name.ll" "$src"
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$name.ll" -o "$ASM/$name.s" \
|| fail "llc failed for $name.c"
echo " $name.s: $(grep -c . "$ASM/$name.s") lines"
# shellcheck disable=SC2086
"$ROOT/scripts/tms-clang" "$CLANG_OPT" $EXTRA_INCLUDES \
-o "$ASM/$base.ll" "$src"
if [ "$NATIVE" = 1 ]; then
if [ "$NATIVE_SKIP_ASM" != 1 ]; then
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
fi
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=obj \
"$ASM/$base.ll" -o "$ASM/$base.o" \
|| fail "llc -filetype=obj failed for $name"
echo " $base.o: $(wc -c < "$ASM/$base.o") bytes"
else
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$base.ll" -o "$ASM/$base.s" \
|| fail "llc -filetype=asm failed for $name"
echo " $base.s: $(grep -c . "$ASM/$base.s") lines"
fi
done
echo "== extract the 1987 SDK"
@@ -96,54 +162,249 @@ echo "== assemble and link with GSPA/GSPLNK under DOSBox"
# LBB0_1, LBB1_2, ... restarting in every translation unit. Give each TU its
# own LBB prefix, as the M3 runner does, so a multi-TU client (xshow + xgfix)
# cannot collide. The per-TU .s files keep their original labels.
tag=0
for name in $SOURCES; do
tag=$((tag + 1))
sed "s/LBB\([0-9][0-9]*_[0-9][0-9]*\)/LBB$tag\1/g" \
"$ASM/$name.s" > "$ASM/$name.unique.s"
done
cat "$ENTRY" > "$SDK/M4.ASM"
for name in $SOURCES; do
cat "$ASM/$name.unique.s" >> "$SDK/M4.ASM"
done
if [ -n "${M4_ROM_SYMBOLS:-}" ]; then
"$ROOT/scripts/m2/gen-rom-imports.sh" "$SYMS" "$WORK/rom-imports.asm"
fi
# A separately assembled entry must declare the symbols another object
# defines; GSPA otherwise treats an undefined reference as an assembly error.
# (In the asm path the definitions are in the same concatenated assembly.)
entry_externs() {
awk '
{
line = $0
sub(/;.*/, "", line)
if (line ~ /^[[:space:]]*\.(globl|ref|bss)[[:space:]]/) {
n = split(line, a, /[[:space:],]+/)
for (i = 1; i <= n; i++)
if (a[i] ~ /^_[A-Za-z0-9_]+$/) known[a[i]] = 1
}
if (line ~ /^[[:space:]]*_[A-Za-z0-9_]+:/) {
s = line
sub(/^[[:space:]]*/, "", s)
sub(/:.*/, "", s)
known[s] = 1
}
n = split(line, a, /[^A-Za-z0-9_]+/)
for (i = 1; i <= n; i++)
if (a[i] ~ /^_[A-Za-z0-9_]+$/) ref[a[i]] = 1
}
END { for (s in ref) if (!known[s]) print s }
' "$@" | sort
}
strip_end() {
sed '/^[[:space:]]*\.end[[:space:]]*$/d' "$1"
}
EXTRAS=
if [ -n "${M4_EXTRA_ASM:-}" ]; then
for extra in $M4_EXTRA_ASM; do
[ -f "$extra" ] || fail "missing extra assembly: $extra"
cat "$extra" >> "$SDK/M4.ASM"
EXTRAS="$EXTRAS $extra"
done
fi
if [ -n "${M4_ROM_SYMBOLS:-}" ]; then
"$ROOT/scripts/m2/gen-rom-imports.sh" "$SYMS" "$WORK/rom-imports.asm"
cat "$WORK/rom-imports.asm" >> "$SDK/M4.ASM"
EXTRAS="$EXTRAS $WORK/rom-imports.asm"
fi
if [ "$NATIVE" = 1 ]; then
# Assemble the entry and the extras (cinit, ROM import stubs) as their own
# objects, with the extras last. That keeps the linked layout equal to the
# default asm path (entry, C code, extras), so the dis34 stream comparison
# sees the same function addresses.
{
entry_externs "$ENTRY" | sed 's/^/\t.globl\t/'
strip_end "$ENTRY"
printf '\t.end\n'
} > "$SDK/M4.ASM"
if [ -n "$EXTRAS" ]; then
{
# shellcheck disable=SC2086
entry_externs $EXTRAS | sed 's/^/\t.globl\t/'
for extra in $EXTRAS; do
strip_end "$extra"
done
printf '\t.end\n'
} > "$SDK/M4EXT.ASM"
fi
NATIVE_OBJS="M4.OBJ"
for name in $SOURCES; do
case $name in
*/*) src=$name ;;
*) src=$DIR/$name.c ;;
esac
base=$(basename "$src" .c)
dos=$(printf '%s' "$base" | tr '[:lower:]' '[:upper:]')
[ "${#dos}" -le 8 ] \
|| fail "native object name '$dos.OBJ' does not fit 8.3"
cp "$ASM/$base.o" "$SDK/$dos.OBJ"
NATIVE_OBJS="$NATIVE_OBJS $dos.OBJ"
done
if [ -n "$EXTRAS" ]; then
NATIVE_OBJS="$NATIVE_OBJS M4EXT.OBJ"
fi
if [ "$NATIVE_RTS" = 1 ]; then
[ -f "$SDK/RTS.LIB" ] || fail "RTS.LIB not extracted into $SDK"
NATIVE_LIBS="$NATIVE_LIBS rts.lib"
fi
for lib in $NATIVE_LIBS; do
dos=$(printf '%s' "$lib" | tr '[:lower:]' '[:upper:]')
[ -f "$SDK/$dos" ] || [ -f "$SDK/$lib" ] \
|| fail "$lib not extracted into $SDK"
done
{
printf '%s\n' '-a' '-o M4.OUT' '-m M4.MAP' '-e _start'
printf '%s\n' "$NATIVE_OBJS"
for lib in $NATIVE_LIBS; do
printf '%s\n' "-l $lib"
done
printf '%s\n' 'MEMORY' '{'
printf ' prog: origin = 018A0000h, length = %s\n' "$NATIVE_PROG_LEN"
printf ' ram: origin = 01A00000h, length = %s\n' "$NATIVE_RAM_LEN"
printf '%s\n' '}'
printf '%s\n' 'SECTIONS' '{'
printf '%s\n' ' .text: {} > prog'
printf '%s\n' ' .data: {} > prog'
printf '%s\n' ' .cinit: {} > prog'
printf '%s\n' ' .bss: {} > ram'
printf '%s\n' '}'
} > "$WORK/m4.cmd"
sed 's/$/\r/' "$WORK/m4.cmd" > "$SDK/M4.CMD"
else
tag=0
for name in $SOURCES; do
case $name in
*/*) src=$name ;;
*) src=$DIR/$name.c ;;
esac
base=$(basename "$src" .c)
tag=$((tag + 1))
sed "s/LBB\([0-9][0-9]*_[0-9][0-9]*\)/LBB$tag\1/g" \
"$ASM/$base.s" > "$ASM/$base.unique.s"
done
cat "$ENTRY" > "$SDK/M4.ASM"
for name in $SOURCES; do
case $name in
*/*) src=$name ;;
*) src=$DIR/$name.c ;;
esac
base=$(basename "$src" .c)
cat "$ASM/$base.unique.s" >> "$SDK/M4.ASM"
done
if [ -n "${M4_EXTRA_ASM:-}" ]; then
for extra in $M4_EXTRA_ASM; do
cat "$extra" >> "$SDK/M4.ASM"
done
fi
if [ -n "${M4_ROM_SYMBOLS:-}" ]; then
cat "$WORK/rom-imports.asm" >> "$SDK/M4.ASM"
fi
# The linker command file must keep CRLF line endings.
sed 's/\r$//' "$LINK_CMD" | sed 's/$/\r/' > "$SDK/M4.CMD"
fi
# The linker command file must keep CRLF line endings.
sed 's/\r$//' "$DIR/link.cmd" | sed 's/$/\r/' > "$SDK/M4.CMD"
rm -f "$SDK/M4.OBJ" "$SDK/M4.OUT" "$SDK/M4.MAP" "$SDK/M4.LST"
rm -f "$SDK/M4EXT.OBJ" "$SDK/M4EXT.LST"
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gsplnk M4.cmd" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
run_dosbox() {
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf "$@" > "$WORK/dosbox.log" 2>&1
}
[ -f "$SDK/M4.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M4.LST" > "$WORK/m4.lst"
grep -q 'No Errors' "$WORK/m4.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/m4.lst" >&2 || true; fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/m4.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/m4.lst" >&2 || true; fail "GSPA reported warnings"; }
[ -f "$SDK/M4.OUT" ] || fail "GSPLNK produced no M4.OUT"
if [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
# tms-link is a host tool: GSPA still assembles the entry/extras objects,
# but GSPLNK is not run.
if [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gspa M4EXT M4EXT.obj M4EXT.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
else
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
elif [ "$NATIVE" = 1 ] && [ -n "$EXTRAS" ]; then
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gspa M4EXT M4EXT.obj M4EXT.lst -l" \
-c "gsplnk M4.cmd" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
else
run_dosbox \
-c "mount c $SDK" -c "c:" \
-c "gspa M4 M4.obj M4.lst -l" \
-c "gsplnk M4.cmd" \
-c "exit" -exit \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
fi
if [ "$NATIVE" = 1 ] && [ "$LINKER" = tms-link ]; then
TMSLINK_INPUTS=
for obj in $NATIVE_OBJS; do
TMSLINK_INPUTS="$TMSLINK_INPUTS $SDK/$obj"
done
echo "== link with tools/tms-link"
# shellcheck disable=SC2086
"$TMS_LINK" -o "$SDK/M4.OUT" --map "$SDK/M4.MAP" --entry _start \
--text 018A0000 --bss 01A00000 \
--prog-len "$NATIVE_PROG_LEN" --ram-len "$NATIVE_RAM_LEN" \
$TMSLINK_INPUTS \
|| fail "tms-link failed"
fi
check_lst() {
lst=$1
[ -f "$SDK/$lst.LST" ] \
|| fail "GSPA produced no $lst.LST (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/$lst.LST" > "$WORK/$lst.lst"
grep -q 'No Errors' "$WORK/$lst.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/$lst.lst" >&2 || true; \
fail "GSPA reported errors in $lst"; }
grep -q 'No Warnings' "$WORK/$lst.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/$lst.lst" >&2 || true; \
fail "GSPA reported warnings in $lst"; }
}
check_lst M4
[ -z "$EXTRAS" ] || [ "$NATIVE" != 1 ] || check_lst M4EXT
[ -f "$SDK/M4.OUT" ] || fail "$LINKER produced no M4.OUT"
sed 's/\r$//' "$SDK/M4.MAP" > "$WORK/m4.map"
cp "$SDK/M4.OUT" "$COFF"
cp "$SDK/M4.ASM" "$WORK/m4.asm"
[ ! -f "$SDK/M4EXT.ASM" ] || cp "$SDK/M4EXT.ASM" "$WORK/m4ext.asm"
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m4.map")
[ "$ENTRY_ADDR" = "018A0000" ] || fail "linker entry _start is '$ENTRY_ADDR', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m4.map" \
|| fail "linker map has no _start entry point"
# GSPLNK 2.00 can zero the 48-byte file+optional header (observed on links
# whose test object contributed no initialized .data), and can emit an odd
# .bss size.
# Validate every linked COFF and repair only those two known shapes; any other
# malformed image is a hard link failure.
command -v python3 >/dev/null 2>&1 || fail "python3 is required for COFF validation"
if [ "$COFF_REPAIR" = 1 ]; then
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --repair \
--entry "$ENTRY_ADDR" "$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation/repair failed for $COFF"; }
else
coff_out=$(python3 "$ROOT/scripts/m4/coff-check.py" --entry "$ENTRY_ADDR" \
"$COFF" 2>&1) \
|| { printf '%s\n' "$coff_out" | sed 's/^/ /' >&2; \
fail "COFF validation failed for $COFF"; }
fi
printf '%s\n' "$coff_out" | sed 's/^/ /'
echo " linked .text at 018A0000, M4.OUT -> $COFF"
if [ -n "${M4_SKIP_MAME:-}" ]; then
@@ -176,15 +437,18 @@ timeout "${MAME_TIMEOUT:-900}" "$MAME" vt1200 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M4: ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4 markers"; }
MARKERS=$(grep -E '^(M4|M7): ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4/M7 markers"; }
echo " $MARKERS"
grep -q 'LOADER: result status=0 (OK)' "$WORK/mame.log" \
|| { grep 'LOADER: result' "$WORK/mame.log" >&2 || true; fail "COFF loader did not report status 0"; }
grep -q 'placed \.text .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .text bytes"
grep -q '^M4 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "M4 marker check failed"; }
grep -qE '^M[47] MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
echo "M4 MAME: PASS"
case "$MARKERS" in
M7:*) echo "M7 MAME: PASS" ;;
*) echo "M4 MAME: PASS" ;;
esac
+5 -5
View File
@@ -3,11 +3,11 @@
* driver's late-GEP policy.
*
* The optimizer's switch-to-lookup-table transform creates a new i8 GEP after
* tms-bitaddr --scale; --normalize cannot tell that index apart from an
* already-scaled bit offset, so the table would be indexed one bit per slot.
* tms-clang passes -switch-to-lookup=false; this source makes the hazard
* reachable at -O2 (termtris' init_game and runesc switches are the real
* cases).
* tms-bitaddr --scale. tms-clang's post-opt --scale converts that byte/element
* index to bits (M6 Task 6 generalized this beyond the old switch.table-only
* normalize rule). This source makes the hazard reachable at -O2 (termtris'
* init_game and runesc switches are the real cases): a missed scale would
* index the table one bit per slot.
*/
int sw_tile(int c)
{
+107 -1
View File
@@ -39,6 +39,16 @@ ROM_HI=$((0x3FFFFFFF))
MAPWINDOW=$((0x3FD64F60))
RAISEWINDOW=$((0x3FD645B0))
# M7.3 wider surface: the six GUI_APPS table entries, pinned as addresses as
# well as by opcode/helper. A table edit to a different builder with the same
# opcode still fails here.
WIDER_MAPSUBWINDOWS=$((0x3FD64BF0))
WIDER_CHANGEWATTRS=$((0x3FD38770))
WIDER_CONFIGUREWINDOW=$((0x3FD3A510))
WIDER_INTERNATOM=$((0x3FD5E420))
WIDER_CHANGEPROPERTY=$((0x3FD37330))
WIDER_CHANGEGC=$((0x3F999F80))
fail() {
echo "m4 validate-syms: FAIL: $*" >&2
exit 1
@@ -79,6 +89,10 @@ require_match() { # require_match DIS_TEXT ERE WHAT
}
}
require_addr() { # require_addr NAME ADDR WANT WHAT
[ "$(($2))" -eq "$3" ] || fail "$1 is $2, expected $(printf '0x%08X' "$3") ($4)"
}
check_prologue() { # check_prologue NAME ADDR
_name=$1
_addr=$2
@@ -229,6 +243,97 @@ check_xcreateimage() {
echo " ok XCreateImage allocates an 88-byte XImage"
}
# The M7.3 wider surface: six public entries from the GUI_APPS table. Each
# body is the ROM request builder named by that table, so pin the request
# opcode (and the helper each builder calls) rather than trusting the name.
# XMapSubwindows opcode 9
# XChangeWindowAttributes opcode 2, values walker 0x3FDA A550
# XConfigureWindow opcode 12, fixed CWX|CWY|CWWidth|CWHeight mask 15
# XInternAtom opcode 16, strlen on the name
# XChangeProperty opcode 18, blit_copy for the value bytes
# XChangeGC opcode 56 (0x38), GC cache serializer 0x3F997AD0
check_wider_xlib() {
_addr=$(sym_addr XMapSubwindows)
[ -n "$_addr" ] || fail "table has no XMapSubwindows entry"
require_addr XMapSubwindows "$_addr" "$WIDER_MAPSUBWINDOWS" "GUI_APPS"
dis_at "$((_addr))" 384 "$TMP/mapsubwindows"
require_match "$TMP/mapsubwindows" 'movk[[:space:]]+9,[[:space:]]+a[0-9]+' \
"XMapSubwindows does not build MapSubwindows request opcode 9"
require_match "$TMP/mapsubwindows" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XMapSubwindows does not write its request opcode to the buffer"
echo " ok XMapSubwindows builds MapSubwindows opcode 9"
_addr=$(sym_addr XChangeWindowAttributes)
[ -n "$_addr" ] || fail "table has no XChangeWindowAttributes entry"
require_addr XChangeWindowAttributes "$_addr" "$WIDER_CHANGEWATTRS" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/changewattrs"
require_match "$TMP/changewattrs" 'movk[[:space:]]+2,[[:space:]]+a[0-9]+' \
"XChangeWindowAttributes does not build ChangeWindowAttributes request opcode 2"
require_match "$TMP/changewattrs" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeWindowAttributes does not write its request opcode to the buffer"
require_match "$TMP/changewattrs" 'calla[[:space:]]+0x3fdaa550' \
"XChangeWindowAttributes does not call the XSetWindowAttributes value walker"
echo " ok XChangeWindowAttributes builds opcode 2 + value walker"
_addr=$(sym_addr XConfigureWindow)
[ -n "$_addr" ] || fail "table has no XConfigureWindow entry"
require_addr XConfigureWindow "$_addr" "$WIDER_CONFIGUREWINDOW" "GUI_APPS"
dis_at "$((_addr))" 448 "$TMP/configurewindow"
require_match "$TMP/configurewindow" 'movk[[:space:]]+12,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not build ConfigureWindow request opcode 12"
require_match "$TMP/configurewindow" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XConfigureWindow does not write its request opcode to the buffer"
require_match "$TMP/configurewindow" 'movk[[:space:]]+15,[[:space:]]+a[0-9]+' \
"XConfigureWindow does not arm the fixed CWX|CWY|CWWidth|CWHeight mask 15"
require_match "$TMP/configurewindow" '\*a13\(0xffa0\)' \
"XConfigureWindow does not read the x argument (a13-12)"
require_match "$TMP/configurewindow" '\*a13\(0xff80\)' \
"XConfigureWindow does not read the y argument (a13-16)"
require_match "$TMP/configurewindow" '\*a13\(0xff60\)' \
"XConfigureWindow does not read the width argument (a13-20)"
require_match "$TMP/configurewindow" '\*a13\(0xff40\)' \
"XConfigureWindow does not read the height argument (a13-24)"
echo " ok XConfigureWindow builds opcode 12, fixed mask 15, x/y/width/height"
_addr=$(sym_addr XInternAtom)
[ -n "$_addr" ] || fail "table has no XInternAtom entry"
require_addr XInternAtom "$_addr" "$WIDER_INTERNATOM" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/internatom"
require_match "$TMP/internatom" 'movk[[:space:]]+16,[[:space:]]+a[0-9]+' \
"XInternAtom does not build InternAtom request opcode 16"
require_match "$TMP/internatom" 'calla[[:space:]]+0x3fb458d0' \
"XInternAtom does not strlen the atom name"
require_match "$TMP/internatom" '\*a13\(0xffa0\)' \
"XInternAtom does not read the only_if_exists argument (a13-12)"
echo " ok XInternAtom builds opcode 16, strlens the name"
_addr=$(sym_addr XChangeProperty)
[ -n "$_addr" ] || fail "table has no XChangeProperty entry"
require_addr XChangeProperty "$_addr" "$WIDER_CHANGEPROPERTY" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changeproperty"
require_match "$TMP/changeproperty" 'movk[[:space:]]+18,[[:space:]]+a[0-9]+' \
"XChangeProperty does not build ChangeProperty request opcode 18"
require_match "$TMP/changeproperty" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeProperty does not write its request opcode to the buffer"
require_match "$TMP/changeproperty" 'calla[[:space:]]+0x3fb44400' \
"XChangeProperty does not copy its value bytes through blit_copy"
require_match "$TMP/changeproperty" '\*a13\(0xff00\)' \
"XChangeProperty does not read the nelements argument (a13-32)"
echo " ok XChangeProperty builds opcode 18, blit_copy value bytes"
_addr=$(sym_addr XChangeGC)
[ -n "$_addr" ] || fail "table has no XChangeGC entry"
require_addr XChangeGC "$_addr" "$WIDER_CHANGEGC" "GUI_APPS"
dis_at "$((_addr))" 512 "$TMP/changegc"
require_match "$TMP/changegc" 'movi[[:space:]]+0x38,[[:space:]]+a[0-9]+' \
"XChangeGC does not build ChangeGC request opcode 56 (0x38)"
require_match "$TMP/changegc" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XChangeGC does not write its request opcode to the buffer"
require_match "$TMP/changegc" 'calla[[:space:]]+0x3f997ad0' \
"XChangeGC does not call the GC value-cache serializer"
echo " ok XChangeGC builds opcode 56, flushes the GC value cache"
}
# The error-handler setters write the per-process XG block: IO at +0x40,
# protocol error at +0x60. The defaults are the ROM's _XDefaultIOError and
# _XDefaultError.
@@ -273,6 +378,7 @@ check_image_requests
check_font_copy
check_pixmap_focus
check_xcreateimage
check_wider_xlib
check_error_handlers
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned)"
echo "m4 validate-syms: PASS ($count v2.2 entries in ROM, aligned, prologues valid; XMapWindow/XRaiseWindow pinned; M7.3 wider Xlib opcodes pinned)"
+1 -1
View File
@@ -3,7 +3,7 @@
.globl _start
.globl _varargs_test
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+141 -3
View File
@@ -230,6 +230,107 @@ typedef union _XEvent {
#define XYPixmap 1
#define ZPixmap 2
/*
* M7.3 wider Xlib surface. The VT1200 ROM is X11R4: these are the X11R4
* value-mask bits and struct layouts (32-bit fields, packed by the TMS34010
* C ABI). The ROM's own request builders use the same ordering: the
* ConfigureWindow entry arms CWX|CWY|CWWidth|CWHeight (mask 15), and the
* window-attributes walker reads background_pixel from byte 4.
*/
typedef struct {
int x, y;
int width, height;
int border_width;
Window sibling;
int stack_mode;
} XWindowChanges;
#define CWBackPixmap (1L << 0)
#define CWBackPixel (1L << 1)
#define CWBorderPixmap (1L << 2)
#define CWBorderPixel (1L << 3)
#define CWBitGravity (1L << 4)
#define CWWinGravity (1L << 5)
#define CWBackingStore (1L << 6)
#define CWBackingPlanes (1L << 7)
#define CWBackingPixel (1L << 8)
#define CWOverrideRedirect (1L << 9)
#define CWSaveUnder (1L << 10)
#define CWEventMask (1L << 11)
#define CWDontPropagate (1L << 12)
#define CWColormap (1L << 13)
#define CWCursor (1L << 14)
#define CWX (1L << 0)
#define CWY (1L << 1)
#define CWWidth (1L << 2)
#define CWHeight (1L << 3)
#define CWBorderWidth (1L << 4)
#define CWSibling (1L << 5)
#define CWStackMode (1L << 6)
/* X11R4 XSetWindowAttributes: background_pixel is byte 4 (CWBackPixel). */
typedef struct {
unsigned long background_pixmap;
unsigned long background_pixel;
unsigned long border_pixmap;
unsigned long border_pixel;
int bit_gravity;
int win_gravity;
int backing_store;
unsigned long backing_planes;
unsigned long backing_pixel;
Bool save_under;
long event_mask;
long do_not_propagate_mask;
Bool override_redirect;
Colormap colormap;
Cursor cursor;
} XSetWindowAttributes;
/* X11R4 XGCValues: the ROM value walker reads GCFont's field at byte 60. */
typedef struct {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
Pixmap tile;
Pixmap stipple;
int ts_x_origin;
int ts_y_origin;
Font font;
int subwindow_mode;
int graphics_exposures;
int clip_x_origin;
int clip_y_origin;
Pixmap clip_mask;
int dash_offset;
char dashes;
} XGCValues;
#define GCFunction (1L << 0)
#define GCPlaneMask (1L << 1)
#define GCForeground (1L << 2)
#define GCBackground (1L << 3)
#define GCLineWidth (1L << 4)
#define GCLineStyle (1L << 5)
#define GCCapStyle (1L << 6)
#define GCJoinStyle (1L << 7)
#define GCFillStyle (1L << 8)
#define GCFillRule (1L << 9)
#define GCTile (1L << 10)
#define GCStipple (1L << 11)
#define GCTileStipXOrigin (1L << 12)
#define GCTileStipYOrigin (1L << 13)
#define GCFont (1L << 14)
#define True 1
#define False 0
#define None 0L
@@ -241,9 +342,10 @@ typedef int (*XIOErrorHandler)(Display *);
* Real Xlib entry points. The VT1200 ROM exports these names; Task 5
* validates their bit addresses in symbols/vt1200-v22.syms.
*
* XCreateGC's XGCValues* and XLookupString's XComposeStatus* are modelled as
* void*: the layout is not needed by the M4 clients and the 32-bit pointer
* ABI is unchanged.
* XCreateGC's values argument stays void* (the 32-bit pointer ABI is
* unchanged); the X11R4 XGCValues layout is declared above for the M7.3
* wider-surface client and its offset checks. XLookupString's
* XComposeStatus* is modelled as void*.
*/
extern Display *XOpenDisplay(const char *name);
extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
@@ -252,6 +354,38 @@ extern Window XCreateSimpleWindow(Display *display, Window parent, int x, int y,
unsigned long border,
unsigned long background);
extern int XMapWindow(Display *display, Window window);
/*
* M7.3 wider surface, validated in symbols/vt1200-v22.syms.
*
* XMapSubwindows maps every child of `window` (MapSubwindows opcode 9).
*/
extern int XMapSubwindows(Display *display, Window window);
/*
* The ROM's ConfigureWindow entry (0x3FD3A510) is the fixed-mask builder:
* opcode 12, value-mask CWX|CWY|CWWidth|CWHeight, and four scalar arguments.
* That is Xlib's XMoveResizeWindow call shape, not the XWindowChanges-pointer
* shape; XWindowChanges above documents the same four values.
*/
extern int XConfigureWindow(Display *display, Window window, int x, int y,
unsigned int width, unsigned int height);
/* ChangeWindowAttributes opcode 2 (XSetWindowAttributes value walker). */
extern int XChangeWindowAttributes(Display *display, Window window,
unsigned long valuemask,
XSetWindowAttributes *attributes);
/* InternAtom opcode 16; only_if_exists False creates the atom. */
extern Atom XInternAtom(Display *display, const char *name,
Bool only_if_exists);
/* ChangeProperty opcode 18; format 8, mode PropModeReplace = 0. */
extern int XChangeProperty(Display *display, Window window, Atom property,
Atom type, int format, int mode,
const unsigned char *data, int nelements);
/*
* ChangeGC opcode 56. The ROM entry's public shape is (display, gc): it
* serializes the GC's pending value cache (the same serializer the drawing
* primitives call). Values are selected by the cache setters, e.g.
* XSetForeground, or by XCreateGC's XGCValues.
*/
extern int XChangeGC(Display *display, GC gc);
/* CreatePixmap opcode 0x35; depth 1 for the image client's 1-bit pixmap. */
extern Pixmap XCreatePixmap(Display *display, Drawable drawable,
unsigned int width, unsigned int height,
@@ -298,6 +432,10 @@ extern XImage *XCreateImage(Display *display, Visual *visual,
extern int XPutImage(Display *display, Drawable drawable, GC gc, XImage *image,
int src_x, int src_y, int dest_x, int dest_y,
unsigned int width, unsigned int height);
/* GetImage opcode 0x49: synchronous reply; format is XYPixmap or ZPixmap. */
extern XImage *XGetImage(Display *display, Drawable drawable, int x, int y,
unsigned int width, unsigned int height,
unsigned long plane_mask, int format);
extern int XDestroyImage(XImage *image);
extern XErrorHandler XSetErrorHandler(XErrorHandler handler);
extern XIOErrorHandler XSetIOErrorHandler(XIOErrorHandler handler);
+1 -1
View File
@@ -12,7 +12,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+69
View File
@@ -0,0 +1,69 @@
; native-entry.asm -- M5 native-object entry, linked at bit 018A0000.
;
; Calls the object produced by llc -filetype=obj and writes six markers:
; 018A8000 native_value() == 42
; 018A8020 native_combo() == 152 (42 + 'n')
; 018A8040 native_bump() == 1
; 018A8060 native_bump() == 2
; 018A8080 native_loop(5) == 10
; 018A80A0 native_call_external() == 77
;
; native_combo() calls native_value() and native_first(); both are .text
; symbols, so the CALLAs are same-section 0xFFFF relocations. The
; cross-section section-symbol relocation path is exercised by native_first()'s
; MOVI to the .data object msg and native_bump()'s MOVI to the .bss object
; native_counter. native_loop() carries the conditional/unconditional branch
; relocations. native_external() is defined here and is an undefined C_EXT
; reference in the llc object. The object is assembled separately with GSPA
; 2.00 and the two objects are linked by GSPLNK 2.00.
.ref _native_value
.ref _native_combo
.ref _native_bump
.ref _native_loop
.ref _native_call_external
.text
.globl _native_entry
_native_entry:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _native_value
move a8, @018A8000h, 1
calla _native_combo
move a8, @018A8020h, 1
calla _native_bump
move a8, @018A8040h, 1
calla _native_bump
move a8, @018A8060h, 1
move a14, -*sp, 1
movi 5, a0
move a0, *a14+, 1
calla _native_loop
move a8, @018A8080h, 1
calla _native_call_external
move a8, @018A80A0h, 1
rets
.globl _native_external
_native_external:
; Same prologue/epilogue as an llc-compiled leaf so native_call_external
; gets the A14 frame it expects on return.
setf 16, 1, 0
setf 32, 0, 1
move a13, -*sp, 1
move a0, -*sp, 1
move a14, a13
addi 32, a14
move a13, a0
addi -32, a0
move *a0, a0, 1
movi 77, a0
move a0, a8
move *sp(96), a14, 1
move *sp+, a0, 1
move *sp+, a13, 1
rets 2
.bss _cstack, 32768, 16
.end
+124
View File
@@ -0,0 +1,124 @@
/* M5 native-link: one translation unit that the native TI-COFF object path
* must link with a GSPA entry object.
*
* native_value() lives in .text and is called from native-entry.asm.
* msg is a .data pointer to the "native" string; native_first() loads it with
* a cross-section MOVI, so the object needs a .data symbol relocation.
* native_combo() calls native_value() and native_first(): both target .text
* symbols, so those CALLAs are same-section relocations resolved through the
* 0xFFFF section-relative path. A cross-section CALL would need a second code
* section, which this writer does not represent; the shared section-symbol
* relocation path is exercised by the .data and .bss MOVIs instead.
*/
int native_value(void) { return 42; }
const char *msg = "native";
int native_first(void) { return msg[0]; }
/* Element 1 is at a non-zero .bss offset, so the MOVI relocation field is a
* meaningful bit addend rather than an ambiguous zero. */
int native_counter[2];
int native_bump(void) {
native_counter[1] = native_counter[1] + 1;
return native_counter[1];
}
int native_combo(void) { return native_value() + native_first(); }
/* A conditional branch and a back edge, so the object carries JAcc/JAUC
* relocations that GSPLNK must resolve. The in-range branches here are
* relaxed to the one-word JR form; native_far() below keeps the conditional
* absolute form covered. */
int native_loop(int n) {
int s = 0;
for (int i = 0; i < n; ++i)
s += i;
return s;
}
/* A conditional branch whose target is far outside the 127-word one-word
* range (about 280 words with 64 volatile reads, so a small codegen change
* cannot flip it back): the relaxation cannot use JR, so the object still
* carries a conditional JA<cc> relocation. The volatile loads keep the body
* from being folded away. */
volatile int native_probe;
int native_far(int a) {
int s = 0;
if (a) {
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
s += native_probe;
}
return s;
}
/* Defined by native-entry.asm: an undefined C_EXT section-0 symbol plus the
* text relocation that GSPLNK resolves against the entry object. */
extern int native_external(int);
int native_call_external(void) { return native_external(37); }
+16
View File
@@ -0,0 +1,16 @@
-a
-o NATIVE.OUT
-m NATIVE.MAP
-e _native_entry
NATIVE.O ENTRY.O
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+84
View File
@@ -0,0 +1,84 @@
#!/bin/sh
# M5 native-object compile/link driver.
#
# scripts/m5/native.sh [xshow|termtris]
#
# The default mode is `termtris`, so scripts/tests/m4/termtris.sh can use this
# script as its TERMTRIS_BUILD hook: it produces $TERMTRIS_WORK/termtris.coff
# and termtris.map from the six pinned C TUs compiled with
# `llc -filetype=obj` and linked by GSPLNK. The gate then runs the unchanged
# play_keys/MAME checks.
#
# `xshow` builds scripts/m4/xshow.c + xgfix.c through scripts/m4/run.sh with
# M4_NATIVE=1, links them with GSPLNK and runs the M4 image/event MAME check.
# The asm/GSPA path remains the default of run.sh.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN
# M5_XSHOW_WORK TERMTRIS_WORK TERMTRIS_SDK VT1200_TERMTRIS
# M4_SDK DOSBOX DOSBOX_CONF SDK_IMG MAME LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
MODE=${1:-termtris}
DIR=$ROOT/scripts/m4
TERMTRIS_DIR=$DIR/termtris
VENDOR=${VT1200_TERMTRIS:-$ROOT/vendor/vt1200-termtris}
fail() {
echo "M5 native driver: $*" >&2
exit 1
}
case $MODE in
xshow)
WORK=${M5_XSHOW_WORK:-$ROOT/build/m5-native-xshow}
M4_NATIVE=1 \
M4_SOURCES="xshow xgfix" \
M4_ENTRY="$DIR/xshow-entry.asm" \
M4_CHECK_LUA="$DIR/xshow-check.lua" \
M4_CLANG_OPT=-O2 \
M4_LLC_OPT=-O0 \
M4_ROM_SYMBOLS=1 \
LOADER_AT=2500 \
LOADER_END=3400 \
M4_WORK="$WORK" \
VT1200_SKIP_LEVEL1=1 \
VT1200_MONITOR=VR319 \
"$DIR/run.sh"
;;
termtris)
WORK=${TERMTRIS_WORK:-$ROOT/build/m5-native-termtris}
SRC=$VENDOR/apps/termtris/src
[ -d "$SRC" ] || fail "missing pinned termtris source: $SRC"
if git -C "$VENDOR" rev-parse --git-dir >/dev/null 2>&1; then
rev=$(git -C "$VENDOR" rev-parse HEAD)
[ "$rev" = "be5b323f5d2cc4f7a7d25e7143c67bd9828ccbdf" ] \
|| fail "vendor tree is $rev, want be5b323f5d2cc4f7a7d25e7143c67bd9828ccbdf"
fi
mkdir -p "$WORK"
# cinit.asm is a GSPA entry piece (`.sect ".cinit"`); it is assembled into
# the extras object, not compiled by llc. The rts.lib .cinit data makes the
# section non-empty, so the empty cinit.asm is sufficient (the asm gate's
# CINITZ fallback is only needed when no library contributes .cinit).
M4_NATIVE=1 \
M4_SKIP_MAME=1 \
M4_SOURCES="$SRC/vt1200/main.c $SRC/game.c $SRC/vt1200/scoredb.c $SRC/vt1200/x11.c $SRC/vt1200/compat.c $SRC/vt1200/xgfix.c" \
M4_EXTRA_INCLUDES="-I $SRC -I $SRC/vt1200 -I $TERMTRIS_DIR/include" \
M4_ENTRY="$SRC/vt1200/entry.asm" \
M4_EXTRA_ASM="$SRC/vt1200/cinit.asm" \
M4_CLANG_OPT=-O2 \
M4_LLC_OPT=-O0 \
M4_NATIVE_RTS=1 \
M4_NATIVE_PROG_LEN=40000h \
M4_NATIVE_RAM_LEN=40000h \
M4_WORK="$WORK" \
M4_COFF="$WORK/termtris.coff" \
M4_SDK="${TERMTRIS_SDK:-$WORK/sdk}" \
"$DIR/run.sh"
# play_keys.sh reads the linker map by name; run.sh writes m4.map.
cp "$WORK/m4.map" "$WORK/termtris.map"
;;
*)
fail "unknown mode '$MODE' (want xshow or termtris)"
;;
esac
+6
View File
@@ -0,0 +1,6 @@
/* Long private name, TU a: identical in private-long-b.c so the old naming
* scheme would truncate the 8-hex module token at GSPA's 31-character limit
* and emit the same label in both translation units. */
static const char this_is_a_very_long_private_name[] = "same";
char *a(void) { return (char *)this_is_a_very_long_private_name; }
+6
View File
@@ -0,0 +1,6 @@
/* Long private name, TU b: deliberately identical to private-long-a.c. The
* capped base plus the name hash and module token must keep the two labels
* distinct within GSPA's 31-character identifier limit. */
static const char this_is_a_very_long_private_name[] = "same";
char *b(void) { return (char *)this_is_a_very_long_private_name; }
+85
View File
@@ -0,0 +1,85 @@
/*
* abi-oracle.c -- the 1987 TI C compiler ABI oracle for M6 task 1.
*
* The 1987 GSP C compiler is on the 1987-11-06 "Simulator-C Tools-ASM Tools"
* image (::/C2). Run it under DOSBox with the module name (no extension):
*
* gspcpp oracle.c
* gspcc oracle.c
* gspcg oracle.c
*
* ORACLE.ASM then shows the exact stack sequences reproduced in
* build/llvm-clean/TMS34010.md ("M6 state"):
* - _dadd/_dcall: GSP double argument order and the caller-allocated
* hidden return slot (the callee writes saved_STK-64/saved_STK-32);
* - _fadd: a float return uses the single word at saved_STK-32 (the K&R
* compiler promotes the parameters, so it calls FD$ADD + FD$DTOF);
* - _mkpair/_callpair: a 64-bit struct return uses the same hidden slot
* and the caller releases it with ADDI -64,STK;
* - _d2i/_i2d: the FD$DTOI/FD$ITOD conversion entries.
*
* The 1987 compiler is K&R-only; long long did not exist, so i64 has no
* external oracle. M6 i64 memory is little-endian (LSW at the lower
* address, per spec §4.1); the argument/hidden-slot order is MSW-first and
* is documented
* in TMS34010.md and pinned by scripts/m6/spike-probe.asm.
*/
double dadd(a, b)
double a;
double b;
{
return a + b;
}
double dcall(a, b)
double a;
double b;
{
double r;
r = dadd(a, b);
return r;
}
long d2i(a)
double a;
{
return (long)a;
}
double i2d(a)
long a;
{
return (double)a;
}
float fadd(a, b)
float a;
float b;
{
return a + b;
}
struct pair {
long a;
long b;
};
struct pair mkpair(a, b)
long a;
long b;
{
struct pair p;
p.a = a;
p.b = b;
return p;
}
long callpair(a, b)
long a;
long b;
{
struct pair p;
p = mkpair(a, b);
return p.a + p.b;
}
+91
View File
@@ -0,0 +1,91 @@
-- aggregate-check.lua -- read the M6 aggregate marker words and compare them
-- with the expected ABI/layout values.
--
-- AGGREGATE_MARKERS is the bit address of _aggregate_markers from the linker
-- map. Each marker is one 32-bit word at base + n*0x20 bits. The raw-object
-- markers pin the byte layout (little-endian, fields in ascending order) and
-- the guards prove an aggregate copy does not overrun the object.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("AGGREGATE_MARKERS"), 16)
local N = 49
local frames = 0
local checked = false
local expect = {
[0] = 0x11223344, [1] = 0x00005566, -- mk_six fields
[2] = 0x11223344, [3] = 0x00005566, -- raw six object word/half
[4] = 0x600D600D, -- guard after a 6-byte copy
[5] = 0xAABBCCDD, [6] = 0x0000005A, -- mk_five fields (5-byte object)
[7] = 0xAABBCCDD, [8] = 0x0000005A, -- raw five object word/byte
[9] = 0x000000A5, -- guard after a 5-byte copy
[10] = 0x00000010, [11] = 0x00000011, -- mk_big fields
[12] = 0x00000012, [13] = 0x00000013,
[14] = 0x00000014,
[15] = 0x00000010, [16] = 0x00000011, -- raw big object words
[17] = 0x00000012, [18] = 0x00000013,
[19] = 0x00000014,
[20] = 0xAAAA5555, [21] = 0x12345678, -- mk_pair (the 1987 _mkpair)
[22] = 0x00000100, [23] = 0x00000009, -- mk_outer nested fields
[24] = 0x00000003,
[25] = 0xDEADBEEF, [26] = 0xDEADBEEF, -- mk_uni field and raw word
[27] = 0x3366EF96, -- sum_six(six, 100)
[28] = 0x00000024, -- sum_big(big)
[29] = 0x12345678, -- sum_uni(uni)
[30] = 0x000000CF, -- c_usesix(50)
[31] = 0x00000018, -- c_usebig(10)
[32] = 0x00000405, -- c_useouter(0x200)
[33] = 0x0BADF00D, -- c_useuni(...)
[34] = 0x0000000B, -- c_sumpair({5,6})
[35] = 0x00000030, -- c_sumsix({0x10,0x20})
[36] = 0x112233C2, -- c_sumuni(l + c[5])
[37] = 0x000000D2, -- c_usemixed(100)
[38] = 0x00000064, -- mixed raw a
[39] = 0x00000064, -- mixed raw i64 LSW (little-endian)
[40] = 0x00000000, -- mixed raw i64 MSW
[41] = 0x00000000, -- mixed raw double LSW (GSP 1.5)
[42] = 0x400C0000, -- mixed raw double MSW
[43] = 0x40D00000, -- mixed raw float (GSP 2.5)
[44] = 0x00000007, -- mixed raw char
[45] = 0x000B1405, -- c_mkbits fields a=5 b=20 c=-5
[46] = 0xFFFFFFFB, -- signed int c:4 sign-extends
[47] = 0x00000BA5, -- raw packed bitfield word
[48] = 0x5A5A5A5A, -- marker after aggregate_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 aggregate:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 AGGREGATE MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 aggregate: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 AGGREGATE MAME: FAIL")
end
end
end, "aggregate-check")
+28
View File
@@ -0,0 +1,28 @@
; aggregate-entry.asm -- M6 aggregate gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver aggregate_run() and writes a post-return marker. aggregate.sh
; concatenates the llc output for m6-aggregate.ll and the compiled driver
; after this file, so _aggregate_run and the aggregate functions are in the
; same assembly.
;
; The marker array is in .bss (linked at the ram origin); aggregate-check.lua
; reads its address from the linker map and checks 49 words (markers 0..48,
; the last one written after aggregate_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _aggregate_run
movi 5A5A5A5Ah, a0
movi _aggregate_markers+1536, a2 ; marker 48, the post-return word
move a0, *a2, 1
rets
.globl _aggregate_markers
.bss _aggregate_markers, 1568, 16 ; 49 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+351
View File
@@ -0,0 +1,351 @@
/* M6 aggregate gate driver.
*
* Calls the hand-written ABI functions in m6-aggregate.ll through the TI
* aggregate rules and writes result words to the marker array defined by the
* entry assembly. The .ll callees are *not* compiled by Clang, so the driver
* pins the caller side against independently written lowering; the C
* functions below then exercise the compiler's own callee side (and its
* caller side calling itself).
*
* The ABI under test (1987 `_mkbig`/`_callbig`):
* - the caller reserves an alignTo(size, 2)-byte slot at the top of its
* frame before saving STK, pushes the arguments, calls;
* - the callee copies the object bytes to saved_STK-size (the object sits
* at the top of the rounded slot) and ends with LOADSTK + RETS 2;
* - the caller copies the bytes out and releases the slot;
* - struct/union arguments are still byval copies in the argument area;
* - no sret pointer argument and no A8 aggregate return.
*
* Marker word n lives at aggregate_markers[n], i.e. 0x20 bits above the
* previous one; scripts/m6/aggregate-check.lua reads them by bit address from
* the linker map.
*/
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef unsigned long long u64;
struct six {
int a;
short b;
};
struct five {
int a;
char b;
};
/* A packed bitfield struct returned by value: the Task 5 (bitfields) / Task 6
* (aggregate return) seam. The 12 field bits fit one 16-bit word, so the
* hidden slot is 2 bytes and the callee stores the packed bits directly. */
struct bits {
unsigned int a : 3;
unsigned int b : 5;
int c : 4;
};
struct big {
long a, b, c, d, e;
};
struct pair {
long a, b;
};
struct inner {
long a;
short b;
};
struct outer {
struct inner i;
long c;
};
union uni {
long l;
char c[6];
};
struct mixed {
long a;
long long b;
double d;
float f;
char c;
};
struct six_guard {
struct six s;
unsigned int guard;
};
struct five_guard {
struct five f;
unsigned char guard;
};
/* Layout contract: TI packs records, so a 5-byte object is possible and the
* 6-byte slot rounds it up by one byte. */
_Static_assert(sizeof(struct six) == 6, "six");
_Static_assert(__builtin_offsetof(struct six, b) == 4, "six.b");
_Static_assert(sizeof(struct bits) == 2, "bits");
_Static_assert(sizeof(struct five) == 5, "five");
_Static_assert(__builtin_offsetof(struct five, b) == 4, "five.b");
_Static_assert(sizeof(struct big) == 20, "big");
_Static_assert(sizeof(struct pair) == 8, "pair");
_Static_assert(sizeof(struct inner) == 6, "inner");
_Static_assert(sizeof(struct outer) == 10, "outer");
_Static_assert(__builtin_offsetof(struct outer, c) == 6, "outer.c");
_Static_assert(sizeof(union uni) == 6, "uni");
_Static_assert(sizeof(struct mixed) == 25, "mixed");
_Static_assert(__builtin_offsetof(struct mixed, b) == 4, "mixed.b");
_Static_assert(__builtin_offsetof(struct mixed, d) == 12, "mixed.d");
_Static_assert(__builtin_offsetof(struct mixed, f) == 20, "mixed.f");
_Static_assert(__builtin_offsetof(struct mixed, c) == 24, "mixed.c");
extern volatile u32 aggregate_markers[];
/* Callees defined in m6-aggregate.ll. */
extern struct six mk_six(int, int);
extern struct five mk_five(int, int);
extern struct big mk_big(int);
extern struct pair mk_pair(int, int);
extern struct outer mk_outer(int);
extern union uni mk_uni(int);
extern int sum_six(struct six, int);
extern int sum_big(struct big);
extern int sum_uni(union uni);
/* Keep raw object copies in .bss so the exact bytes can be inspected. */
static volatile struct six six_raw;
static volatile struct five five_raw;
static volatile struct big big_raw;
static volatile union uni uni_raw;
static volatile struct mixed mixed_raw;
static volatile struct six_guard six_guard_slot;
static volatile struct five_guard five_guard_slot;
static volatile struct bits bits_raw;
static void mark(u32 n, u32 v) { aggregate_markers[n] = v; }
/* --- C-side aggregate callees (the compiler's callee lowering) ----------- */
static __attribute__((noinline)) struct six c_mksix(int a, int b)
{
struct six s;
s.a = a;
s.b = (short)b;
return s;
}
static __attribute__((noinline)) int c_usesix(int x)
{
struct six s = c_mksix(x, 7);
return s.a * 3 + s.b + x;
}
/* The bitfield-struct return: fields come from x so the callee cannot fold
* the result, and the caller reads them back through the returned object.
* c uses the low bits only: a (x >> 8) & mask source would exercise an
* unrelated generic load-narrowing path on this bit-addressed target. */
static __attribute__((noinline)) struct bits c_mkbits(int x)
{
struct bits v;
v.a = x & 7;
v.b = (x >> 3) & 31;
v.c = -(x & 7);
return v;
}
static __attribute__((noinline)) struct big c_mkbig(int x)
{
struct big b;
b.a = x;
b.b = x + 1;
b.c = x + 2;
b.d = x + 3;
b.e = x + 4;
return b;
}
static __attribute__((noinline)) int c_usebig(int x)
{
struct big b = c_mkbig(x);
return b.a + b.e;
}
static __attribute__((noinline)) struct outer c_mkouter(int x)
{
struct outer o;
o.i.a = x;
o.i.b = 2;
o.c = x + 3;
return o;
}
static __attribute__((noinline)) int c_useouter(int x)
{
struct outer o = c_mkouter(x);
return o.i.a + o.i.b + o.c;
}
static __attribute__((noinline)) union uni c_mkuni(int x)
{
union uni u;
u.l = x;
return u;
}
static __attribute__((noinline)) int c_useuni(int x)
{
union uni u = c_mkuni(x);
return u.l;
}
static __attribute__((noinline)) struct mixed c_mkmixed(int x)
{
struct mixed m;
m.a = x;
m.b = x;
m.d = 1.5;
m.f = 2.5f;
m.c = 7;
return m;
}
static __attribute__((noinline)) int c_usemixed(int x)
{
struct mixed m = c_mkmixed(x);
return (long)m.a + (long)m.b + (long)m.d + (long)m.f + (long)m.c;
}
static __attribute__((noinline)) int c_sumpair(struct pair p) { return p.a + p.b; }
static __attribute__((noinline)) int c_sumsix(struct six s) { return s.a + s.b; }
static __attribute__((noinline)) int c_sumuni(union uni u) { return u.l + u.c[5]; }
void aggregate_run(void)
{
struct six s6;
struct five f5;
struct big b5;
struct pair p2;
struct outer o;
union uni u;
volatile u32 *w;
volatile u8 *pb;
/* The .ll 6-byte struct return and its raw memory image. */
s6 = mk_six(0x11223344, 0x5566);
mark(0, (u32)s6.a);
mark(1, (u16)s6.b);
six_raw = s6;
w = (volatile u32 *)&six_raw;
mark(2, w[0]);
pb = (volatile u8 *)&six_raw;
mark(3, pb[4] | ((u32)pb[5] << 8));
/* A 6-byte object must not overwrite the next object. */
six_guard_slot.guard = 0x600D600D;
six_guard_slot.s = mk_six(0x11223344, 0x5566);
mark(4, six_guard_slot.guard);
/* The 5-byte object in a 6-byte slot; the guard proves the copy is exact
* (the slot's pad byte is not written into the caller's object). */
f5 = mk_five(0xAABBCCDD, 0x5A);
mark(5, (u32)f5.a);
mark(6, (u8)f5.b);
five_raw = f5;
w = (volatile u32 *)&five_raw;
mark(7, w[0]);
pb = (volatile u8 *)&five_raw;
mark(8, pb[4]);
five_guard_slot.guard = 0xA5;
five_guard_slot.f = mk_five(0x01020304, 0x7E);
mark(9, five_guard_slot.guard);
/* The 5-word / 160-bit case. */
b5 = mk_big(0x10);
mark(10, (u32)b5.a);
mark(11, (u32)b5.b);
mark(12, (u32)b5.c);
mark(13, (u32)b5.d);
mark(14, (u32)b5.e);
big_raw = b5;
w = (volatile u32 *)&big_raw;
mark(15, w[0]);
mark(16, w[1]);
mark(17, w[2]);
mark(18, w[3]);
mark(19, w[4]);
/* The 2-word case (1987 `_mkpair`). */
p2 = mk_pair(0xAAAA5555, 0x12345678);
mark(20, (u32)p2.a);
mark(21, (u32)p2.b);
/* Nested struct: flattened fields at 0, 4 and 6. */
o = mk_outer(0x100);
mark(22, (u32)o.i.a);
mark(23, (u32)o.i.b);
mark(24, (u32)o.c);
/* Union return and its raw low word. */
u = mk_uni(0xDEADBEEF);
mark(25, (u32)u.l);
uni_raw = u;
w = (volatile u32 *)&uni_raw;
mark(26, w[0]);
/* Struct/union by value as arguments: the callee receives a private copy
* in the argument area (the driver is the caller here). */
mark(27, (u32)sum_six(s6, 100));
mark(28, (u32)sum_big(b5));
mark(29, (u32)sum_uni(mk_uni(0x12345678)));
/* C-defined callees (the compiler's own callee lowering), called from C. */
mark(30, (u32)c_usesix(50));
mark(31, (u32)c_usebig(10));
mark(32, (u32)c_useouter(0x200));
mark(33, (u32)c_useuni(0x0BADF00D));
p2.a = 5;
p2.b = 6;
mark(34, (u32)c_sumpair(p2));
s6.a = 0x10;
s6.b = 0x20;
mark(35, (u32)c_sumsix(s6));
u.l = 0x11223344;
u.c[5] = 0x7E;
mark(36, (u32)c_sumuni(u));
/* The aggregate can mix i64, double and float members. */
mark(37, (u32)c_usemixed(100));
mixed_raw = c_mkmixed(100);
w = (volatile u32 *)&mixed_raw;
mark(38, w[0]);
mark(39, w[1]);
mark(40, w[2]);
mark(41, w[3]);
mark(42, w[4]);
mark(43, w[5]);
pb = (volatile u8 *)&mixed_raw;
mark(44, pb[24]);
/* Packed bitfield struct returned by value (Task 5/6 seam): fields, the
* signed field and the raw packed word. c_mkbits(0x1A5) is a=5, b=20,
* c=-5 in one 16-bit word. */
{
struct bits v = c_mkbits(0x1A5);
volatile u8 *bb;
mark(45, (u32)v.a | ((u32)v.b << 8) |
((u32)(v.c & 0xF) << 16));
mark(46, (u32)v.c);
bits_raw = v;
bb = (volatile u8 *)&bits_raw;
mark(47, (u32)bb[0] | ((u32)bb[1] << 8));
}
}
+116
View File
@@ -0,0 +1,116 @@
-- bitfield-check.lua -- read the M6 bitfield marker words and compare them
-- with the oracle's expected values.
--
-- BITFIELD_MARKERS is the bit address of _bitfield_markers from the linker
-- map; each marker is one 32-bit word at base + n*0x20 bits. The struct
-- case is the Task 5 oracle: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32,
-- and the raw word0/byte4 markers pin the actual storage bytes, not just the
-- compiled read-back.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("BITFIELD_MARKERS"), 16)
local N = 62
local frames = 0
local checked = false
local expect = {
[0] = 5, -- struct s.a (bits 0..2)
[1] = 21, -- struct s.b (bits 3..7)
[2] = 0xFFFFFFFD, -- struct s.c = -3, signed 4-bit
[3] = 0x000ABCDE, -- struct s.d (bits 12..31)
[4] = 9, -- struct s.e (bits 32..35)
[5] = 0xABCDEDAD, -- raw word0 = a|b<<3|c<<8|d<<12
[6] = 0x09, -- raw byte4 low nibble = e
[7] = 7, -- c = +7
[8] = 0xFFFFFFF8, -- c = -8 (the 4-bit minimum)
[9] = 0x000FEDCB, -- cross.x
[10] = 0x00012345, -- cross.y at bit 20, crossing bit 32
[11] = 0x345FEDCB, -- raw word0: x | (y low 12) << 20
[12] = 0x12, -- raw byte4: y high 8 bits
[13] = 3, -- zw.a
[14] = 17, -- zw.b after the ignored :0 (bit 3)
[15] = 0x8B, -- raw byte = 3 | 17 << 3
[16] = 0xFFFFFFFF, -- one.s = -1 (signed 1-bit)
[17] = 1, -- one.u
[18] = 0x03, -- raw byte: s in bit 0, u in bit 1
[19] = 0, -- one.s = 0
[20] = 1, -- one.u = 1
[21] = 0x02, -- raw byte
[22] = 0xFFFFFFFF, -- one.s = -1
[23] = 0, -- one.u = 0
[24] = 0x01, -- raw byte
[25] = 0xDEADBEEF, -- word.w (full 32-bit field)
[26] = 1, -- word.v at bit 32
[27] = 0xDEADBEEF, -- raw word0
[28] = 0x01, -- raw byte4
[29] = 0x01234567, -- edge.p (28 bits)
[30] = 0xA5, -- edge.q at bit 28, crossing bit 32
[31] = 0x0C, -- edge.r at bit 36
[32] = 0x51234567, -- raw word0: p | (q low nibble) << 28
[33] = 0xCA, -- raw byte4: q high nibble | r << 4
[34] = 0xFFFFFFFD, -- sx.a = -3 (signed 3-bit)
[35] = 2, -- sx.b
[36] = 0xFFFFFF38, -- sx.c = -200 (signed 9-bit)
[37] = 0xFFFE0000, -- sx.d = -131072 (signed 18-bit)
[38] = 0x80002715, -- raw word0 of the packed signed fields
[39] = 0xFA0A1F00, -- sy.e = -100000000 (signed 30-bit)
[40] = 0xFFFFFFEC, -- sy.f = -20 (signed 6-bit, crosses bit 32)
[41] = 0x3A0A1F00, -- raw word0
[42] = 0x0B, -- raw byte4: f high nibble
[43] = 1, -- g2.a through a pointer
[44] = 30, -- g2.b
[45] = 0xFFFFFFFE, -- g2.c = -2
[46] = 0x00054321, -- g2.d
[47] = 15, -- g2.e
[48] = 0x54321EF1, -- g2 raw word0
[49] = 0x0F, -- g2 raw byte4
[50] = 6, -- lz.a (leading :0 ignored)
[51] = 9, -- lz.b at bit 3
[52] = 0x4E, -- raw byte = 6 | 9 << 3
[53] = 0x12345678, -- l64.f = 0x12345678 (bit 33)
[54] = 0x00000000, -- l64 raw word0 (pad)
[55] = 0x2468ACF0, -- l64 raw word1 (pad[32] | f<<1)
[56] = 0x89ABCDEF, -- q64.q low word
[57] = 0x89ABCDEF, -- q64 raw word0 (LSW)
[58] = 0x01234567, -- q64 raw word1 (MSW)
[59] = 0x12345678, -- copy_l64 read-back after an aggregate copy
[60] = 0x2468ACF0, -- copied l64 raw MSW
[61] = 0x5A5A5A5A, -- marker after bitfield_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 bitfield:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 BITFIELD MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 bitfield: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 BITFIELD MAME: FAIL")
end
end
end, "bitfield-check")
+27
View File
@@ -0,0 +1,27 @@
; bitfield-entry.asm -- M6 bitfield gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver bitfield_run() and writes a post-return marker. bitfield.sh
; concatenates the compiled driver after this file, so _bitfield_run and its
; helpers are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); bitfield-check.lua
; reads its address from the linker map and checks 62 words (markers 0..61,
; the last one written after bitfield_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _bitfield_run
movi 5A5A5A5Ah, a0
movi _bitfield_markers+1952, a2 ; marker 61, the post-return word
move a0, *a2, 1
rets
.globl _bitfield_markers
.bss _bitfield_markers, 2048, 16 ; 62 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+255
View File
@@ -0,0 +1,255 @@
/* M6 bitfield gate driver.
*
* Every struct below is the 1987 GSP C compiler's packed bitfield layout:
* bitfields are allocated LSB-first at the next free bit, with no padding
* between adjacent fields and across the 32-bit word boundary; an unnamed
* `:0` bitfield is ignored (the oracle's `b` after `a:3; :0` is at bit 3).
* Clang's record layout for the target must agree; the _Static_asserts check
* the byte-expressible part (sizeof/alignof) and the runtime markers check
* the bit offsets by setting each field to a known value, reading it back and
* checking the raw storage bytes.
*
* The structs are volatile so the accesses survive -O2; the marker array is
* volatile too. Marker word n lives at bitfield_markers[n], i.e. 0x20 bits
* above the previous one; scripts/m6/bitfield-check.lua reads them from the
* linker map.
*
* Raw storage is read little-endian (the target's data layout is `e`): byte 0
* holds struct bits 0..7. The 1987 oracle's `g` is `.bss _g,36,16`, and the
* object allocator rounds that to 48 bits; the M6 .bss emitter rounds every
* object to a 16-bit unit, so a standalone object matches. Arrays, nested
* members and pointer arithmetic on a struct whose content is not a whole
* byte are the documented divergence:
* TI strides by the 36-bit content, Clang by the byte-rounded 5-byte sizeof.
*/
typedef unsigned int u32;
/* The oracle struct from the Task 5 notes (BITS.C). */
struct s {
unsigned a:3;
unsigned b:5;
int c:4;
unsigned d:20;
unsigned e:4;
};
struct cross { unsigned x:20; unsigned y:20; };
struct zw { unsigned a:3; unsigned :0; unsigned b:5; };
struct one { int s:1; unsigned u:1; };
struct word { unsigned w:32; unsigned v:1; };
struct edge { unsigned p:28; unsigned q:8; unsigned r:4; };
struct sx { int a:3; unsigned b:2; int c:9; int d:18; };
struct sy { int e:30; int f:6; };
struct lz { unsigned :0; unsigned a:3; unsigned b:5; };
/* A 31-bit field at bit 33 needs an i64 container (LSB-first). */
struct l64 { unsigned long long pad:33; unsigned f:31; };
struct q64 { unsigned long long q:57; };
volatile struct s g;
volatile struct s g2;
volatile struct cross cg;
volatile struct zw zg;
volatile struct one og;
volatile struct word wg;
volatile struct edge eg;
volatile struct sx sx;
volatile struct sy sy;
volatile struct lz lz;
volatile struct l64 l64g;
volatile struct l64 l64h;
volatile struct q64 q64g;
extern volatile u32 bitfield_markers[];
/* The oracle's sizeof values: 36 bits -> 5 bytes, 40 -> 5, 8 -> 1, 2 -> 1,
* 33 -> 5. TI reports the byte-rounded size; Clang must agree. */
_Static_assert(sizeof(struct s) == 5, "oracle sizeof(struct s)");
_Static_assert(sizeof(struct cross) == 5, "cross is a whole 40-bit word pair");
_Static_assert(sizeof(struct zw) == 1, "the :0 is ignored; a+b is 8 bits");
_Static_assert(sizeof(struct one) == 1, "two 1-bit fields fit one byte");
_Static_assert(sizeof(struct word) == 5, "32+1 bits round to 5 bytes");
_Static_assert(sizeof(struct edge) == 5, "28+8+4 bits = 40");
_Static_assert(sizeof(struct sx) == 4, "3+2+9+18 bits = 32");
_Static_assert(sizeof(struct sy) == 5, "30+6 bits = 36, rounded to 5 bytes");
_Static_assert(sizeof(struct lz) == 1, "leading :0 is ignored");
_Static_assert(sizeof(struct l64) == 8, "33+31 bits = 64");
_Static_assert(sizeof(struct q64) == 8, "57 bits round to 8 bytes");
_Static_assert(_Alignof(struct s) == 1, "packed record alignment is 1 byte");
static u32 raw_byte(volatile void *p, int i)
{
return ((volatile unsigned char *)p)[i];
}
static u32 raw_word0(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[0] | ((u32)b[1] << 8) | ((u32)b[2] << 16) |
((u32)b[3] << 24);
}
static u32 raw_word1(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[4] | ((u32)b[5] << 8) | ((u32)b[6] << 16) |
((u32)b[7] << 24);
}
static void set_l64(unsigned f) { l64g.f = f; }
static unsigned get_l64(void) { return l64g.f; }
static void set_q64(unsigned long long q) { q64g.q = q; }
static unsigned long long get_q64(void) { return q64g.q; }
/* An aggregate copy: at -O2 the optimizer may forward the i64 copy
* into the field read, so the memory order must match the IR. */
static unsigned copy_l64(struct l64 *dst, struct l64 *src)
{
*dst = *src;
return dst->f;
}
void bitfield_run(void)
{
volatile struct s *gp = &g2;
/* The oracle struct: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32.
* Expected bytes: AD ED CD AB 09 (word0 ABCDEDADh, then e in byte 4). */
g.a = 5;
g.b = 21;
g.c = -3;
g.d = 0xABCDE;
g.e = 9;
bitfield_markers[0] = g.a;
bitfield_markers[1] = g.b;
bitfield_markers[2] = (u32)g.c;
bitfield_markers[3] = g.d;
bitfield_markers[4] = g.e;
bitfield_markers[5] = raw_word0((volatile void *)&g);
bitfield_markers[6] = raw_byte((volatile void *)&g, 4);
/* Signed nibble boundaries: +7 and the minimum -8 must sign-extend. */
g.c = 7;
bitfield_markers[7] = (u32)g.c;
g.c = -8;
bitfield_markers[8] = (u32)g.c;
/* struct cross: y:20 at bit 20 crosses bit 32.
* word0 345FEDCBh, byte4 12h. */
cg.x = 0xFEDCB;
cg.y = 0x12345;
bitfield_markers[9] = cg.x;
bitfield_markers[10] = cg.y;
bitfield_markers[11] = raw_word0((volatile void *)&cg);
bitfield_markers[12] = raw_byte((volatile void *)&cg, 4);
/* struct zw: a:3, unnamed :0 ignored, b:5 at bit 3.
* byte 8Bh (a=3 in bits 0..2, b=17 in bits 3..7). */
zg.a = 3;
zg.b = 17;
bitfield_markers[13] = zg.a;
bitfield_markers[14] = zg.b;
bitfield_markers[15] = raw_byte((volatile void *)&zg, 0);
/* struct one: the signed 1-bit field is the SEXT1 case (SLL 31/SRA 31).
* A 1-bit signed field holds 0 or -1: s=-1,u=1 -> byte 3; s=0,u=1 ->
* byte 2; s=-1,u=0 -> byte 1. */
og.s = -1;
og.u = 1;
bitfield_markers[16] = (u32)og.s;
bitfield_markers[17] = og.u;
bitfield_markers[18] = raw_byte((volatile void *)&og, 0);
og.s = 0;
og.u = 1;
bitfield_markers[19] = (u32)og.s;
bitfield_markers[20] = og.u;
bitfield_markers[21] = raw_byte((volatile void *)&og, 0);
og.s = -1;
og.u = 0;
bitfield_markers[22] = (u32)og.s;
bitfield_markers[23] = og.u;
bitfield_markers[24] = raw_byte((volatile void *)&og, 0);
/* struct word: w:32 at bit 0 (a full-word field) and v:1 at bit 32. */
wg.w = 0xDEADBEEF;
wg.v = 1;
bitfield_markers[25] = wg.w;
bitfield_markers[26] = wg.v;
bitfield_markers[27] = raw_word0((volatile void *)&wg);
bitfield_markers[28] = raw_byte((volatile void *)&wg, 4);
/* struct edge: q:8 at bit 28 crosses bit 32 (low nibble in word0 bits
* 28..31, high nibble in byte4 bits 0..3); r:4 at bit 36.
* word0 51234567h, byte4 CAh. */
eg.p = 0x1234567;
eg.q = 0xA5;
eg.r = 0xC;
bitfield_markers[29] = eg.p;
bitfield_markers[30] = eg.q;
bitfield_markers[31] = eg.r;
bitfield_markers[32] = raw_word0((volatile void *)&eg);
bitfield_markers[33] = raw_byte((volatile void *)&eg, 4);
/* Signed fields at odd offsets inside one 32-bit word:
* a:3@0, b:2@3, c:9@5, d:18@14; word0 80002715h. */
sx.a = -3;
sx.b = 2;
sx.c = -200;
sx.d = -131072;
bitfield_markers[34] = (u32)sx.a;
bitfield_markers[35] = sx.b;
bitfield_markers[36] = (u32)sx.c;
bitfield_markers[37] = (u32)sx.d;
bitfield_markers[38] = raw_word0((volatile void *)&sx);
/* A signed field crossing the word boundary: e:30@0, f:6@30.
* e=-100000000 (-100000000 & 3FFFFFFF = 3A0A1F00h), f=-20 (2Ch: low
* two bits 0 in word0 bits 30..31, high nibble Bh in byte4 bits 0..3). */
sy.e = -100000000;
sy.f = -20;
bitfield_markers[39] = (u32)sy.e;
bitfield_markers[40] = (u32)sy.f;
bitfield_markers[41] = raw_word0((volatile void *)&sy);
bitfield_markers[42] = raw_byte((volatile void *)&sy, 4);
/* The same oracle struct through a pointer, so the access path is a
* GEP/load/store rather than a fixed global address.
* word0 54321EF1h, byte4 0Fh. */
gp->a = 1;
gp->b = 30;
gp->c = -2;
gp->d = 0x54321;
gp->e = 15;
bitfield_markers[43] = gp->a;
bitfield_markers[44] = gp->b;
bitfield_markers[45] = (u32)gp->c;
bitfield_markers[46] = gp->d;
bitfield_markers[47] = gp->e;
bitfield_markers[48] = raw_word0((volatile void *)&g2);
bitfield_markers[49] = raw_byte((volatile void *)&g2, 4);
/* A leading unnamed :0 is ignored too: a:3@0, b:5@3, byte 4Eh. */
lz.a = 6;
lz.b = 9;
bitfield_markers[50] = lz.a;
bitfield_markers[51] = lz.b;
bitfield_markers[52] = raw_byte((volatile void *)&lz, 0);
/* 64-bit containers: LSW at the lower address. f@33, 31 bits;
* raw word0 = pad[0..31], raw word1 = pad[32] | f << 1. */
set_l64(0x12345678u);
bitfield_markers[53] = get_l64();
bitfield_markers[54] = raw_word0((volatile void *)&l64g);
bitfield_markers[55] = raw_word1((volatile void *)&l64g);
/* 57-bit field: LSW = q[0..31], MSW = q[32..56]. */
set_q64(0x0123456789ABCDEFull);
bitfield_markers[56] = (u32)get_q64();
bitfield_markers[57] = raw_word0((volatile void *)&q64g);
bitfield_markers[58] = raw_word1((volatile void *)&q64g);
/* Aggregate copy: GVN may forward the i64 copy into the field read at
* -O2, so the memory order must match the IR. (A constant-initialized
* i64 aggregate still hits the pre-existing M2 .data limitation at -O0.) */
bitfield_markers[59] = copy_l64(&l64h, &l64g);
bitfield_markers[60] = raw_word1((volatile void *)&l64h);
}
+183
View File
@@ -0,0 +1,183 @@
#!/bin/sh
# Extract and validate the 1990-11 TMS340 Family SDK floating-point/runtime
# libraries for the M6 ABI work.
#
# scripts/m6/flib-extract.sh
#
# The 1990 r5.01 Code Generation Tools are OS/2 1.x NE binaries and do not run
# under DOSBox, but their TI-COFF libraries are ordinary ar archives. The 1987
# GSPA 2.00/GSPLNK 2.00 tools assemble and link them unchanged, `$` symbols
# included.
#
# Outputs (all under build/m6-sdk, which is git-ignored):
# flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src
# flib-members/ rts-members/ extracted archive members
# flib-symbols.txt exact external definitions
#
# Overridable: M6_SDK_OUT
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OUT=${M6_SDK_OUT:-$ROOT/build/m6-sdk}
ZIPDIR="$ROOT/vendor/vt1200/tools/tms34010-sdk/1990-11 TMS340 Family SDK"
ZIP1="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip"
ZIP2="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (2 of 2) r5.01 rev2564062-1641.zip"
fail() {
echo "m6 flib-extract: FAIL: $*" >&2
exit 1
}
command -v unzip >/dev/null 2>&1 || fail "unzip is required"
command -v ar >/dev/null 2>&1 || fail "ar is required"
mkdir -p "$OUT"
if [ ! -f "$OUT/flib.lib" ] || [ ! -f "$OUT/rts.lib" ]; then
[ -f "$ZIP2" ] || fail "1990 SDK archive not found: $ZIP2"
unzip -o -q "$ZIP2" -d "$OUT"
# The tool archives are not needed to link (the 1987 tools are used), but
# extracting them records the exact 1990 release the libraries came from.
if [ -f "$ZIP1" ]; then
unzip -o -q "$ZIP1" -d "$OUT"
fi
fi
for f in flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src; do
[ -f "$OUT/$f" ] || fail "missing $OUT/$f after extraction"
done
extract_members() {
lib=$1
dir=$OUT/$2
rm -rf "$dir"
mkdir -p "$dir"
(cd "$dir" && ar x "$OUT/$lib")
chmod -R u+rw "$dir"
}
extract_members flib.lib flib-members
extract_members flibc.lib flibc-members
extract_members flibi.lib flibi-members
extract_members rts.lib rts-members
python3 - "$ROOT" "$OUT" <<'PY'
import os
import struct
import sys
root, out = sys.argv[1], sys.argv[2]
sys.path.insert(0, os.path.join(root, "vendor", "vt1200", "dwt", "loader"))
import coff
def symname(c, sym):
"""Return a TI-COFF symbol name, resolving the long-name string table."""
d = c["data"]
raw = d[c["symptr"] + sym["index"] * 18:][:8]
if raw[:4] == b"\0\0\0\0":
off = struct.unpack_from("<I", raw, 4)[0]
base = c["symptr"] + c["nsyms"] * 18
end = d.index(b"\0", base + off)
return d[base + off:end].decode("latin1")
return raw.rstrip(b"\0").decode("latin1")
lines = [
"# 1990-11 TMS340 Family SDK r5.01 external symbol definitions",
"# generated by scripts/m6/flib-extract.sh; do not edit",
"#",
"# flib.lib is the GSP-format floating-point library used by the TI C",
"# compiler by default. flibc.lib/flibi.lib are identified as the",
"# 34082/IEEE variants from member-code inspection (see the variant",
"# section at the end); the 1990 compiler was not run. M6 links flib.lib.",
"",
]
for lib, members in (("flib.lib", "flib-members"), ("rts.lib", "rts-members")):
lines.append("== %s" % lib)
d = os.path.join(out, members)
for fn in sorted(os.listdir(d)):
c = coff.parse(os.path.join(d, fn))
ext = [symname(c, s) for s in c["symbols"]
if s["sclass"] == 2 and s["secno"] > 0]
if ext:
lines.append("%-14s %s" % (fn, " ".join(ext)))
lines.append("")
def text_bits(c):
for s in c["sections"]:
if s["name"] == ".text":
return s["size"]
return 0
lines.append("== variant inspection (not linked by M6)")
for lib, members in (("flib.lib", "flib-members"),
("flibc.lib", "flibc-members"),
("flibi.lib", "flibi-members")):
parts = []
for fn in ("fs_add.obj", "fd_add.obj"):
c = coff.parse(os.path.join(out, members, fn))
parts.append("%s .text %d bits" % (fn, text_bits(c)))
lines.append("%-11s %s" % (lib, "; ".join(parts)))
lines.extend([
"# flibc/flibi are identified as the 34082/IEEE variants from member-code",
"# inspection (their members begin with the 34082 path and are larger) and",
"# release naming, not by running the OS/2-only 1990 compiler. M6 links",
"# flib.lib only.",
"",
])
text = "\n".join(lines) + "\n"
with open(os.path.join(out, "flib-symbols.txt"), "w") as f:
f.write(text)
sys.stdout.write(text)
PY
# The exact entries M6 tasks 2/3/6 depend on. If a name is missing the ABI
# contract in TMS34010.md/README.md is stale, so fail loudly.
for sym in \
'FS$ADD' 'FS$SUB' 'FS$SUB_R' 'FS$MUL' 'FS$DIV' 'FS$DIV_R' 'FS$NEG' \
'FS$EQ' 'FS$NE' 'FS$LT' 'FS$LE' 'FS$GT' 'FS$GE' 'FS$ZERO' 'FS$INC' \
'FS$INCR' 'FS$DEC' 'FS$DECR' \
'FD$ADD' 'FD$SUB' 'FD$SUB_R' 'FD$MUL' 'FD$DIV' 'FD$DIV_R' 'FD$NEG' \
'FD$EQ' 'FD$NE' 'FD$LT' 'FD$LE' 'FD$GT' 'FD$GE' 'FD$ZERO' 'FD$INC' \
'FD$INCR' 'FD$DEC' 'FD$DECR' \
'FD$DTOF' 'FD$FTOD' 'FD$FTOI' 'FD$FTOU' 'FD$DTOI' 'FD$DTOU' \
'FD$ITOF' 'FD$ITOD' 'FD$UTOF' 'FD$UTOD'
do
grep -Fq " $sym" "$OUT/flib-symbols.txt" \
|| fail "expected flib symbol $sym is missing"
done
# rts.lib is the C runtime, not a 64-bit arithmetic source: M6 task 2 must use
# target sequences, not invented helpers. Record that fact as a checked one.
if grep -Eiq '(^| )(__ll|_ll|llmul|lldiv|lladd|llsub|\$ll|\$i64|__i64)' "$OUT/flib-symbols.txt"; then
fail "unexpected 64-bit helper in flib/rts symbol list; re-check the ABI note"
fi
cat > "$OUT/m6-abi.txt" <<EOF
flib ABI (from flib.src and the 1987 C compiler output):
* arithmetic: operands are pushed on A14, first operand first, second last;
the result is pushed on A14 (one word for FS\$, two for FD\$);
* compares: both operands are popped from A14; the boolean is in A8
(1 true, 0 false); nothing is pushed;
* conversions: FD\$FTOI/FTOU and FD\$DTOI/DTOU pop the float/double from A14
and return the integer in A8; FD\$ITOF/UTOF and FD\$ITOD/UTOD take the
integer in A8 and push one float / two double words on A14;
FD\$FTOD pops a float and pushes two double words, FD\$DTOF pops a double
and pushes one float word;
* flib routines end in RETS (not RETS 2): pop the pushed result (if any),
then restore the caller A14 from the old-STK word saved on the system
stack;
* flib.lib uses the GSP floating format: 1.5 = 40600000h (float) and
00000000h/400C0000h (double, LSW at the lower address);
* float arguments are one 32-bit slot (ANSI/FS\$ rule; the 1987 K&R oracle
promotes float parameters to double, so it does not pin this slot).
link line:
GSPLNK -l flib.lib -l rts.lib (scripts/m6/link.cmd)
symbol list: $OUT/flib-symbols.txt
EOF
cat "$OUT/m6-abi.txt"
+139
View File
@@ -0,0 +1,139 @@
# 1990-11 TMS340 Family SDK r5.01 external symbol definitions
# generated by scripts/m6/flib-extract.sh; do not edit
#
# flib.lib is the GSP-format floating-point library used by the TI C
# compiler by default. flibc.lib/flibi.lib are identified as the
# 34082/IEEE variants from member-code inspection (see the variant
# section at the end); the 1990 compiler was not run. M6 links flib.lib.
== flib.lib
fc_dtof.obj FD$DTOF
fc_dtoi.obj FD$DTOI
fc_dtou.obj FD$DTOU
fc_ftod.obj FD$FTOD
fc_ftoi.obj FD$FTOI
fc_ftou.obj FD$FTOU
fc_itod.obj FD$ITOD
fc_itof.obj FD$ITOF
fc_utod.obj FD$UTOD
fc_utof.obj FD$UTOF
fd_add.obj FD$ADD FD$SUB_R FD$SUB
fd_cmp.obj FD$GE FD$LE FD$GT FD$LT
fd_decr.obj FD$DECR FD$DEC
fd_div.obj FD$DIV_R FD$DIV
fd_eq.obj FD$EQ
fd_error.obj _fp_error
fd_incr.obj FD$INCR FD$INC
fd_mul.obj FD$MUL
fd_ne.obj FD$NE
fd_neg.obj FD$NEG
fd_zero.obj FD$ZERO
fs_add.obj FS$SUB_R FS$ADD FS$SUB
fs_decr.obj FS$DECR FS$DEC
fs_div.obj FS$DIV FS$DIV_R
fs_eq.obj FS$EQ
fs_ge.obj FS$GE
fs_gt.obj FS$GT
fs_incr.obj FS$INC FS$INCR
fs_le.obj FS$LE
fs_lt.obj FS$LT
fs_mul.obj FS$MUL
fs_ne.obj FS$NE
fs_neg.obj FS$NEG
fs_zero.obj FS$ZERO
== rts.lib
abs.obj _labs _abs
asctime.obj _asctime
asin.obj _acos _asin
atan.obj _atan2 _atan
atof.obj _atof
atoi.obj _atoi _atol
boot.obj _c_int00 __present82
bsearch.obj _bsearch
check82.obj _check82
clock.obj _clock
ctime.obj _ctime
ctype.obj __ctypes_
difftime.obj _difftime
div.obj _div _ldiv
dtos.obj _dtos
ecvt.obj _ecvt
errno.obj _errno
exit.obj _abort _exit _atexit
exp.obj _exp
fabs.obj _fabs
fconvert.obj _fconvert
fcvt.obj _fcvt
floor.obj _ceil _floor
fmod.obj _fmod
frexp.obj _frexp
gmtime.obj _gmtime
isalnum.obj _isalnum
isalpha.obj _isalpha
isascii.obj _isascii
iscntrl.obj _iscntrl
isdigit.obj _isdigit
isgraph.obj _isgraph
islower.obj _islower
isprint.obj _isprint
ispunct.obj _ispunct
isspace.obj _isspace
isupper.obj _isupper
isxdigit.obj _isxdigit
ldexp.obj _ldexp
localtim.obj _localtime
log.obj _log _log10
ltoa.obj _ltoa
memchr.obj _memchr
memcmp.obj _memcmp
memmov.obj _memmove _memcpy
memory.obj _minit _malloc _realloc _free _calloc
memset.obj _memset
mktime.obj _mktime
modf.obj _modf
pow.obj _pow
qsort.obj _qsort
rand.obj _srand _rand
scheck.obj s$check
setjmp.obj _longjmp __setjmp _setjmp
sin.obj _cos _sin
sinh.obj _sinh _cosh
sqrt.obj _sqrt
strcat.obj _strcat
strchr.obj _strchr
strcmp.obj _strcmp
strcoll.obj _strcoll
strcpy.obj _strcpy
strcspn.obj _strcspn
strerror.obj _strerror
strftime.obj _strftime
strlen.obj _strlen
strncat.obj _strncat
strncmp.obj _strncmp
strncpy.obj _strncpy
strpbrk.obj _strpbrk
strrchr.obj _strrchr
strspn.obj _strspn
strstr.obj _strstr
strtod.obj _strtod
strtok.obj _strtok
strtol.obj _strtol
strtoul.obj _strtoul
strxfrm.obj _strxfrm
tan.obj _tan
tanh.obj _tanh
time.obj _time
toascii.obj _toascii
tolower.obj _tolower
toupper.obj _toupper
== variant inspection (not linked by M6)
flib.lib fs_add.obj .text 2384 bits; fd_add.obj .text 3728 bits
flibc.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
flibi.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
# flibc/flibi are identified as the 34082/IEEE variants from member-code
# inspection (their members begin with the 34082 path and are larger) and
# release naming, not by running the OS/2-only 1990 compiler. M6 links
# flib.lib only.
+114
View File
@@ -0,0 +1,114 @@
-- float-check.lua -- read the M6 float/double marker words and compare them
-- with the expected GSP bit patterns.
--
-- FLOAT_MARKERS is the bit address of _float_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. Doubles are pairs: LSW
-- first (the lower address), MSW second, which is also the GSP memory order.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("FLOAT_MARKERS"), 16)
local N = 80
local frames = 0
local checked = false
local expect = {
[0] = 0x41400000, -- fadd(1.5,2.5) = 4.0
[1] = 0x40400000, -- fsub(2.5,1.5) = 1.0
[2] = 0xC0400000, -- fsub(1.5,2.5) = -1.0
[3] = 0x41C00000, -- fmul(4.0,2.0) = 8.0
[4] = 0x40C00000, -- fdiv(4.0,2.0) = 2.0
[5] = 0xC0600000, -- fneg(1.5) = -1.5
[6] = 0x41400000, -- C body float_add(1.5,2.5)
[7] = 0x40600000, -- C float_ret() = 1.5
[8] = 0x00000000, [9] = 0x40280000, -- dadd(1.5,2.5) = 4.0
[10] = 0x00000000, [11] = 0x40080000, -- dsub(2.5,1.5) = 1.0
[12] = 0x00000000, [13] = 0xC0080000, -- dsub(1.5,2.5) = -1.0
[14] = 0x00000000, [15] = 0x40380000, -- dmul(4.0,2.0) = 8.0
[16] = 0x00000000, [17] = 0x40180000, -- ddiv(4.0,2.0) = 2.0
[18] = 0x00000000, [19] = 0xC00C0000, -- dneg(1.5) = -1.5
[20] = 0x00000000, [21] = 0x40280000, -- C double_add(1.5,2.5) = 4.0
[22] = 0x00000000, [23] = 0x401A0000, -- C double_ret() = 2.5
[24] = 1, -- fcmpeq(1.5,1.5)
[25] = 0, -- fcmpeq(1.5,2.5)
[26] = 1, -- fcmplt(1.5,2.5)
[27] = 0, -- fcmplt(2.5,1.5)
[28] = 1, -- fcmple(2.5,2.5)
[29] = 1, -- fcmpgt(2.5,1.5)
[30] = 0, -- fcmpge(1.5,2.5)
[31] = 1, -- fcmpne(1.5,2.5)
[32] = 0, -- fcmpne(1.5,1.5)
[33] = 1, -- dcmplt(1.5,2.5)
[34] = 0, -- dcmplt(2.5,1.5)
[35] = 1, -- dcmpeq(2.5,2.5)
[36] = 2, -- ftoi(2.5)
[37] = 0xFFFFFFFF, -- ftoi(-1.5) = -1
[38] = 3, -- ftou(3.9)
[39] = 2, -- dtoi(2.5)
[40] = 3, -- dtou(3.9)
[41] = 0x41700000, -- itof(7) = 7.0
[42] = 0x41700000, -- utof(7) = 7.0
[43] = 0xC0E00000, -- itof(-3) = -3.0
[44] = 0x00000000, [45] = 0x402E0000, -- itod(7) = 7.0
[46] = 0x00000000, [47] = 0x402E0000, -- utod(7) = 7.0
[48] = 0x00000000, [49] = 0x400C0000, -- ftod(1.5f) = 1.5
[50] = 0x40D00000, -- dtof(2.5) = 2.5
[51] = 0x41700000, -- constant 7.0f
[52] = 0xC0E00000, -- constant -3.0f
[53] = 0x00000000, [54] = 0x402E0000, -- constant 7.0
[55] = 0x00000000, [56] = 0xC01C0000, -- constant -3.0
[57] = 1, -- fcmpge(2.5,2.5)
[58] = 0, -- fcmpgt(1.5,1.5)
[59] = 0xFFFFFFFF, -- dtoi(-1.5) = -1
[60] = 0, -- fcmple(2.5,1.5)
[61] = 0, -- dcmpeq(1.5,2.5)
[62] = 11, -- fb_lt(1.5,2.5) true path
[63] = 22, -- fb_lt(2.5,1.5) false path
[64] = 33, -- db_lt(1.5,2.5) true path
[65] = 44, -- db_lt(2.5,1.5) false path
[66] = 3, -- fcount_lt(1.5,4.0): 1.5,2.5,3.5
[67] = 0x00000000, [68] = 0x400C0000, -- dsel_i(1,1.5,2.5) = 1.5
[69] = 0x00000000, [70] = 0x401A0000, -- dsel_i(0,1.5,2.5) = 2.5
[71] = 0x00000000, [72] = 0x40280000, -- dsel_f(<,4.0,8.0) = 4.0
[73] = 0x00000000, [74] = 0x40380000, -- dsel_f(>,4.0,8.0) = 8.0
[75] = 0x00000000, -- fnegzero(): GSP canonicalises -0.0
[76] = 0x00000000, -- fposzero()
[77] = 0x00000000, [78] = 0x00000000, -- dnegzero(): two zero words
[79] = 0x5A5A5A5A, -- marker after float_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 float:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 FLOAT MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 float: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 FLOAT MAME: FAIL")
end
end
end, "float-check")
+27
View File
@@ -0,0 +1,27 @@
; float-entry.asm -- M6 float/double gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver float_run() and writes a post-return marker. float.sh concatenates
; the llc output for m6-float.ll and the compiled driver after this file, so
; _float_run and the float/double functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); float-check.lua reads
; its address from the linker map and checks 80 words (markers 0..79, the last
; one written after float_run returns). Marker n is 0x20 bits above marker
; n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _float_run
movi 5A5A5A5Ah, a0
movi _float_markers+2528, a2 ; marker 79, the post-return word
move a0, *a2, 1
rets
.globl _float_markers
.bss _float_markers, 2560, 16 ; 80 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+241
View File
@@ -0,0 +1,241 @@
/* M6 float/double gate driver.
*
* Calls the compiled float/double functions in m6-float.ll through the M6
* flib ABI and writes the expected GSP result words to the marker array
* defined by the entry assembly. Compiling this driver also exercises the
* compiler's caller side (hidden float/double return slot, stack argument
* pushes, LSW-first doubles) and the callee side of its own C functions
* (float_add, double_add, float_ret, double_ret).
*
* Values are written as raw GSP words, not converted: a float union member
* and an array of two 32-bit words for a GSP double (u[0] = LSW, u[1] = MSW).
*
* Marker word n lives at float_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/float-check.lua reads them by bit address from the linker
* map.
*/
typedef unsigned int u32;
typedef union {
float f;
u32 u;
} fu;
typedef union {
double d;
u32 u[2];
} du;
extern volatile u32 float_markers[];
/* Callees defined in m6-float.ll. */
extern float fadd(float, float);
extern float fsub(float, float);
extern float fmul(float, float);
extern float fdiv(float, float);
extern float fneg(float);
extern double dadd(double, double);
extern double dsub(double, double);
extern double dmul(double, double);
extern double ddiv(double, double);
extern double dneg(double);
extern int fcmpeq(float, float);
extern int fcmplt(float, float);
extern int fcmple(float, float);
extern int fcmpgt(float, float);
extern int fcmpge(float, float);
extern int fcmpne(float, float);
extern int dcmplt(double, double);
extern int dcmpeq(double, double);
extern int ftoi(float);
extern int ftou(float);
extern int dtoi(double);
extern int dtou(double);
extern float itof(int);
extern float utof(u32);
extern double itod(int);
extern double utod(u32);
extern double ftod(float);
extern float dtof(double);
/* Control flow on floating-point comparisons. These are the shapes that were
* missing: `if (a < b)` on float/double and `?:` on a double. */
static int fb_lt(float a, float b)
{
if (a < b)
return 11;
return 22;
}
static int db_lt(double a, double b)
{
if (a < b)
return 33;
return 44;
}
/* A while loop whose condition is a float compare and whose body is float
* arithmetic: a(float) = 1.5, b(float) = 4.0 iterates 1.5, 2.5, 3.5 and stops
* at 4.5, so it counts 3. */
static int fcount_lt(float a, float b)
{
int n = 0;
while (a < b) {
a = a + 1.0f;
n++;
}
return n;
}
/* An f64 select with an integer condition. */
static double dsel_i(int c, double x, double y)
{
return c ? x : y;
}
/* An f64 select with a floating-point condition. */
static double dsel_f(double a, double b, double x, double y)
{
return (a < b) ? x : y;
}
/* GSP has no signed zero: -0.0 must lower to the same all-zero words as +0.0,
* exactly as GSPA prints `.float -0.0`. These markers pin that. */
static float fnegzero(void)
{
return -0.0f;
}
static float fposzero(void)
{
return 0.0f;
}
static double dnegzero(void)
{
return -0.0;
}
static void mark_f(u32 n, float v)
{
fu x;
x.f = v;
float_markers[n] = x.u;
}
static void mark_d(u32 n, double v)
{
du x;
x.d = v;
float_markers[n] = x.u[0]; /* LSW: the lower address in GSP order */
float_markers[n + 1] = x.u[1]; /* MSW */
}
/* C-side callees: the compiler must emit the flib calls for these bodies. */
float float_add(float a, float b)
{
return a + b;
}
double double_add(double a, double b)
{
return a + b;
}
float float_ret(void)
{
return 1.5f;
}
double double_ret(void)
{
return 2.5;
}
void float_run(void)
{
/* Single-precision arithmetic, including the reversed subtraction order
* and a negative result. */
mark_f(0, fadd(1.5f, 2.5f)); /* 4.0 */
mark_f(1, fsub(2.5f, 1.5f)); /* 1.0 */
mark_f(2, fsub(1.5f, 2.5f)); /* -1.0 */
mark_f(3, fmul(4.0f, 2.0f)); /* 8.0 */
mark_f(4, fdiv(4.0f, 2.0f)); /* 2.0 */
mark_f(5, fneg(1.5f)); /* -1.5 */
mark_f(6, float_add(1.5f, 2.5f)); /* C body */
mark_f(7, float_ret()); /* C no-argument hidden return */
/* Double-precision arithmetic, LSW then MSW. */
mark_d(8, dadd(1.5, 2.5)); /* 4.0 */
mark_d(10, dsub(2.5, 1.5)); /* 1.0 */
mark_d(12, dsub(1.5, 2.5)); /* -1.0 */
mark_d(14, dmul(4.0, 2.0)); /* 8.0 */
mark_d(16, ddiv(4.0, 2.0)); /* 2.0 */
mark_d(18, dneg(1.5)); /* -1.5 */
mark_d(20, double_add(1.5, 2.5)); /* C body */
mark_d(22, double_ret()); /* C no-argument hidden return */
/* Float compares: true and false cases. */
float_markers[24] = (u32)fcmpeq(1.5f, 1.5f);
float_markers[25] = (u32)fcmpeq(1.5f, 2.5f);
float_markers[26] = (u32)fcmplt(1.5f, 2.5f);
float_markers[27] = (u32)fcmplt(2.5f, 1.5f);
float_markers[28] = (u32)fcmple(2.5f, 2.5f);
float_markers[29] = (u32)fcmpgt(2.5f, 1.5f);
float_markers[30] = (u32)fcmpge(1.5f, 2.5f);
float_markers[31] = (u32)fcmpne(1.5f, 2.5f);
float_markers[32] = (u32)fcmpne(1.5f, 1.5f);
/* Double compares. */
float_markers[33] = (u32)dcmplt(1.5, 2.5);
float_markers[34] = (u32)dcmplt(2.5, 1.5);
float_markers[35] = (u32)dcmpeq(2.5, 2.5);
/* float/double -> integer: truncation toward zero. */
float_markers[36] = (u32)ftoi(2.5f); /* 2 */
float_markers[37] = (u32)ftoi(-1.5f); /* -1 */
float_markers[38] = (u32)ftou(3.9f); /* 3 */
float_markers[39] = (u32)dtoi(2.5); /* 2 */
float_markers[40] = (u32)dtou(3.9); /* 3 */
/* integer -> float/double. */
mark_f(41, itof(7)); /* 7.0 */
mark_f(42, utof(7)); /* 7.0 */
mark_f(43, itof(-3)); /* -3.0 */
mark_d(44, itod(7)); /* 7.0 */
mark_d(46, utod(7)); /* 7.0 */
mark_d(48, ftod(1.5f)); /* 1.5 */
mark_f(50, dtof(2.5)); /* 2.5 */
/* Constants materialised from the GSP pool, including a negative one. */
mark_f(51, 7.0f);
mark_f(52, -3.0f);
mark_d(53, 7.0);
mark_d(55, -3.0);
float_markers[57] = (u32)fcmpge(2.5f, 2.5f); /* 1 */
float_markers[58] = (u32)fcmpgt(1.5f, 1.5f); /* 0 */
float_markers[59] = (u32)dtoi(-1.5); /* -1 */
float_markers[60] = (u32)fcmple(2.5f, 1.5f); /* 0 */
float_markers[61] = (u32)dcmpeq(1.5, 2.5); /* 0 */
/* Control flow on float/double comparisons: the true and false path of a
* float and a double branch, and a float-compared while loop. */
float_markers[62] = (u32)fb_lt(1.5f, 2.5f); /* true: 11 */
float_markers[63] = (u32)fb_lt(2.5f, 1.5f); /* false: 22 */
float_markers[64] = (u32)db_lt(1.5, 2.5); /* true: 33 */
float_markers[65] = (u32)db_lt(2.5, 1.5); /* false: 44 */
float_markers[66] = (u32)fcount_lt(1.5f, 4.0f); /* 3 iterations */
/* ?: on a double, with an integer and a floating-point condition. */
mark_d(67, dsel_i(1, 1.5, 2.5)); /* 1.5 */
mark_d(69, dsel_i(0, 1.5, 2.5)); /* 2.5 */
mark_d(71, dsel_f(1.5, 2.5, 4.0, 8.0)); /* 4.0 */
mark_d(73, dsel_f(2.5, 1.5, 4.0, 8.0)); /* 8.0 */
/* Signed zero: both spellings lower to all-zero GSP words. */
mark_f(75, fnegzero()); /* 0 */
mark_f(76, fposzero()); /* 0 */
mark_d(77, dnegzero()); /* 0 / 0 */
}
+81
View File
@@ -0,0 +1,81 @@
-- i64-check.lua -- read the M6 i64 marker words and compare them with the
-- expected ABI/arithmetic values.
--
-- I64_MARKERS is the bit address of _i64_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. The values are pairs:
-- MSW first, LSW second, so the word order is checked as well as the result.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("I64_MARKERS"), 16)
local N = 57
local frames = 0
local checked = false
local expect = {
[0] = 0x2345678A, [1] = 0x00000001, -- addll(carry)
[2] = 0x00000000, [3] = 0xACF13568, -- addll(12345678h,9ABCDEF0h)
[4] = 0xFEDCBA98, [5] = 0x00000005, -- subll borrow
[6] = 0x0000000A, [7] = 0x00000008, -- mull cross terms
[8] = 0xFFFFFFFF, [9] = 0xFFFFFFF1, -- (-3)*5
[10] = 0x00010004, [11] = 0xC016906B, -- divll / 1234h
[12] = 0x00000000, [13] = 0x00000334, -- remll / 1234h
[14] = 0x00000000, [15] = 0x10000000, -- divll by a >32-bit divisor
[16] = 0x00000000, [17] = 0x0ABCDEF0, -- remll by a >32-bit divisor
[18] = 0xFFFFFFDE, [19] = 0xBD0CFDB7, -- sdivll(-1e12, 7)
[20] = 0xFFFFFFFF, [21] = 0xFFFFFFFF, -- sremll(-1e12, 7) == -1
[22] = 0xFFFFFFFF, [23] = 0xFFFFFFEF, -- sdivll(123, -7) == -17
[24] = 0x00000000, [25] = 0x00000004, -- sremll(123, -7) == 4
[26] = 0x00000100, [27] = 0x00000000, -- 1 << 40
[28] = 0x00000000, [29] = 0x00000001, -- 8000000000000000h >> 63
[30] = 0xFFFFFFFF, [31] = 0xFFFFFFFC, -- -16 >> 2
[32] = 1, [33] = 0, -- cmplt(-1,1), cmplt(1,-1)
[34] = 1, [35] = 0, -- cmpeq both halves
[36] = 0x00000006, [37] = 0x00000004, -- i64_slot LSW/MSW word order
[38] = 0x00000004, [39] = 0x00000006, -- i64 load round-trip
[40] = 0x0F0F0000, [41] = 0x0F0F0000, -- and
[42] = 0xFFFF0F0F, [43] = 0xFFFF0F0F, -- or
[44] = 0xF0F00F0F, [45] = 0xF0F00F0F, -- xor
[46] = 0x11223344, [47] = 0x55667788, -- zero-argument i64 return
[48] = 0x11223344, [49] = 0x55667788, -- shll(x, 0)
[50] = 0x55667788, [51] = 0x00000000, -- shll(x, 32)
[52] = 0x00000000, [53] = 0x11223344, -- srl(x, 32)
[54] = 0xFFFFFFFF, [55] = 0x80000000, -- sra(8000..., 32)
[56] = 0x5A5A5A5A, -- marker after i64_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 i64:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 I64 MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 i64: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 I64 MAME: FAIL")
end
end
end, "i64-check")
+27
View File
@@ -0,0 +1,27 @@
; i64-entry.asm -- M6 i64 gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver i64_run() and writes a post-return marker. i64.sh concatenates the
; llc output for m6-i64.ll and the compiled driver after this file, so
; _i64_run and the i64 functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); i64-check.lua reads
; its address from the linker map and checks 57 words (markers 0..56, the last
; one written after i64_run returns). Marker n is 0x20 bits above marker n-1,
; matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64_run
movi 5A5A5A5Ah, a0
movi _i64_markers+1792, a2 ; marker 56, the post-return word
move a0, *a2, 1
rets
.globl _i64_markers
.bss _i64_markers, 2048, 16 ; 57 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+127
View File
@@ -0,0 +1,127 @@
/* M6 i64 gate driver.
*
* Calls the compiled `long long` functions in m6-i64.ll through the M6 ABI and
* writes the expected result words to the marker array defined by the entry
* assembly. Compiling this driver also exercises the compiler's *caller*
* side of the hidden-return slot and the two-slot i64 argument pushes; the
* callee side (argument reads, ADD/ADDC, MPYS/MPYU, the division loop, RETS 2)
* comes from the same llc output the lit test checks.
*
* Marker word n lives at i64_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/i64-check.lua reads them by bit address from the linker map.
*/
typedef unsigned int u32;
typedef unsigned long long u64;
typedef long long s64;
extern u64 addll(u64, u64);
extern u64 subll(u64, u64);
extern u64 mull(u64, u64);
extern u64 divll(u64, u64);
extern u64 remll(u64, u64);
extern s64 sdivll(s64, s64);
extern s64 sremll(s64, s64);
extern u64 andll(u64, u64);
extern u64 orll(u64, u64);
extern u64 xorll(u64, u64);
extern u64 shll(u64, u32);
extern u64 srl(u64, u32);
extern s64 sra(s64, u32);
extern u32 cmplt(s64, s64);
extern u32 cmpeq(u64, u64);
extern u64 ret64(void);
extern volatile u32 i64_markers[];
/* Every value is written as MSW first, LSW second, so the marker pair pins
* the word order as well as the numeric result. */
static void mark64(u32 n, u64 v)
{
i64_markers[n] = (u32)(v >> 32);
i64_markers[n + 1] = (u32)v;
}
/* i64 memory order: little-endian, LSW at the lower address. */
volatile u64 i64_slot;
void i64_run(void)
{
u64 r;
/* addll(12345678FFFFFFFEh, 1111111100000003h) = 2345678A00000001h.
* This is the Task 1 probe value; the low-word carry must reach the
* high word. */
mark64(0, addll(0x12345678FFFFFFFEull, 0x1111111100000003ull));
/* The literal brief case addll(12345678h, 9ABCDEF0h) = ACF13568h. */
mark64(2, addll(0x12345678ull, 0x9ABCDEF0ull));
/* subll(1111111100000003h, 12345678FFFFFFFEh) = FEDCBA9800000005h:
* the borrow crosses from the low into the high word. */
mark64(4, subll(0x1111111100000003ull, 0x12345678FFFFFFFEull));
/* mull(0000000100000002h, 0000000300000004h) = 0000000A00000008h:
* both cross terms are needed. */
mark64(6, mull(0x0000000100000002ull, 0x0000000300000004ull));
/* (-3) * 5 = -15 = FFFFFFFFFFFFFFF1h. */
mark64(8, mull(0xFFFFFFFFFFFFFFFDull, 5ull));
/* 123456789ABCDEF0h / 1234h = 10004C016906Bh, remainder 334h. */
mark64(10, divll(0x123456789ABCDEF0ull, 0x1234ull));
mark64(12, remll(0x123456789ABCDEF0ull, 0x1234ull));
/* A divisor above 32 bits forces the full 64x64 path:
* 123456789ABCDEF0h / 123456789h = 100000000h, remainder ABCDEF0h. */
mark64(14, divll(0x123456789ABCDEF0ull, 0x123456789ull));
mark64(16, remll(0x123456789ABCDEF0ull, 0x123456789ull));
/* Signed division truncates toward zero: -1000000000000 / 7 =
* -142857142857 = FFFFFFDEBD0CFDB7h, remainder -1. */
mark64(18, (u64)sdivll(-1000000000000ll, 7ll));
mark64(20, (u64)sremll(-1000000000000ll, 7ll));
/* 123 / -7 = -17 = FFFFFFFFh/FFFFFFEFh, remainder 4. */
mark64(22, (u64)sdivll(123ll, -7ll));
mark64(24, (u64)sremll(123ll, -7ll));
/* Variable-amount shifts: 1 << 40 = 10000000000h. */
mark64(26, shll(1ull, 40));
/* 8000000000000000h >> 63 = 1. */
mark64(28, srl(0x8000000000000000ull, 63));
/* -16 >> 2 = -4 = FFFFFFFFFFFFFFFCh (arithmetic). */
mark64(30, (u64)sra(-16ll, 2));
/* Compares: signed high-half ordering and equality across both halves. */
i64_markers[32] = cmplt(-1ll, 1ll);
i64_markers[33] = cmplt(1ll, -1ll);
i64_markers[34] = cmpeq(0x123456789ABCDEF0ull, 0x123456789ABCDEF0ull);
i64_markers[35] = cmpeq(0x123456789ABCDEF1ull, 0x123456789ABCDEF0ull);
/* i64 store then load through a volatile object, plus a direct word
* read: little-endian memory puts the LSW at the lower address. */
i64_slot = addll(0x0000000100000002ull, 0x0000000300000004ull);
{
volatile u32 *w = (volatile u32 *)&i64_slot;
i64_markers[36] = w[0];
i64_markers[37] = w[1];
}
r = i64_slot;
mark64(38, r);
/* Word-wise logic: and/or/xor of both halves. */
mark64(40, andll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(42, orll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(44, xorll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
/* A zero-argument i64 return: the caller still saves STK for the hidden
* slot and the callee must LOADSTK + RETS 2 with no argument area. */
mark64(46, ret64());
/* Variable-shift edges: 0, 32, and the arithmetic sign fill. */
mark64(48, shll(0x1122334455667788ull, 0));
mark64(50, shll(0x1122334455667788ull, 32));
mark64(52, srl(0x1122334455667788ull, 32));
mark64(54, (u64)sra(0x8000000000000000ull, 32));
}
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+139
View File
@@ -0,0 +1,139 @@
-- runtime-check.lua -- read the M6 runtime gate marker words and the shim's
-- printf output block, and compare them with the expected values.
--
-- RUNTIME_MARKERS is the bit address of _runtime_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. The shim's CONF
-- output block is fixed: length at 01B00020h, bytes at 01B10000h (one byte per
-- 8 bits). The checker compares the whole output byte-for-byte, including the
-- newlines, so the format implementation is the runtime oracle.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local BASE = tonumber(os.getenv("RUNTIME_MARKERS"), 16)
local LEN_ADDR = 0x01B00020
local OUT = 0x01B10000
local CAP = 16384
local N = 13 -- markers 0..12 are written by the driver
local SENT = 15 -- marker 15 is written after runtime_run returns
local frames = 0
local checked = false
local expect = {
[0] = 31, -- printf("%d %s %f %lld\n", ...) length
[1] = 9, -- sprintf("%d|%s|%.1f", 7, "abc", 2.5) length
[2] = 19, -- sprintf("%lld", 1234567890123456789) length
[3] = 300, -- sprintf truncation: full length, not the stored one
[4] = 255, -- strlen after truncation (SPRINTF_CAP-1)
[5] = 1, -- the truncated buffer is NUL-terminated
[6] = 4, -- (int)(1.5 + 2.5), flib FD$ADD + FD$DTOI
[7] = 3, -- (int)(1.5 * 2.5), flib FD$MUL + FD$DTOI
[8] = 1, -- memcpy result equals the source
[9] = 1, -- overlapping memmove forward ("aabcdef")
[10] = 1, -- overlapping memmove backward ("3456567")
[11] = 17, -- printf("S[%s] (%d)\n", ...) length
[12] = 1, -- rts.lib _isascii('A') nonzero, (0xC8) zero
}
local lines = {
"-42 hi 3.250000 -1234567890123",
"[ 42][-0042][7 ][+5][ 5][ff][0xff][10][010][ abc]",
"c=[ A][B ][C]",
"9223372036854775807 -9223372036854775808 " ..
"18446744073709551615 0 -1 4294967295 " ..
"[-0000000000000000005]",
"int=[-123456789][123456789abcdef0][110642547423257157360][00042][42 ]",
"-3.250000 -3.25 3 1.3 3.25 3.25 +3.250000",
"0.000000|00003.25|0.00| 3.25| 3.250000|3.|3.250000",
"cap=2147483520.000000",
"prec=[010][][][][][][0][0][ ]",
"round=10.000000 ncap=-2147483520.000000",
"S[7|abc|2.5] (9)",
"T(300,255,1)",
"mem=abcdefg abcdefg",
"mov=aabcdef",
"mov2=3456567",
"rts=1",
"flib 4.000000 3.750000",
}
local want_out = table.concat(lines, "\n") .. "\n"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
local function escape(s)
return (s:gsub("\n", "\\n"))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
got[SENT] = prog:read_u32(BASE + SENT * 0x20)
if got[SENT] ~= 0x5A5A5A5A then
bad = bad + 1
end
io.write(string.format("M6 runtime:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write(string.format(" %08X\n", got[SENT]))
local len = prog:read_u32(LEN_ADDR)
if len > CAP then
print(string.format("M6 runtime: output length %d > cap %d",
len, CAP))
bad = bad + 1
len = 0
end
local out = read_string(prog, OUT, len)
print(string.format("M6 runtime out(%d): '%s'", len, escape(out)))
if out ~= want_out then
local diff = 1
while diff <= #out and diff <= #want_out and
out:sub(diff, diff) == want_out:sub(diff, diff) do
diff = diff + 1
end
print(string.format(
"M6 runtime: output differs at byte %d: got '%s' want '%s'",
diff, escape(out:sub(diff, diff + 20)),
escape(want_out:sub(diff, diff + 20))))
bad = bad + 1
end
if bad == 0 then
print("M6 RUNTIME MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 runtime: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
if got[SENT] ~= 0x5A5A5A5A then
print(string.format(
"M6 runtime: sentinel got %08X want 5A5A5A5A",
got[SENT]))
end
print("M6 RUNTIME MAME: FAIL")
end
end
end, "runtime-check")
+47
View File
@@ -0,0 +1,47 @@
; runtime-entry.asm -- M6 runtime gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver runtime_run() and writes a post-return marker. runtime.sh
; concatenates the compiled driver and the shared conformance shim after this
; file, so _runtime_run, printf/sprintf and the string/memory functions share
; one assembly.
;
; The marker array is in .bss (linked at the ram origin); runtime-check.lua
; reads its address from the linker map and checks 13 words (0..12 written by
; the driver), 15 after runtime_run returns, and leaves 13..14 zero/unchecked.
; Marker n is 0x20 bits above marker n-1.
;
; The shim's printf output goes to its own CONF_* block above the linked RAM
; region (length at 01B00020h, bytes at 01B10000h); the checker compares those
; bytes with the expected text.
;
; GSPA requires `.ref` for an external symbol used by CALLA. The AsmPrinter
; emits it for the flib `$` ExternalSymbols but not for an ordinary C
; declaration (a GlobalAddress), so declare the rts.lib entry here.
.ref _isascii
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
; Clear the shim's stream lengths. This entry does not otherwise touch
; the result block, and the shim's shadows cannot repair a cell it never
; writes (an empty stream), so clear both cells here.
movi 01B00020h, a1
sub a0, a0
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
calla _runtime_run
movi 5A5A5A5Ah, a0
movi _runtime_markers+480, a2 ; marker 15, the post-return word
move a0, *a2, 1
rets
.globl _runtime_markers
.bss _runtime_markers, 512, 16 ; 16 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+142
View File
@@ -0,0 +1,142 @@
/* M6 runtime gate driver.
*
* Exercises the linked M6 runtime surface through the shared shim:
* - printf("%d %s %f %lld", ...) with a negative int, a string, a GSP double
* with a fraction, and a negative 64-bit value;
* - the M5 integer formats/flags/width/alternate forms;
* - i64/unsigned-i64 boundaries, %ld/%lu and a zero-padded %lld;
* - %f sign/space/plus/zero/width/precision, star width/precision, and the
* documented half-up rounding of %.0f / %.1f;
* - sprintf return values (C: the full untruncated length), NUL
* termination, and safe truncation at the shim's SPRINTF_CAP;
* - memcpy and memmove, including an overlapping backward copy;
* - a double add and multiply that must call flib.lib (FD$ADD/FD$MUL) and be
* converted back to an int by the compiler's fptosi path (FD$DTOI).
*
* The shim writes printf output to the CONF_* block (0x01B00020 length,
* 0x01B10000 bytes); runtime-check.lua compares those bytes exactly with the
* expected text. Marker word n is runtime_markers[n], 0x20 bits apart, in the
* .bss array defined by runtime-entry.asm.
*/
typedef unsigned int u32;
extern volatile u32 runtime_markers[];
extern int printf(const char *fmt, ...);
extern int sprintf(char *buf, const char *fmt, ...);
extern void *memcpy(void *dst, const void *src, unsigned int n);
extern void *memmove(void *dst, const void *src, unsigned int n);
extern int memcmp(const void *a, const void *b, unsigned int n);
extern unsigned int strlen(const char *s);
/* A real rts.lib scalar entry (isascii.obj; no data/.cinit dependency). The
* 1990 `_div`/`_ldiv` wrappers also live in rts.lib but return div_t/ldiv_t
* with the 1990 sret form, not M6's 1987 hidden slot, so calling them would
* not be valid M6 ABI evidence. */
extern int rts_isascii(int c) __asm__("isascii");
void runtime_run(void)
{
char sbuf[256]; /* the shim's sprintf cap (SPRINTF_CAP) */
char lng[301];
char m1[8] = "abcdefg";
char m2[8];
char m3[8] = "1234567";
volatile double a = 1.5; /* volatile: keep FD$ADD/FD$MUL at -O2 */
volatile double b = 2.5;
double d, e;
int i, n;
/* 1. The required mixed conversion: int, string, GSP double, i64. */
runtime_markers[0] = (u32)printf("%d %s %f %lld\n",
-42, "hi", 3.25,
-1234567890123LL);
/* 2. M5 flags/width/alternate plus the new %s precision and width. */
printf("[%5d][%05d][%-5d][%+d][% d][%x][%#x][%o][%#o][%8.3s]\n",
42, -42, 7, 5, 5, 255, 255, 8, 8, "abcdef");
/* 2b. %c honours width/left; a bare %c is unchanged. */
printf("c=[%3c][%-3c][%c]\n", 'A', 'B', 'C');
/* 3. i64/unsigned-i64 boundaries, 32-bit long, zero-padded i64. */
printf("%lld %lld %llu %llu %lld %lu [%020lld]\n",
9223372036854775807LL, (-9223372036854775807LL - 1),
0xFFFFFFFFFFFFFFFFULL, 0ULL, -1LL, 0xFFFFFFFFUL, -5LL);
/* 3b. %ld, 64-bit hex/octal, integer precision and a negative `*`
* width (left-justify with the magnitude of the width). */
printf("int=[%ld][%llx][%llo][%.5d][%*d]\n",
-123456789L, 0x123456789ABCDEF0ULL,
0x123456789ABCDEF0ULL, 42, -6, 42);
/* 4. %f sign/flags/width/precision; %.0f and %.1f round half-up. */
printf("%f %.2f %.0f %.1f %10.2f %-10.2f %+f\n",
-3.25, -3.25, 2.5, 1.25, 3.25, 3.25, 3.25);
/* 5. Zero, zero-padded, star width/precision, space and '#' flags;
* %.9f proves the documented 6-digit precision cap. */
printf("%f|%08.2f|%.2f|%*.*f|% f|%#.0f|%.9f\n",
0.0, 3.25, -0.0, 7, 2, 3.25, 3.25, 2.5, 3.25);
/* 5b. The documented i32-range cap: an out-of-range magnitude is clamped
* instead of taking FD$DTOI's error path. */
printf("cap=%f\n", 3000000000.0);
/* 5c. C precision edge cases: the octal '#' must not add a second
* leading zero when precision already supplies one, and zero with
* precision 0 produces no digits (except `%#.0o`/`%#o`, which keep
* one). */
printf("prec=[%#.3o][%.0d][%.0i][%.0u][%.0x][%.0X][%#.0o][%#o][%5.0d]\n",
8, 0, 0, 0, 0, 0, 0, 0, 0);
/* 5d. Rounding carry through the fraction into the integer part
* (9.9999999 -> 10.000000) and the negative magnitude clamp. */
printf("round=%f ncap=%f\n", 9.9999999, -3000000000.0);
/* sprintf into the caller buffer and print it; the return is the
* C number of characters written (no NUL). */
n = sprintf(sbuf, "%d|%s|%.1f", 7, "abc", 2.5);
runtime_markers[1] = (u32)n;
runtime_markers[11] = (u32)printf("S[%s] (%d)\n", sbuf, n);
/* sprintf return value at the 64-bit boundary (19 digits). */
runtime_markers[2] = (u32)sprintf(sbuf, "%lld",
1234567890123456789LL);
/* sprintf truncation: 300 characters into the 256-byte shim cap. */
for (i = 0; i < 300; i++)
lng[i] = 'a';
lng[300] = 0;
n = sprintf(sbuf, "%s", lng);
runtime_markers[3] = (u32)n;
runtime_markers[4] = strlen(sbuf);
runtime_markers[5] = (u32)(sbuf[255] == 0);
printf("T(%d,%u,%d)\n", n, strlen(sbuf), sbuf[255] == 0);
/* memcpy; then memmove in both directions (overlapping ranges). */
memcpy(m2, m1, 8);
runtime_markers[8] = (u32)(memcmp(m2, m1, 8) == 0);
printf("mem=%s %s\n", m2, m1);
memmove(m1 + 1, m1, 6);
runtime_markers[9] = (u32)(memcmp(m1, "aabcdef", 8) == 0);
printf("mov=%s\n", m1);
memmove(m3, m3 + 2, 4);
runtime_markers[10] = (u32)(memcmp(m3, "3456567", 8) == 0);
printf("mov2=%s\n", m3);
/* rts.lib is linked for real: _isascii is a scalar entry with the TI ABI
* (the 1990 _div/_ldiv wrappers are sret-form and are not called). */
i = (rts_isascii('A') != 0) && (rts_isascii(0xC8) == 0);
runtime_markers[12] = (u32)i;
printf("rts=%d\n", i);
/* flib.lib double arithmetic, formatted back through %f. The volatile
* operands keep the add/multiply from folding at -O2, so both levels
* link and call the real FD$ entries. */
d = a + b;
e = a * b;
runtime_markers[6] = (u32)(int)d;
runtime_markers[7] = (u32)(int)e;
printf("flib %f %f\n", d, e);
}
+70
View File
@@ -0,0 +1,70 @@
-- spike-check.lua -- load the M6 ABI-spike COFF with dwt/loader/loader.lua and
-- read the marker words written by scripts/m6/spike-probe.asm and
-- spike-entry.asm.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- Markers (0x20 bits apart) are the M4 marker convention:
-- 018A8000 FS$ADD float 4.0 (GSP) == 41400000h
-- 018A8020 FD$ADD double 4.0 MSW (GSP) == 40280000h
-- 018A8040 FD$ADD double 4.0 LSW == 00000000h
-- 018A8060 _m6_dadd hidden-return MSW == 40280000h
-- 018A8080 _m6_dadd hidden-return LSW == 00000000h
-- 018A80A0 i64 sum high word == 2345678Ah
-- 018A80C0 i64 sum low word == 00000001h
-- 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
-- 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
-- 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
-- 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
-- 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
-- 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local frames = 0
local checked = false
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 12 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M6: fs_add=%08X fd_add=%08X/%08X dadd=%08X/%08X i64=%08X/%08X fsub=%08X feq=%d ftoi=%d itof=%08X fadd=%08X ret=%08X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6],
m[7], m[8], m[9], m[10], m[11], m[12]))
local want = {
0x41400000, -- FS$ADD 1.5 + 2.5
0x40280000, -- FD$ADD 4.0 MSW
0x00000000, -- FD$ADD 4.0 LSW
0x40280000, -- hidden-return 4.0 MSW
0x00000000, -- hidden-return 4.0 LSW
0x2345678A, -- i64 sum high
0x00000001, -- i64 sum low
0x40400000, -- FS$SUB(2.5,1.5) = 1.0
0x00000001, -- FS$EQ(1.5,1.5) = true in A8
0x00000001, -- FD$FTOI(1.5) = 1 in A8
0x40400000, -- FD$ITOF(1) = float 1.0 pushed on A14
0x41400000, -- _m6_fadd hidden-return 4.0
0x5A5A5A5A, -- _start after _m6_probe returns
}
local ok = true
for i = 0, 12 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M6 MAME: PASS")
else
print("M6 MAME: FAIL (want fs_add=41400000 fd_add=40280000/00000000 dadd=40280000/00000000 i64=2345678A/00000001 fsub=40400000 feq=1 ftoi=1 itof=40400000 fadd=41400000 ret=5A5A5A5A)")
end
end
end, "m6-check")
+25
View File
@@ -0,0 +1,25 @@
; spike-entry.asm -- M6 ABI spike entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the spike stack and calls the
; hand-written probe. The probe is assembly because the compiler does not
; support float/i64 calls until tasks 2/3.
;
; scripts/m6/spike-probe.asm the FS$/FD$ and i64 stack probes
; scripts/m6/spike-check.lua the MAME marker check
; scripts/tests/m6/spike.sh assemble, link with flib.lib/rts.lib, run
;
; FS0 is 16 and FS1 is 32 with the field-extension bit set, exactly as the M2
; ABI requires. A13 is FP and A14 is STK. spike.sh concatenates
; spike-probe.asm after this file, so _m6_probe is defined in the same assembly.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _m6_probe
move a8, @018A8180h, 1 ; marker after the probe returns
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+274
View File
@@ -0,0 +1,274 @@
; spike-probe.asm -- M6 float/double/i64 stack-ABI probe.
;
; The M6 compiler does not lower float/double or i64 calls yet (tasks 2/3), so
; this probe is hand-written assembly that exercises the TI C stack ABI and
; the 1990 SDK flib.lib entry points directly:
;
; 1. FS$ADD(1.5, 2.5) single-precision float, GSP format
; 2. FD$ADD(1.5, 2.5) double precision, GSP format
; 3. _m6_dadd(1.5, 2.5) a C-ABI double function with a caller-allocated
; hidden 8-byte return slot; it calls FD$ADD
; 4. _m6_i64_add two 32-bit argument words per i64 argument and a
; caller-allocated hidden 8-byte return slot
; 5. FS$SUB(2.5, 1.5) pins the arithmetic push order (2.5 first)
; 6. FS$EQ(1.5, 1.5) compare result in A8, not on A14
; 7. FD$FTOI/FD$ITOF integer conversion in A8 / float push on A14
; 8. _m6_fadd(1.5,2.5) a C-ABI float function with a one-word hidden slot
; 9. a marker after _m6_probe returns, so a broken A14 restore/RETS fails
;
; Results are written at the M4 marker addresses (0x20 bits apart) for
; scripts/m6/spike-check.lua:
;
; 018A8000 FS$ADD float 4.0 == 41400000h (GSP)
; 018A8020 FD$ADD double 4.0 most-significant word == 40280000h (GSP)
; 018A8040 FD$ADD double 4.0 least-significant word == 00000000h
; 018A8060 _m6_dadd hidden-return MSW == 40280000h
; 018A8080 _m6_dadd hidden-return LSW == 00000000h
; 018A80A0 i64 sum high word == 2345678Ah
; 018A80C0 i64 sum low word == 00000001h
; 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
; 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
; 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
; 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
; 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
; 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
;
; 1990 flib.lib is the GSP-format library (flibc.lib/flibi.lib are the
; 34082/IEEE variants by member inspection, not linked here). A GSP double is
; stored least-significant word first:
; the lower stack address holds the mantissa word, the higher address holds the
; sign/exponent word. The M6 i64 stack-slot order is MSW-first, so its
; most-significant word is at the lower address.
FP .set A13
STK .set A14
.ref FS$ADD
.ref FS$SUB
.ref FS$EQ
.ref FD$ADD
.ref FD$FTOI
.ref FD$ITOF
.text
.globl _m6_probe
_m6_probe:
setf 16, 1, 0
setf 32, 0, 1
move a14, -*sp, 1 ; preserve the probe's entry STK
move a13, -*sp, 1 ; preserve the probe's entry FP
; ---------------------------------------------------------------------------
; 1. FS$ADD: 1.5 + 2.5 == 4.0 (one 32-bit slot per float, GSP format)
; ---------------------------------------------------------------------------
move a14, -*sp, 1 ; flib uses RETS, not RETS 2
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
movi 040D00000h, a0 ; 2.5
move a0, *a14+, 1
calla FS$ADD
move -*a14, a8, 1 ; result 4.0
move *sp+, a14, 1 ; restore STK
move a8, @018A8000h, 1
; ---------------------------------------------------------------------------
; 2. FD$ADD: 1.5 + 2.5 == 4.0 (two 32-bit slots per double, GSP format).
; GSP puts the least-significant (mantissa) word at the lower address, so
; push it first; the sign/exponent word is the top of the operand.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
clr a0 ; 1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; 1.5 MSW
move a0, *a14+, 1
clr a0 ; 2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; 2.5 MSW
move a0, *a14+, 1
calla FD$ADD
move -*a14, a0, 1 ; result MSW (top)
move -*a14, a1, 1 ; result LSW
move *sp+, a14, 1
move a0, @018A8020h, 1
move a1, @018A8040h, 1
; ---------------------------------------------------------------------------
; 3. _m6_dadd(1.5, 2.5): the caller reserves the 8-byte return slot at the top
; of its frame, then saves STK, then pushes the arguments. The callee
; writes the result at saved_STK-64 (LSW) and saved_STK-32 (MSW).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated return slot
move a14, -*sp, 1 ; save STK for the callee
clr a0 ; b=2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; b=2.5 MSW
move a0, *a14+, 1
clr a0 ; a=1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; a=1.5 MSW
move a0, *a14+, 1
calla _m6_dadd
move -*a14, a0, 1 ; result MSW (saved_STK-32)
move -*a14, a1, 1 ; result LSW (saved_STK-64)
move a0, @018A8060h, 1
move a1, @018A8080h, 1
; ---------------------------------------------------------------------------
; 4. _m6_i64_add(12345678FFFFFFFEh, 1111111100000003h) == 2345678A00000001h.
; Each i64 argument is two 32-bit slots, most-significant word first; the
; return is the 8-byte caller-allocated slot (MSW at saved_STK-64, LSW at
; saved_STK-32).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated i64 return slot
move a14, -*sp, 1
movi 011111111h, a0 ; b high
move a0, *a14+, 1
movi 3, a0 ; b low
move a0, *a14+, 1
movi 012345678h, a0 ; a high
move a0, *a14+, 1
movi 0FFFFFFFEh, a0 ; a low
move a0, *a14+, 1
calla _m6_i64_add
move -*a14, a0, 1 ; result low (saved_STK-32)
move -*a14, a1, 1 ; result high (saved_STK-64)
move a1, @018A80A0h, 1
move a0, @018A80C0h, 1
; ---------------------------------------------------------------------------
; 5. FS$SUB(2.5, 1.5) == 1.0. The first operand is pushed first; the library
; pops the second (top) and subtracts it from the first. Reversing the
; push order would yield -1.0 (C0400000h), so this pins the order.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040D00000h, a0 ; 2.5 (first)
move a0, *a14+, 1
movi 040600000h, a0 ; 1.5 (second)
move a0, *a14+, 1
calla FS$SUB
move -*a14, a0, 1 ; result 1.0
move *sp+, a14, 1
move a0, @018A80E0h, 1
; ---------------------------------------------------------------------------
; 6. FS$EQ(1.5, 1.5) -> A8=1. A compare pops both operands and does not push
; a result; the boolean is in A8.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
move a0, *a14+, 1
calla FS$EQ
move *sp+, a14, 1 ; compare popped both; no result push
move a8, @018A8100h, 1 ; boolean true
; ---------------------------------------------------------------------------
; 7. FD$FTOI(1.5) -> A8=1 (float input on A14, integer result in A8), then
; FD$ITOF(1) -> float 1.0 pushed on A14 (integer input in A8).
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
calla FD$FTOI
move *sp+, a14, 1 ; input popped; no result push
move a8, @018A8120h, 1 ; integer 1
move a14, -*sp, 1 ; A8 still holds 1
calla FD$ITOF
move -*a14, a0, 1 ; result float 1.0 = 40400000h
move *sp+, a14, 1
move a0, @018A8140h, 1
; ---------------------------------------------------------------------------
; 8. _m6_fadd(1.5, 2.5): the caller reserves a one-word return slot
; (ADDI 32,STK), the callee writes it at saved_STK-32 and RETS 2.
; ---------------------------------------------------------------------------
addi 32, a14 ; caller-allocated float return slot
move a14, -*sp, 1
movi 040D00000h, a0 ; b=2.5
move a0, *a14+, 1
movi 040600000h, a0 ; a=1.5
move a0, *a14+, 1
calla _m6_fadd
move -*a14, a0, 1 ; result 4.0 (saved_STK-32)
move a0, @018A8160h, 1
; ---------------------------------------------------------------------------
; 9. Return a known A8 after all A14 save/restore pairs. spike-entry.asm
; stores it after CALLA _m6_probe, so a broken restore or RETS cannot pass.
; ---------------------------------------------------------------------------
movi 05A5A5A5Ah, a8
move *sp+, a13, 1 ; restore entry FP
move *sp+, a14, 1 ; restore entry STK
rets
; ---------------------------------------------------------------------------
; _m6_dadd: double dadd(double a, double b) with the TI C hidden-return rule.
; a at FP(-64)=LSW, FP(-32)=MSW; b at FP(-128)=LSW, FP(-96)=MSW
; result at saved_STK-64=LSW, saved_STK-32=MSW
; ---------------------------------------------------------------------------
.globl _m6_dadd
_m6_dadd:
mmtm sp, a0, a1, a2
move a13, -*sp, 1
move a14, a13
move *a13(-64), *a14+, 1 ; a LSW
move *a13(-32), *a14+, 1 ; a MSW
move *a13(-128), *a14+, 1 ; b LSW
move *a13(-96), *a14+, 1 ; b MSW
calla FD$ADD
move -*a14, a2, 1 ; result MSW
move -*a14, a1, 1 ; result LSW
move *sp(160), a14, 1 ; caller's saved STK (3 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; LSW at saved_STK-64
move a2, *a0, 1 ; MSW at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2
rets 2
; ---------------------------------------------------------------------------
; _m6_fadd: float fadd(float a, float b) with the TI C hidden-return rule.
; One 32-bit slot per float: a at FP(-32), b at FP(-64).
; result at saved_STK-32.
; ---------------------------------------------------------------------------
.globl _m6_fadd
_m6_fadd:
mmtm sp, a0, a1
move a13, -*sp, 1
move a14, a13
move *a13(-32), *a14+, 1 ; a
move *a13(-64), *a14+, 1 ; b
calla FS$ADD
move -*a14, a1, 1 ; result
move *sp(128), a14, 1 ; caller's saved STK (2 regs+FP+PC)
move a14, a0
subi 32, a0
move a1, *a0, 1 ; result at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1
rets 2
; ---------------------------------------------------------------------------
; _m6_i64_add: long long add(long long a, long long b), hidden 8-byte return.
; a high at FP(-64), a low at FP(-32); b high at FP(-128), b low at FP(-96).
; The caller pushes b high, b low, a high, a low, so the pop order is
; a low, a high, b low, b high.
; ---------------------------------------------------------------------------
.globl _m6_i64_add
_m6_i64_add:
mmtm sp, a0, a1, a2, a3
move a13, -*sp, 1
move a14, a13
move -*a14, a2, 1 ; a low
move -*a14, a1, 1 ; a high
move -*a14, a0, 1 ; b low
move -*a14, a3, 1 ; b high
add a0, a2 ; low = a low + b low, sets carry
addc a3, a1 ; high = a high + b high + carry
move *sp(192), a14, 1 ; caller's saved STK (4 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; high at saved_STK-64
move a2, *a0, 1 ; low at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2, a3
rets 2
+87
View File
@@ -0,0 +1,87 @@
-- varargs-check.lua -- read the M6 varargs marker words and the formatted
-- output buffer, and compare them with the expected values.
--
-- VARARGS_MARKERS is the bit address of _varargs_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. VARARGS_OUT is the
-- bit address of the C driver's `char varargs_out[64]`; the checker reads the
-- bytes of the expected string (TMS34010 memory is byte-addressed at the low
-- end of a bit address, one byte per 8 bits).
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("VARARGS_MARKERS"), 16)
local OUT = tonumber(os.getenv("VARARGS_OUT"), 16)
local N = 15
local frames = 0
local checked = false
local expect = {
[0] = 100, -- vsum(4, 10, 20, 30, 40): int walk
[1] = 42, -- vlong(0, 42): long is one slot
[2] = 1, -- vptr(0, 0x12345678): char * is one slot
[3] = 2, -- vdbl(0, 2.5): GSP double, MSW at the top
[4] = 0x9ABCDEF0, -- vll(0, 123456789ABCDEF0h): i64 LSW at the top
[5] = 257, -- mixed_di(0, 2.5, 7): double then int
[6] = 0x5566BD76, -- mixed_llp(0, 1122334455667788h, CAFEh)
[7] = 13, -- vcopy(0, 4, 5, 6): va_copy independence
[8] = 24, -- vforward(3, 7, 8, 9): forwarded va_list
[9] = 11, -- vnoargs(11): no fixed argument
[10] = 77, -- vlastd(1.5, 77): double last fixed argument
[11] = 4, -- myfmt("n=%d", -7) length
[12] = 19, -- myfmt("v=%d s=%s d=%f", ...) length
[13] = 2, -- call_vf32(): one-slot f32 va_arg
[14] = 0x5A5A5A5A, -- marker after varargs_run returns
}
local want_out = "v=42 s=hello d=3.25"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 varargs:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
local out = read_string(prog, OUT, #want_out)
print(string.format("M6 varargs out: '%s'", out))
if out ~= want_out then
print(string.format("M6 varargs: output got '%s' want '%s'",
out, want_out))
bad = bad + 1
end
if bad == 0 then
print("M6 VARARGS MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 varargs: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 VARARGS MAME: FAIL")
end
end
end, "varargs-check")
+28
View File
@@ -0,0 +1,28 @@
; varargs-entry.asm -- M6 varargs gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver varargs_run() and writes a post-return marker. varargs.sh
; concatenates the llc output for m6-varargs.ll and the compiled driver after
; this file, so _varargs_run and the variadic functions share one assembly.
;
; The marker array is in .bss (linked at the ram origin); varargs-check.lua
; reads its address from the linker map and checks 15 words (markers 0..14, the
; last one written after varargs_run returns). Marker n is 0x20 bits above
; marker n-1. varargs_out is the formatted-output buffer defined by the C
; driver (zero-initialized .bss); the checker also reads its bytes.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _varargs_run
movi 5A5A5A5Ah, a0
movi _varargs_markers+448, a2 ; marker 14, the post-return word
move a0, *a2, 1
rets
.globl _varargs_markers
.bss _varargs_markers, 512, 16 ; 15 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+175
View File
@@ -0,0 +1,175 @@
/* M6 varargs gate driver.
*
* Calls the compiled variadic functions in m6-varargs.ll through the TI
* all-stack ABI and writes the expected result words to the marker array
* defined by the entry assembly. Compiling this driver exercises the
* compiler's own caller side (variadic call pushes) and callee side (a real
* __builtin_va_list walk in myfmt, including a GSP double read).
*
* myfmt is the `%d %s %f` style output: it walks its va_list downward and
* writes "v=42 s=hello d=3.25" into varargs_out. The MAME checker compares
* those bytes exactly, so the formatted text is the runtime oracle for the
* int, pointer (string) and double va_arg paths in one call.
*
* Marker word n lives at varargs_markers[n], i.e. 0x20 bits above the
* previous one; scripts/m6/varargs-check.lua reads them by bit address from
* the linker map.
*/
typedef unsigned int u32;
typedef long long s64;
extern volatile u32 varargs_markers[];
/* Callees defined in m6-varargs.ll. The driver and the .ll must agree on the
* argument sequence; the IR signatures are the authoritative side.
*
* `vnoargs` is really `int vnoargs(...)`. ISO C cannot declare a variadic
* function with no named parameter, so the driver declares a variadic
* prototype with one int. The call site is variadic (so the caller saves STK,
* which is what a variadic callee needs), and the callee treats that pushed
* word as its first variadic argument. The declaration must not be used for
* any other callee. */
extern int vsum(int, ...);
extern int vlong(int, ...);
extern char *vptr(int, ...);
extern int vdbl(int, ...);
extern int vll(int, ...);
extern int mixed_di(int, ...);
extern int mixed_llp(int, ...);
extern int vcopy(int, ...);
extern int vforward(int, ...);
extern int vnoargs(int, ...);
extern int vlastd(double, ...);
extern int call_vf32(void);
char varargs_out[64];
static int outn;
static void out_char(char c)
{
if (outn < 64)
varargs_out[outn++] = c;
}
static void out_str(const char *s)
{
while (*s)
out_char(*s++);
}
static void out_num(int v)
{
char tmp[12];
int n = 0;
unsigned int uv;
if (v < 0) {
out_char('-');
uv = ~(unsigned int)v + 1U;
} else {
uv = (unsigned int)v;
}
if (uv == 0)
tmp[n++] = '0';
while (uv) {
tmp[n++] = (char)('0' + uv % 10);
uv /= 10;
}
while (n--)
out_char(tmp[n]);
}
/* printf-shaped variadic callee using the real va_list: %d, %s and %f with
* two fraction digits. The double is converted through the flib ftoi path, so
* this also exercises a float-to-int conversion on a variadic value. */
int myfmt(const char *fmt, ...)
{
__builtin_va_list ap;
const char *p;
__builtin_va_start(ap, fmt);
outn = 0;
for (p = fmt; *p; p++) {
if (*p != '%') {
out_char(*p);
continue;
}
p++;
switch (*p) {
case 'd': {
int v = __builtin_va_arg(ap, int);
out_num(v);
break;
}
case 's': {
char *s = __builtin_va_arg(ap, char *);
out_str(s);
break;
}
case 'f': {
double d = __builtin_va_arg(ap, double);
int scaled = (int)(d * 100.0);
int frac = scaled % 100;
out_num(scaled / 100);
out_char('.');
if (frac < 10)
out_char('0');
out_num(frac);
break;
}
default:
out_char('%');
out_char(*p);
break;
}
}
__builtin_va_end(ap);
return outn;
}
void varargs_run(void)
{
/* int walk over a fixed argument plus four variadic ints. */
varargs_markers[0] = (u32)vsum(4, 10, 20, 30, 40);
/* long (one slot). */
varargs_markers[1] = (u32)vlong(0, 42);
/* char * (one slot): compare the returned bit address. */
varargs_markers[2] = (u32)(vptr(0, (char *)0x12345678UL) ==
(char *)0x12345678UL);
/* double (two slots, MSW at the higher address): 2.5 -> 2. */
varargs_markers[3] = (u32)vdbl(0, 2.5);
/* long long (two slots, LSW at the higher address): low word. */
varargs_markers[4] = (u32)vll(0, 0x123456789ABCDEF0LL);
/* Mixed sequences: double then int, and i64 then pointer. */
varargs_markers[5] = (u32)mixed_di(0, 2.5, 7);
varargs_markers[6] = (u32)mixed_llp(0, 0x1122334455667788LL,
(char *)0xCAFEUL);
/* va_copy: ap reads 4 then 5; aq still reads 4 independently. */
varargs_markers[7] = (u32)vcopy(0, 4, 5, 6);
/* A callee forwarding its va_list to vsum_walk. */
varargs_markers[8] = (u32)vforward(3, 7, 8, 9);
/* No fixed argument: the first pushed word is the first va_arg. */
varargs_markers[9] = (u32)vnoargs(11);
/* A double last fixed argument (two slots) before the variadic area. */
varargs_markers[10] = (u32)vlastd(1.5, 77);
/* An f32 va_arg: one GSP word (the C caller cannot pass a promoted
* float, so call_vf32 is the hand-written IR caller). */
varargs_markers[13] = (u32)call_vf32();
/* The %d path with a negative value, then the %d %s %f output. */
varargs_markers[11] = (u32)myfmt("n=%d", -7);
varargs_markers[12] = (u32)myfmt("v=%d s=%s d=%f", 42, "hello", 3.25);
}
+51
View File
@@ -0,0 +1,51 @@
; cinit-entry.asm -- M7.2 `.cinit` gate entry, linked at bit 018A0000.
;
; The `.cinit` loop is byte-for-byte the termtris `_start` loop from
; vendor/vt1200-termtris/apps/termtris/src/vt1200/entry.asm:
;
; movi cinit,a9
; move *a9+,count ; u16 data-word count
; jrz done
; move *a9+,dest,1 ; u32 destination (a TMS34010 bit address)
; move *a9+,*dest+ ; copy `count` words
;
; The public `cinit` symbol is defined at offset 0 of this object's empty
; `.cinit` section (the termtris cinit.asm shape), so the linker places it at
; the `.cinit` origin and the C table (concatenated after this zero-size input
; section) is the record the loop reads. GSPA emits this object's sections in
; the order .text/.data/.bss/.cinit; tms-link accepts that GSPA order as well
; as the llc .text/.data/.cinit/.bss order.
;
; After the copy loop the entry calls cinit_probe(), which returns the sum of
; the three copied words; that value is the 018A8000 marker.
.ref _cinit_probe
.text
.globl _start
_start:
setf 32,0,1
movi _cstack,a14
move a14,a13
movi cinit,a9
ci_loop:
setf 16,0,0
move *a9+,a11
jrz ci_done
move *a9+,a10,1
ci_copy:
move *a9+,*a10+
dsjs a11,ci_copy
jruc ci_loop
ci_done:
setf 32,0,1
move a13,a14
calla _cinit_probe
move a8,@018A8000h,1
rets
.sect ".cinit"
.globl cinit
cinit:
.bss _cstack,32768,16
.end
+51
View File
@@ -0,0 +1,51 @@
/* M7.2 `.cinit` gate table: the TI init-record format in C.
*
* The TI format is a sequence of records:
*
* packed struct {
* unsigned short count; // data word count
* unsigned long destination; // TMS34010 *bit* address
* unsigned short data[count];
* };
*
* terminated by a zero count. `cinit-entry.asm` defines the public `cinit`
* symbol at the start of its own empty `.cinit` section (the termtris
* `cinit.asm` shape) and walks this table exactly like the termtris `_start`:
* `movi cinit,a9; move *a9+,count; move *a9+,dst,1; copy count words`.
*
* The destination is a pointer-typed union member rather than a plain
* `unsigned long` initialised with `(unsigned long)&cinit_target`. Both are
* the same packed 32-bit field at byte offset 2, but the object writer emits a
* relocation only for a pointer constant; casting the address to an integer
* produces an LLVM `ptrtoint` constant expression that the `.data`/.cinit
* emitter deliberately rejects as unsupported. The pointer value *is* the
* TMS34010 bit address in this ABI, so the linked field is the resolved bit
* address the entry loop needs. The record header is packed, so the 32-bit
* destination sits at bit offset 16 and the linker resolves it as an ordinary
* R-RELLONG field (the CPU copy loop is bit-addressed).
*/
unsigned short cinit_target[4];
struct __attribute__((packed)) cinit_record {
unsigned short count;
union {
unsigned long destination;
unsigned short *address;
} target;
unsigned short data[3];
unsigned short end;
};
/* The table lives in `.cinit`; the entry object contributes the `cinit`
* symbol at offset 0 of the concatenated section. */
__attribute__((section(".cinit")))
const struct cinit_record cinit_table = {
3, { .address = cinit_target }, { 0x1111, 0x2222, 0x3333 }, 0
};
/* Called by the entry after the copy loop; returns the sum of the copied
* words (0x1111 + 0x2222 + 0x3333 = 0x6666). */
int cinit_probe(void) {
return cinit_target[0] + cinit_target[1] + cinit_target[2];
}
+29
View File
@@ -0,0 +1,29 @@
; debug-entry.asm -- M7.2 debug-info gate entry, linked at bit 018A0000.
;
; debug.c is linked first so debug_mul is the text-origin function and its
; DWARF low PC is the expected 0x314000 (text origin 018A0000 / 8). This
; entry calls debug_mul(), debug_add() and debug_ptr() and stores their
; results, 43, 14 and 30, at 018A8000, 018A8020 and 018A8040.
;
; debug_ptr() takes no argument: it uses the .data debug_index (2) for the
; pointer update, so the entry needs no argument-pushing sequence.
.ref _debug_mul
.ref _debug_add
.ref _debug_ptr
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _debug_mul
move a8,@018A8000h,1
calla _debug_add
move a8,@018A8020h,1
calla _debug_ptr
move a8,@018A8040h,1
rets
.bss _cstack,32768,16
.end
+37
View File
@@ -0,0 +1,37 @@
int debug_mul(void) {
int product = 42;
return product + 1;
}
int debug_add(void) {
int sum = 7;
return sum + 7;
}
int debug_array[4] = {10, 20, 30, 40};
int debug_index = 2;
int debug_ptr(void) {
int *p = debug_array;
p += debug_index;
return *p;
}
/* M7.2 debug-info gate driver.
*
* Three functions, so the linked `.debug_info` has three subprograms and the
* second/third `.text` offsets are nonzero. debug_mul returns 43,
* debug_add returns 14 and debug_ptr returns debug_array[2] = 30; the entry
* stores them at 018A8000/018A8020/018A8040 after the stripped link is loaded
* in MAME.
*
* debug_ptr is the bit-pointer barrier coverage: `p += debug_index` is a
* runtime `getelementptr` that --bitptr rewrites, so the -O0 gate proves the
* line row survives that rewrite; debug.sh also builds this TU at -O2 -g to
* exercise opt/--scale/--lower-bitptr/instcombine.
*
* The declarations are on lines 1, 6 and 14; the first local-variable /
* pointer-update lines are 2, 7, 15 and 16; debug.sh asserts those
* `.debug_line` rows and the DW_AT_decl_line values. The comment is
* deliberately after the code so the line numbers stay stable.
*/
+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Wrap linked TI-COFF `.debug_*` sections in a minimal ELF32 container.
The TMS34010 native path is TI-COFF end to end; `llvm-dwarfdump` reads ELF,
Mach-O and Wasm, not the 1987 TI COFF variant. This test-only helper extracts
the non-allocated `.debug_*` sections from a `tms-link --keep-debug` image and
writes an ELF32 little-endian relocatable container with section headers and a
`.shstrtab` but no program headers or symbol table.
No addresses or relocations are rewritten: `tms-link` has already resolved the
DWARF byte addresses (for example `.debug_addr` holds 0x314000 for text origin
0x018A0000), and DWARF section-internal offsets are section-relative.
Usage:
elf-debug-wrap.py -o OUT.elf LINKED.coff [SECTION ...]
With no SECTION arguments every `.debug_*` section is wrapped. The input is
parsed directly (the helper has no project dependencies) so the debug gate can
assert the linked TI-COFF and the ELF wrapper independently.
"""
from __future__ import annotations
import argparse
import struct
import sys
MAGIC = 0x0090
class WrapError(Exception):
pass
def _u16(data, off):
return struct.unpack_from("<H", data, off)[0]
def _u32(data, off):
return struct.unpack_from("<I", data, off)[0]
def _string_at(table, offset, what):
if offset < 4:
raise WrapError("%s string-table offset %d is inside the 4-byte size "
"field" % (what, offset))
end = table.find(b"\0", offset)
if end < 0:
raise WrapError("%s string-table entry at %d is not terminated"
% (what, offset))
return table[offset:end].decode("latin1")
def read_coff(path):
with open(path, "rb") as fh:
data = fh.read()
if len(data) < 20:
raise WrapError("%s: shorter than a COFF file header" % path)
machine, nscns, _timdat, symptr, nsyms, opthdr, _flags = \
struct.unpack_from("<HHIIIHH", data, 0)
if machine != MAGIC:
raise WrapError("%s: machine %#06x, expected %#06x"
% (path, machine, MAGIC))
if nscns == 0:
raise WrapError("%s: no sections" % path)
string_table = b""
if nsyms:
string_base = symptr + nsyms * 18
if string_base + 4 > len(data):
raise WrapError("%s: symbol/string table runs past EOF" % path)
size = _u32(data, string_base)
if size < 4 or string_base + size > len(data):
raise WrapError("%s: implausible string-table size %d"
% (path, size))
string_table = data[string_base:string_base + size]
sections = []
base = 20 + opthdr
for i in range(nscns):
off = base + i * 40
if off + 40 > len(data):
raise WrapError("%s: section header %d past EOF" % (path, i))
raw_name = data[off:off + 8]
if raw_name.startswith(b"/"):
digits = raw_name[1:].split(b"\0", 1)[0]
if not digits.isdigit():
raise WrapError("%s: bad long section name %r"
% (path, raw_name))
name = _string_at(string_table, int(digits),
"%s: section %d" % (path, i + 1))
else:
name = raw_name.split(b"\0", 1)[0].decode("latin1")
paddr, vaddr, size, scnptr, relptr, _lnnoptr, nreloc, _nlnno, flags = \
struct.unpack_from("<IIIIIIHHI", data, off + 8)
if size % 8:
raise WrapError("%s: section %r size %d bits is not whole bytes"
% (path, name, size))
blob = b""
if size and name != ".bss":
if scnptr + size // 8 > len(data):
raise WrapError("%s: section %r raw data runs past EOF"
% (path, name))
blob = data[scnptr:scnptr + size // 8]
sections.append(dict(name=name, paddr=paddr, vaddr=vaddr, size=size,
flags=flags, nreloc=nreloc, raw=blob))
by_name = {s["name"]: s for s in sections}
if len(by_name) != len(sections):
raise WrapError("%s: duplicate section names" % path)
return sections
def build_elf(sections):
# Only the section-header table and the section payloads exist; the DWARF
# data is already absolute, so no symbol table or relocations are needed.
shstr = bytearray(b"\0")
name_off = {}
for sec in sections:
name_off[sec["name"]] = len(shstr)
shstr.extend(sec["name"].encode("latin1"))
shstr.append(0)
shstr_name = len(shstr)
shstr.extend(b".shstrtab\0")
shnum = len(sections) + 2 # null section + payload sections + shstrtab
shoff = 52
cursor = (shoff + shnum * 40 + 3) & ~3
payload_off = []
for sec in sections:
payload_off.append(cursor)
cursor += len(sec["raw"])
cursor = (cursor + 3) & ~3
shstr_off = cursor
cursor += len(shstr)
total = (cursor + 3) & ~3
out = bytearray(total)
e_ident = b"\x7fELF" + bytes([1, 1, 1, 0]) + bytes(8) # 32-bit LE v1
struct.pack_into("<16sHHIIIIIHHHHHH", out, 0, e_ident,
1, # e_type ET_REL
# EM_386 keeps llvm-dwarfdump from warning about an
# unknown machine (there is no standard TMS34010 EM_*).
3, # e_machine EM_386
1, # e_version
0, # e_entry
0, # e_phoff (no program headers)
shoff, # e_shoff
0, # e_flags
52, # e_ehsize
0, 0, # e_phentsize, e_phnum
40, # e_shentsize
shnum, # e_shnum
shnum - 1) # e_shstrndx
for i, sec in enumerate(sections, start=1):
off = shoff + i * 40
struct.pack_into("<IIIIIIIIII", out, off,
name_off[sec["name"]],
1, # SHT_PROGBITS
0, # no sh_flags
0, # sh_addr (DWARF is absolute)
payload_off[i - 1],
len(sec["raw"]),
0, 0, # sh_link, sh_info
1, # sh_addralign
0) # sh_entsize
out[payload_off[i - 1]:payload_off[i - 1] + len(sec["raw"])] = \
sec["raw"]
off = shoff + (shnum - 1) * 40
struct.pack_into("<IIIIIIIIII", out, off, shstr_name, 3, 0, 0,
shstr_off, len(shstr), 0, 0, 1, 0)
out[shstr_off:shstr_off + len(shstr)] = shstr
return bytes(out)
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("-o", "--output", required=True, metavar="OUT.elf",
help="ELF32 output container")
p.add_argument("coff", metavar="LINKED.coff",
help="linked TI-COFF with --keep-debug")
p.add_argument("sections", nargs="*", metavar="SECTION",
help="debug section names to include (default: all "
".debug_*)")
args = p.parse_args(argv)
try:
all_sections = read_coff(args.coff)
by_name = {s["name"]: s for s in all_sections}
if args.sections:
missing = [n for n in args.sections if n not in by_name]
if missing:
raise WrapError("%s: missing section(s): %s"
% (args.coff, ", ".join(missing)))
chosen = [by_name[n] for n in args.sections]
else:
chosen = [s for s in all_sections
if s["name"].startswith(".debug_")]
if not chosen:
raise WrapError("%s: no .debug_* sections to wrap" % args.coff)
for sec in chosen:
if not sec["name"].startswith(".debug_"):
raise WrapError("%s: %r is not a .debug_* section"
% (args.coff, sec["name"]))
if sec["paddr"] != 0 or sec["vaddr"] != 0:
raise WrapError("%s: debug section %r has paddr/vaddr "
"%#x/%#x, expected 0/0"
% (args.coff, sec["name"], sec["paddr"],
sec["vaddr"]))
elf = build_elf(chosen)
with open(args.output, "wb") as fh:
fh.write(elf)
print("elf-debug-wrap: %s <- %s (%s)"
% (args.output, args.coff,
" ".join("%s=%dB" % (s["name"], len(s["raw"]))
for s in chosen)))
return 0
except (WrapError, OSError) as exc:
print("elf-debug-wrap: error: %s" % exc, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+111
View File
@@ -0,0 +1,111 @@
-- hw-check.lua -- M7.3 real-hardware marker gate, MAME-equivalent acceptance.
--
-- Loads the same COFF that hostload.py sends to the real unit
-- (scripts/m7/hwmark.c, linked at .text 018C0000 / .data 018D0000 /
-- .bss 018D8000) through vendor/vt1200/dwt/loader/loader.lua, then requires
-- exactly what hostload.py's verify_markers() requires:
--
-- 018E0000 start == the loader result block's entry (018C0000)
-- 018E0020 data == 0xDEADBEEF (copied .data)
-- 018E0040 data2 == 0x12345678 (copied .data)
-- 018E0060 bss == 0 (zeroed .bss; loader pre-fills A5A5)
-- 018E0080 count advances (the child is scheduled, not jumped)
--
-- and that the loader result status is 0. LOADER_AT/LOADER_END come from the
-- M4-style environment; the counter is sampled after the child has run, then
-- again one frame before the loader exits.
dofile(os.getenv("M4_LOADER_LUA"))
local AT = tonumber(os.getenv("LOADER_AT") or "2500")
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local RESULT = 0x01882D00
local CELLS = {
{ 0x018E0000, "start" },
{ 0x018E0020, "data" },
{ 0x018E0040, "data2" },
{ 0x018E0060, "bss" },
{ 0x018E0080, "count" },
}
-- First sample: a few frames after injection, so the child has started.
-- Second sample: the last frame before loader.lua inspects and exits.
local SAMPLE0 = math.max(AT + 5, ENDF - 11)
local SAMPLE1 = ENDF - 1
local frames = 0
local first_count = nil
local checked = false
local function r32(prog, addr)
local ok, v = pcall(function() return prog:read_u32(addr) end)
if ok then return v end
return nil
end
emu.register_frame_done(function()
frames = frames + 1
if frames == SAMPLE0 and first_count == nil then
local prog = manager.machine.devices[':maincpu'].spaces['program']
first_count = r32(prog, 0x018E0080)
end
if frames == SAMPLE1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local v = {}
for _, cell in ipairs(CELLS) do
v[cell[2]] = r32(prog, cell[1])
end
local status = r32(prog, RESULT + 0x000)
local entry = r32(prog, RESULT + 0x020)
local count0 = first_count or 0
local count1 = v.count or 0
print(string.format(
"M7 HW: start=0x%08X data=0x%08X data2=0x%08X bss=0x%08X count=%d->%d status=%d entry=0x%08X",
v.start or 0, v.data or 0, v.data2 or 0, v.bss or 0,
count0, count1, status or -1, entry or 0))
local problems = {}
if status ~= 0 then
problems[#problems + 1] = string.format("loader status=%s, want 0",
tostring(status))
end
if entry ~= 0x018C0000 then
problems[#problems + 1] = string.format(
"loader entry=0x%08X, want 0x018C0000", entry or 0)
end
if v.start ~= entry then
problems[#problems + 1] = string.format(
"start=0x%08X, want the entry 0x%08X", v.start or 0, entry or 0)
end
if v.data ~= 0xDEADBEEF then
problems[#problems + 1] = string.format("data=0x%08X, want 0xDEADBEEF",
v.data or 0)
end
if v.data2 ~= 0x12345678 then
problems[#problems + 1] = string.format(
"data2=0x%08X, want 0x12345678", v.data2 or 0)
end
if v.bss ~= 0 then
problems[#problems + 1] = string.format("bss=0x%08X, want 0",
v.bss or 0)
end
if count0 <= 0 or count1 <= count0 then
problems[#problems + 1] = string.format(
"count did not advance (%d -> %d)", count0, count1)
end
if #problems == 0 then
print("M7 HW MAME: PASS")
else
for _, p in ipairs(problems) do
print("M7 HW: FAIL: " .. p)
end
print("M7 HW MAME: FAIL")
end
end
end, "m7-hw-check")
+76
View File
@@ -0,0 +1,76 @@
/*
* hwmark.c -- M7.3 real-hardware marker client, built at the proven VT1200
* hardware origins:
*
* .text 018C0000h
* .data 018D0000h
* .bss 018D8000h
*
* This is the COFF image that dwt/loader/hostload.py pokes and that
* dwt/loader/loader.asm places through create_process. The marker cells are
* the ones hostload.py's MARKER_CELLS names (all TMS34010 *bit* addresses):
*
* 018E0000 _start address at run time (must equal the loader entry)
* 018E0020 d_magic read from .data (must be DEADBEEF)
* 018E0040 d_two read from .data (must be 12345678)
* 018E0060 b_zero read from .bss (must be 0)
* 018E0080 b_counter, a live counter (must advance)
*
* The M7.3 brief prefers a C-only entry when the compiler can express it, so
* `start` is an ordinary C function and the COFF entry point is `_start`.
* create_process() supplies the process stack (the firmware allocates it; the
* xhello trace records a valid entry A14). The MAME run proves the generated
* prologue did not fault and the markers/counter are correct, not that A14/SP
* point at the create_process stack; the real-unit run (VT1200_HOST) is the
* hardware confirmation. The `.data` pointer
* initializer below is supported as an ordinary pointer relocation, so no
* `ptrtoint` constant initializer and no assembly entry are needed.
*
* The loader zeroes .bss after the harness has pre-filled it with A5A5, so a
* zero at 018E0060 is the loader's work, not fresh RAM. The delay loop is
* marker.asm's 2000h `dsjs` delay: the child stays scheduled but does not burn
* the cooperative scheduler with an unbroken hot loop.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018E0000u + (n) * 0x20u))
/* Initialised .data: the loader must copy these bytes from the COFF. */
unsigned int d_magic = 0xDEADBEEFu;
unsigned int d_two = 0x12345678u;
/* Uninitialised .bss: the loader must zero these. */
unsigned int b_zero;
unsigned int b_counter;
void start(void);
/*
* The entry address as a relocated pointer, not a ptrtoint constant. The
* loader's result block reports the same `_start` bit address as the COFF
* entry point, so the runtime start cell proves placement, not a guess.
*/
void (*const start_address)(void) = start;
/* A volatile .bss sink keeps the delay loop from being folded away. */
static volatile unsigned int delay_sink;
void start(void) {
unsigned int count = 0;
MARK(0) = (unsigned int)start_address;
MARK(1) = d_magic;
MARK(2) = d_two;
MARK(3) = b_zero;
for (;;) {
unsigned int spin;
count++;
b_counter = count;
MARK(4) = count;
for (spin = 0; spin < 0x2000u; spin++) {
delay_sink = spin;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
-a
-o M4.OUT
-m M4.MAP
-e _start
M4.obj
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Assert the M7.4 i64div perf marker cells are outside every linked section.
Usage:
i64div-map-check.py MAP MARKER_HEX [PROG_ORIGIN PROG_LEN RAM_ORIGIN RAM_LEN]
MAP is a GSPLNK 2.00 map (the SECTION ALLOCATION MAP has origin/length in
bits) or a tms-link map (the symbol addresses give .text/etext,
.data/edata, .bss/end). MARKER_HEX is the marker base bit address; the gate
uses 8 cells 0x20 bits apart. The optional region arguments are also in hex
(bits) and bound .text/.data to prog and .bss/the markers to ram.
Exit status: 0 = every check passed, 1 = overlap/out-of-region, 2 = the map
could not be parsed.
"""
import re
import sys
def parse_sections(lines):
"""Return {name: (start, end)} for .text/.data/.bss."""
sections = {}
# GSPLNK allocation lines: name page origin length [attributes]
for line in lines:
m = re.match(
r"^\s*(\.\w+)\s+\d+\s+([0-9A-Fa-f]+)\s+([0-9A-Fa-f]+)\b",
line)
if not m:
continue
origin = int(m.group(2), 16)
length = int(m.group(3), 16)
sections[m.group(1)] = (origin, origin + length)
if sections:
return sections
# tms-link map: "ADDR .text" / "ADDR etext" style symbol addresses.
starts, ends = {}, {}
for line in lines:
m = re.match(
r"^\s*([0-9A-Fa-f]+)\s+(\.\w+|etext|edata|end)\s*$", line)
if not m:
continue
addr = int(m.group(1), 16)
name = m.group(2)
if name in (".text", ".data", ".bss"):
starts[name] = addr
else:
ends[name] = addr
for name, endname in ((".text", "etext"), (".data", "edata"),
(".bss", "end")):
if name in starts and endname in ends:
sections[name] = (starts[name], ends[endname])
return sections
def main():
if len(sys.argv) not in (3, 7):
print(__doc__, file=sys.stderr)
return 2
map_path = sys.argv[1]
marker = int(sys.argv[2], 16)
marker_end = marker + 8 * 0x20
regions = None
if len(sys.argv) == 7:
prog_origin, prog_len, ram_origin, ram_len = (
int(v, 16) for v in sys.argv[3:7])
regions = (prog_origin, prog_origin + prog_len,
ram_origin, ram_origin + ram_len)
with open(map_path, encoding="ascii", errors="replace") as f:
sections = parse_sections(f.read().splitlines())
missing = [s for s in (".text", ".data", ".bss") if s not in sections]
if missing:
print(
"i64div perf map: cannot find %s in %s"
% (", ".join(missing), map_path),
file=sys.stderr)
return 2
ok = True
for name in (".text", ".data", ".bss"):
lo, hi = sections[name]
if marker < hi and marker_end > lo:
print(
"i64div perf map: markers 0x%08X..0x%08X overlap %s "
"0x%08X..0x%08X" % (marker, marker_end, name, lo, hi),
file=sys.stderr)
ok = False
if regions is not None:
prog_lo, prog_hi, ram_lo, ram_hi = regions
for name in (".text", ".data"):
lo, hi = sections[name]
if lo < prog_lo or hi > prog_hi:
print(
"i64div perf map: %s 0x%08X..0x%08X is outside prog "
"0x%08X..0x%08X" % (name, lo, hi, prog_lo, prog_hi),
file=sys.stderr)
ok = False
lo, hi = sections[".bss"]
if lo < ram_lo or hi > ram_hi:
print(
"i64div perf map: .bss 0x%08X..0x%08X is outside ram "
"0x%08X..0x%08X" % (lo, hi, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if marker < ram_lo or marker_end > ram_hi:
print(
"i64div perf map: markers 0x%08X..0x%08X are outside ram "
"0x%08X..0x%08X" % (marker, marker_end, ram_lo, ram_hi),
file=sys.stderr)
ok = False
if not ok:
return 1
extents = ", ".join(
"%s 0x%08X..0x%08X" % (name, sections[name][0], sections[name][1])
for name in (".text", ".data", ".bss"))
print(
"i64div perf map: %s; markers 0x%08X..0x%08X outside every section"
% (extents, marker, marker_end))
if regions is not None:
print(
"i64div perf map: markers inside ram 0x%08X..0x%08X"
% (regions[2], regions[3]))
return 0
if __name__ == "__main__":
sys.exit(main())
+117
View File
@@ -0,0 +1,117 @@
-- i64div-perf-check.lua -- measure the M7.4 i64 divide/remainder fast path in
-- MAME.
--
-- Loads the gate COFF with vendor/vt1200/dwt/loader/loader.lua (through the
-- M4_LOADER_LUA variable scripts/m4/run.sh exports) and polls the marker
-- words once per frame. A MAME frame is a fixed number of emulated 50 MHz
-- cycles, so the number of frames between the start marker and each phase's
-- completion marker is a reproducible cycle proxy for the equal-iteration
-- workloads in scripts/m7/i64div-perf.c:
--
-- fast phase: 16384 iterations, every divide fits 32 bits -> one DIVU each;
-- slow phase: 16384 iterations, nonzero high words -> the 64-step loop.
--
-- The gate requires the fast phase to complete in materially fewer frames
-- (slow_frames >= 8 * max(fast_frames, 1)) and the slow phase to be long
-- enough to measure (>= 20 frames). A sub-frame fast phase is reported as
-- fast_frames=0 and compared as one frame, which can only make the check
-- harder.
--
-- Both phase checksums are required to equal the deterministic values below.
-- They were computed from the same LCG/arithmetic with an independent host
-- implementation of scripts/m7/i64div-perf.c (see the header comment there):
-- fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE.
-- The in-image self-check (marker 7) also covers large 32-bit magnitudes
-- (0xFFFFFFFF/7, -123/7 and INT32_MIN/3), so a wrong fast quotient or
-- remainder fails before the timing comparison.
--
-- Markers at 01A20000h, 0x20 bits apart (free RAM above the 4 KiB entry stack;
-- scripts/m7/i64div-map-check.py asserts they are outside .text/.data/.bss):
-- 0 start 0x51A47A11 | 1/2 fast checksum | 3 fast done 0xFA57D01E
-- 4/5 slow checksum | 6 slow done 0x5104D0E5 | 7 status 0x600D600D
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "4000")
local BASE = 0x01A20000
local START = 0x51A47A11
local FAST_DONE = 0xFA57D01E
local SLOW_DONE = 0x5104D0E5
local STATUS_OK = 0x600D600D
local FAST_HI, FAST_LO = 0x00000001, 0x1E6F9AB4
local SLOW_HI, SLOW_LO = 0x00000000, 0x007512AE
local frames = 0
local start_f, fast_f, slow_f
local reported = false
local function rd(n)
local prog = manager.machine.devices[':maincpu'].spaces['program']
return prog:read_u32(BASE + n * 0x20)
end
emu.register_frame_done(function()
frames = frames + 1
if start_f == nil and rd(0) == START then
start_f = frames
end
if start_f ~= nil and fast_f == nil and rd(3) == FAST_DONE then
fast_f = frames
end
if fast_f ~= nil and slow_f == nil and rd(6) == SLOW_DONE then
slow_f = frames
end
if slow_f ~= nil and not reported then
reported = true
local fast_frames = fast_f - start_f
local slow_frames = slow_f - fast_f
local basis = fast_frames
if basis < 1 then
basis = 1
end
local status = rd(7)
local cs_fast_hi, cs_fast_lo = rd(2), rd(1)
local cs_slow_hi, cs_slow_lo = rd(5), rd(4)
local ratio = slow_frames / basis
local cs_ok = cs_fast_hi == FAST_HI and cs_fast_lo == FAST_LO
and cs_slow_hi == SLOW_HI and cs_slow_lo == SLOW_LO
local ok = status == STATUS_OK and cs_ok
and slow_frames >= 20
and slow_frames >= 8 * basis
print(string.format(
"M7: i64div perf: start=%d fast_done=%d slow_done=%d "
.. "fast_frames=%d slow_frames=%d ratio=%.1f "
.. "status=%08X cs_fast=%08X%08X cs_slow=%08X%08X "
.. "cs_expected=%08X%08X/%08X%08X cs=%s",
start_f, fast_f, slow_f, fast_frames, slow_frames, ratio,
status, cs_fast_hi, cs_fast_lo, cs_slow_hi, cs_slow_lo,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO,
cs_ok and "ok" or "BAD"))
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (status=%08X checksums=%s "
.. "fast_frames=%d slow_frames=%d; want status %08X, "
.. "fast %08X%08X, slow %08X%08X, slow_frames >= 20 "
.. "and >= 8*max(fast_frames,1))",
status, cs_ok and "ok" or "BAD",
fast_frames, slow_frames, STATUS_OK,
FAST_HI, FAST_LO, SLOW_HI, SLOW_LO))
end
elseif frames == ENDF - 1 and not reported then
reported = true
local seen = string.format(
"start=%s fast_done=%s slow_done=%s",
tostring(start_f), tostring(fast_f), tostring(slow_f))
print(string.format(
"M7: i64div perf: incomplete at frame %d at marker 0x%08X",
frames, BASE))
print("M7 MAME: FAIL (timed out: " .. seen .. ")")
end
end, "i64div-perf-check")
+19
View File
@@ -0,0 +1,19 @@
; i64div-perf-entry.asm -- M7.4 i64 divide/remainder performance gate entry,
; linked at bit 018A0000 by scripts/tests/m7/i64div.sh through
; scripts/m4/run.sh.
;
; Sets the TI C field sizes, points STK/FP at the gate stack and calls
; i64div_perf_run(), which writes the phase markers and returns. The loader
; harness inspects the markers at LOADER_END-1, so no post-return sentinel is
; needed; the program's last marker write is the slow-phase completion flag.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64div_perf_run
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+193
View File
@@ -0,0 +1,193 @@
/* M7.4 i64 divide/remainder fast-path performance driver.
*
* Two equal-iteration workloads exercise the two paths of
* TMS34010LowerI64::lowerDivRem:
*
* fast phase: both operands fit 32 bits after the signed magnitude
* normalization, so the compiler emits one 32-bit DIVU (plus
* the div/mul/sub remainder reconstruction) instead of the
* 64-step restoring loop;
* slow phase: the operands have nonzero high words, so the 64-step loop
* runs for each of the four i64 div/rem forms.
*
* The loop bodies are driven by a volatile iteration count and volatile
* seeds, and every result feeds a volatile accumulator that is published in
* the marker words, so neither phase can be constant-folded or discarded.
*
* Markers (0x20 bits apart at 01A20000h, the free RAM area above the 4 KiB
* entry stack at 01A00000h; outside .text/.data/.bss, see
* scripts/m7/i64div-map-check.py):
* 0 start 0x51A47A11
* 1 fast checksum low (printed evidence)
* 2 fast checksum high
* 3 fast phase done 0xFA57D01E
* 4 slow checksum low (printed evidence)
* 5 slow checksum high
* 6 slow phase done 0x5104D0E5
* 7 self-check status 0x600D600D on success
*
* The self-check runs known i64 divisions first (fast and slow, unsigned and
* signed, including full-width low words and the INT32_MIN magnitude), so the
* timing comparison is between two correct paths rather than between a
* fast-but-wrong path and the loop. scripts/m7/i64div-perf-check.lua polls
* the markers once per MAME frame, turns the frame numbers into the gate's
* cycle proxy, and requires the exact phase checksums. With the 16384
* iterations above the deterministic LCG workloads produce
* fast = 0x000000011E6F9AB4, slow = 0x00000000007512AE
* (checked against an independent host implementation of this file; the
* target compiler must produce the same integer results).
*/
typedef unsigned int u32;
typedef int s32;
typedef unsigned long long u64;
typedef long long s64;
#define MARK(n) (*(volatile u32 *)(0x01A20000u + (u32)(n) * 0x20u))
#define PERF_START 0x51A47A11u
#define PERF_FAST_DONE 0xFA57D01Eu
#define PERF_SLOW_DONE 0x5104D0E5u
#define PERF_STATUS_OK 0x600D600Du
#define PERF_STATUS_BAD 0xBAD0BAD0u
/* 16384 iterations put the fast phase at a few frames and the slow phase at a
* few hundred frames on the emulated 50 MHz part, with a wide margin under
* the 4000-frame loader budget. The count is volatile so the optimizer keeps
* a real loop and does not unroll it into a folded constant. */
static volatile u32 perf_iters = 16384u;
/* Seeds are volatile for the same reason: the divisions must really execute. */
static volatile u64 seed_a = 0x0000000012345678ull;
static volatile u64 seed_b = 0x000000009ABCDEF1ull;
/* Known-value inputs (values pinned by the M6 i64 gate). */
static volatile u64 sc_n1 = 0x123456789ABCDEF0ull;
static volatile u64 sc_d1 = 0x0000000000001234ull;
static volatile u64 sc_d2 = 0x0000000123456789ull;
static volatile s64 sc_n3 = -1000000000000ll;
static volatile s64 sc_d3 = 7ll;
static volatile s64 sc_n4 = 123ll;
static volatile s64 sc_d4 = -7ll;
/* Fast-path cases with large low words: the high word is zero (or the value
* is a negative 32-bit value whose magnitude still fits), so the quotient and
* remainder must come from the 32-bit DIVU, not the loop. */
static volatile u64 sc_max32 = 0xFFFFFFFFull;
static volatile u64 sc_seven = 7ull;
static volatile s64 sc_neg123 = -123ll;
static volatile s64 sc_int32min = -2147483648ll;
static volatile s64 sc_three = 3ll;
static u32 lcg(u32 x)
{
return x * 1103515245u + 12345u;
}
/* Known-value checks for both paths, unsigned and signed, including the
* full-width low words and INT32_MIN. */
static u32 selfcheck(void)
{
u64 q, r;
s64 sq, sr;
u32 ok = 1;
q = sc_n1 / sc_d1;
r = sc_n1 % sc_d1;
ok &= (q == 0x00010004C016906Bull) && (r == 0x334ull);
/* Divisor above 32 bits: the restoring loop. */
q = sc_n1 / sc_d2;
r = sc_n1 % sc_d2;
ok &= (q == 0x0000000010000000ull) && (r == 0x0ABCDEF0ull);
/* Both signed values fit after normalization: the signed fast path. */
sq = sc_n4 / sc_d4;
sr = sc_n4 % sc_d4;
ok &= (sq == -17ll) && (sr == 4ll);
/* Fast paths with large low words. A wrong 32-bit quotient/remainder
* for a full-width magnitude (or for INT32_MIN's magnitude 2^31) must
* fail here before the timing comparison. */
q = sc_max32 / sc_seven;
r = sc_max32 % sc_seven;
ok &= (q == 0x0000000024924924ull) && (r == 3ull);
/* sc_d3 is the signed 7: sc_seven is u64, so mixing it with a negative
* s64 would make the comparison unsigned (the same C conversion the
* target performs). */
sq = sc_neg123 / sc_d3;
sr = sc_neg123 % sc_d3;
ok &= (sq == -17ll) && (sr == -4ll);
sq = sc_int32min / sc_three;
sr = sc_int32min % sc_three;
ok &= (sq == -715827882ll) && (sr == -2ll);
/* A large signed dividend: the signed slow path. */
sq = sc_n3 / sc_d3;
sr = sc_n3 % sc_d3;
ok &= (sq == -142857142857ll) && (sr == -1ll);
return ok ? PERF_STATUS_OK : PERF_STATUS_BAD;
}
/* Small operands: the high words are zero, so the four divisions take the
* 32-bit fast path. The signed forms cast a 32-bit value to i64; a negative
* value still has a 32-bit magnitude, so it also takes the fast path. */
static void run_fast(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = (u64)(lcg((u32)a) & 0x7FFFFFFFu) + 1u;
b = (u64)(lcg((u32)b) & 0x0000FFFFu) + 1u;
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)(s32)a / (s64)(s32)b);
acc ^= (u64)((s64)(s32)a % (s64)(s32)b);
}
MARK(1) = (u32)acc;
MARK(2) = (u32)(acc >> 32);
MARK(3) = PERF_FAST_DONE;
}
/* Nonzero high words in both operands: all four forms take the 64-step
* restoring loop. The same iteration count as the fast phase makes the frame
* counts directly comparable. */
static void run_slow(void)
{
u64 acc = 0;
u64 a = seed_a;
u64 b = seed_b;
u32 n = perf_iters;
u32 i;
for (i = 0; i < n; i++) {
a = ((u64)(1u + (lcg((u32)(a >> 32)) & 0xFFFFu)) << 32)
| (u64)(lcg((u32)a) | 1u);
b = ((u64)(1u + (lcg((u32)(b >> 32)) & 0x00FFu)) << 32)
| (u64)(lcg((u32)b) | 1u);
acc += a / b;
acc ^= a % b;
acc += (u64)((s64)a / (s64)b);
acc ^= (u64)((s64)a % (s64)b);
}
MARK(4) = (u32)acc;
MARK(5) = (u32)(acc >> 32);
MARK(6) = PERF_SLOW_DONE;
}
void i64div_perf_run(void)
{
MARK(7) = selfcheck();
MARK(0) = PERF_START;
run_fast();
run_slow();
}
+11
View File
@@ -0,0 +1,11 @@
/* M7.2 long-public-name gate, TU A.
*
* The public function name is 44 characters (45 with the C `_` prefix),
* longer than GSPA 2.00's 31-character symbol limit. The object path keeps it
* intact; tms-link resolves the cross-TU reference from longname-b.c and writes
* the full name into its map.
*/
int tms34010_public_function_name_longer_than_31(void) {
return 42;
}
+12
View File
@@ -0,0 +1,12 @@
/* M7.2 long-public-name gate, TU B.
*
* Declares and calls the 44-character public function from longname-a.c. The
* call is a normal undefined-external R-RELLONG in this object; tms-link
* resolves it to TU A's definition without truncating either name.
*/
int tms34010_public_function_name_longer_than_31(void);
int longname_call(void) {
return tms34010_public_function_name_longer_than_31() + 1;
}
+21
View File
@@ -0,0 +1,21 @@
; longname-entry.asm -- M7.2 long-public-name gate entry, linked at 018A0000.
;
; Calls the short-named TU B wrapper (which calls the 44-character public
; function in TU A) and stores its result, 43, at 018A8000. GSPA never sees
; the long name: it only assembles the short `_longname_call` reference, so
; the gate exercises tms-link's long-name symbol resolution rather than GSPA's
; 31-character truncation.
.ref _longname_call
.text
.globl _start
_start:
setf 16,1,0
setf 32,0,1
movi _cstack,a14
move a14,a13
calla _longname_call
move a8,@018A8000h,1
rets
.bss _cstack,32768,16
.end
+149
View File
@@ -0,0 +1,149 @@
-- xmore-check.lua -- load the M7.3 wider-Xlib COFF with dwt/loader/loader.lua,
-- then prove the markers and the window pixels.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame (default 3400)
--
-- Markers (0x20 bits apart, read at LOADER_END-1):
-- 018A8000 parent Window id, nonzero
-- 018A8020 child Window id, nonzero
-- 018A8040 gc GC pointer, nonzero
-- 018A8060 atom XInternAtom("WM_NAME"): nonzero atom, or
-- 0xFFFFFFFF documented skip (the ROM _XSend path
-- that carries the name does not complete here)
-- 018A8080 property 1 after the XChangeProperty call site ran (no
-- server read-back; zero X errors is the only
-- runtime check)
-- 018A80A0 configure client-computed (child width << 16) | height
-- (0x00C80096); the move is pixel-proven, the size
-- is not read back
-- 018A80C0 font XLoadFont("fixed"), nonzero
-- 018A80E0 image (pixel << 8) | flags (0x13F when the full
-- XCreateImage/XGetImage/XPutImage/XDestroyImage
-- round trip worked: pixel=1 and flags=0x3F)
-- 018A8100 errors X protocol error count (0)
-- 018A8120 stage 14 = InternAtom attempted (skip), 15 = returned
-- 018A8140 attrs 1 after the XChangeWindowAttributes call site ran;
-- the real proof is the black CWBackPixel margin
-- (the ROM builder does not set A8)
-- 018A8160 gcchange XChangeGC source call count (2); runtime entry is
-- not proven, and the ROM entry is a cache flush
-- 018A8180 text set pixels in the XDrawString band (0,126) 64x16
-- 018A81A0 display Display pointer stored just before XInternAtom
-- 018A81C0 fill (FILL_W << 16) | FILL_H (0xA00078), pins the
-- margin sample's fill geometry
--
-- Geometry: parent at screen (100,100) 400x300 (the WM leaves a top-level
-- client window at its requested origin, as the M4 xshow gate proves), child
-- configured to (20,20) 200x150. The child is created with background 1
-- (white), then CWBackPixel=0 (black). The 160x120 black fill leaves a
-- right/bottom margin; screen (300,240) is in that margin, so it is black only
-- because of the window attribute (without it the child background is white).
-- The white rectangle is at child (0,0) 32x32 (screen 120,120), the heap image
-- at child (40,32) (screen 160,152; 32-bit aligned) and the XGetImage result
-- put back at child (104,32) (screen 224,152). The text is drawn at baseline
-- child (4,140) on the black margin, and the XGetImage band (child 0,126 64x16)
-- counts its white glyph pixels.
--
-- The printed "parent(...)" coordinate is screen minus the parent origin
-- (100,100), i.e. parent-relative, not child-relative (the child is at 20,20
-- inside the parent).
--
-- Pixel sampling reads the exact VRAM bit address (VR319: 2048-bit rows,
-- LSB-first), not a whole unaligned word. If XConfigureWindow did not move the
-- child from its created (40,40), the p_rect sample (screen 128,128) is outside
-- the child and p_back (screen 240,160) maps outside the put-back image; p_img
-- alone would still be white (it would land inside the 32x32 rectangle).
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local VRAM_BASE = 0x04000000
local VRAM_PITCH = 2048
local WIN_X, WIN_Y = 100, 100
local frames = 0
local checked = false
local function read_bit(prog, sx, sy)
local bit = VRAM_BASE + sy * VRAM_PITCH + sx
return prog:read_u16(bit) % 2, bit
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 14 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M7: window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14]))
local function sample(sx, sy, want)
local b, bit = read_bit(prog, sx, sy)
print(string.format(
"M7: pixel screen(%d,%d) parent(%d,%d) bit=0x%08X value=%d %s",
sx, sy, sx - WIN_X, sy - WIN_Y, bit, b,
b == 1 and "white" or "black"))
return b == want
end
-- (screen x, screen y, expected); parent-relative coordinates.
local p_rect = sample(128, 128, 1) -- parent (28,28): XFillRectangle
local p_img = sample(170, 162, 1) -- parent (70,62): heap XPutImage
local p_back = sample(240, 160, 1) -- parent (140,60): put back
local p_bg = sample(300, 240, 0) -- parent (200,140): CWBackPixel margin
local configure_want = 200 * 65536 + 150
local image_want = 0x13F
local atom_skip = (m[3] == 0xFFFFFFFF)
local atom_ok = (m[3] ~= 0 and m[3] ~= 0xFFFFFFFF
and m[3] ~= 0xFFFFFFFE)
local stage_ok = (atom_skip and m[9] == 14)
or (atom_ok and m[9] == 15)
local text_want_max = 64 * 16
local ok = m[0] ~= 0 and m[1] ~= 0 and m[2] ~= 0
and (atom_skip or atom_ok)
and m[4] == 1 and m[5] == configure_want and m[6] ~= 0
and m[7] == image_want and m[8] == 0 and stage_ok
and m[10] == 1 and m[11] == 2
and m[12] > 0 and m[12] < text_want_max
and m[13] ~= 0 and m[14] == 0xA00078
and p_rect and p_img and p_back and p_bg
print(string.format(
"M7: text band child(0,126) 64x16 set_pixels=%d (%s); "
.. "gcchange=%d (source call sites; runtime entry not proven); "
.. "attrs_called=%d; property_called=%d (call site ran, no "
.. "server read-back)",
m[12], (m[12] > 0 and m[12] < text_want_max) and "ok" or "BAD",
m[11], m[10], m[4]))
if atom_skip then
print("M7: internatom=SKIP (ROM _XSend scatter path blocks; "
.. "WM_NAME written with predefined atom 39; the display "
.. "marker only proves the connection was live before the "
.. "call; the isolated probe is narrative entry evidence)")
elseif atom_ok then
print(string.format("M7: internatom=0x%X", m[3]))
end
if ok then
print("M7 MAME: PASS")
else
print(string.format(
"M7 MAME: FAIL (window=0x%X child=0x%X gc=0x%X atom=0x%X property_called=%d configure=0x%X font=0x%X image=0x%X errors=%d stage=%d attrs_called=%d gcchange=%d text=%d display=0x%X fill=0x%X; pixels rect=%s image=%s putback=%s margin=%s)",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11], m[12], m[13], m[14],
tostring(p_rect), tostring(p_img), tostring(p_back),
tostring(p_bg)))
end
end
end, "xmore-check")
+25
View File
@@ -0,0 +1,25 @@
; xmore-entry.asm -- M7.3 wider-Xlib client entry, linked at bit 018A0000.
;
; Installs the TI all-stack ABI fields and the 4 KiB stack, then calls the
; compiled xmore() client. Markers (0x20 bits apart):
; 018A8000 parent nonzero
; 018A8020 child nonzero
; 018A8040 gc nonzero
; 018A8060 atom WM_NAME atom, or 0xFFFFFFFF documented skip
; 018A8080 property post-call flag, 1 (no server read-back)
; 018A80A0 configure (width << 16) | height (client-computed; move pixel-proven)
; 018A80C0 font XLoadFont("fixed") handle
; 018A80E0 image (pixel << 8) | round-trip flags
; 018A8100 errors 0
; 018A8120 stage last completed step (14 skip, 15 atom returned)
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _xmore
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+456
View File
@@ -0,0 +1,456 @@
/*
* xmore.c -- the M7.3 wider VT1200 Xlib surface client.
*
* The client opens the ROM X display, builds one parent window and one child
* window, maps the children with XMapSubwindows, moves/resizes the child with
* the ROM's fixed-mask XConfigureWindow builder, writes the parent's WM_NAME
* property (XChangeProperty), changes the child's background with
* XChangeWindowAttributes, changes the GC foreground with XChangeGC, loads a
* font and draws text (XLoadFont + XDrawString) and a rectangle, and performs
* a heap image round trip: XCreateImage with malloc'd bytes, XPutImage,
* XGetImage of the same region, a second XPutImage of the returned image, then
* XDestroyImage on both. XInternAtom("WM_NAME") is the last surface call.
*
* The child is created with background 1 (white) and then given
* CWBackPixel=0 (black); the 160x120 black fill leaves a right/bottom margin
* that only the window attribute can make black. The text is drawn on that
* margin and its pixels are counted from an XGetImage band.
*
* Markers live at 0x018A8000 + n*0x20 (bit addresses):
* 0 parent Window id (nonzero)
* 1 child Window id (nonzero; the XMapSubwindows child)
* 2 gc GC pointer (nonzero)
* 3 atom XInternAtom("WM_NAME") result:
* nonzero the call returned the atom
* 0xFFFFFFFF the call was attempted but blocked; the
* surface is kept and the skip is explicit
* 0xFFFFFFFE the call returned None
* 4 property 1 after the XChangeProperty call site ran (no server
* read-back; the zero X-error count is the only runtime
* check)
* 5 configure client-computed (child width << 16) | child height; the
* move is pixel-proven, the size is not read back
* 6 font XLoadFont("fixed") handle (nonzero; the GC uses the
* server default font, see the CreateGC note below)
* 7 image (get_pixel << 8) | flags:
* 0x01 XCreateImage, 0x02 XGetImage returned an image,
* 0x04 the XGetImage pixel word was all white,
* 0x08 XPutImage of the returned image,
* 0x10 XDestroyImage both images,
* 0x20 XGetImage was usable (not skipped)
* all six flags plus a white pixel is 0x13F
* 8 errors X protocol error count (0)
* 9 stage last completed step (14 = XInternAtom attempted after
* everything else; 15 = it returned and the property was
* rewritten with that atom)
* 10 attrs 1 after the XChangeWindowAttributes call site ran; the
* real proof is the black CWBackPixel margin sampled by the
* gate (the ROM builder does not set A8)
* 11 gcchange count of XChangeGC source call sites (2). The ROM entry is
* the 2-arg GC-cache flush; this counts the calls in source,
* not their runtime entry.
* 12 text set pixels counted in the XDrawString band (64x16 at
* child 0,126) after XGetImage; must be > 0 and below the
* band size
* 13 display Display pointer stored just before XInternAtom; proves the
* connection was live at the pre-call marker, not that the
* call was entered
* 14 fill (FILL_W << 16) | FILL_H, so the hard-coded margin sample
* cannot silently become vacuous if the fill changes
*
* The image marker distinguishes a usable XGetImage (0x13F) from a failed or
* skipped one; a failed call clears IMG_USABLE and the gate names it.
*
* XInternAtom is deliberately last. The ROM's _XSend (0x3F9B44C0) is the
* scatter/service-write path used for InternAtom's name bytes (and for
* XPutImage's direct-send path); the M4 xshow client already records that
* this path does not make progress in the loader harness. The call is kept in
* the surface, and marker 3 records the documented skip instead of dropping
* it. The WM_NAME property is therefore written first with the predefined
* X11R4 atom XA_WM_NAME (39), which the server knows without an InternAtom.
* If XInternAtom does return (the real unit), the client rewrites the property
* with the returned atom and advances to stage 15.
*
* Two ROM/Xlib details matter:
* - XChangeProperty copies the value bytes with the ROM blitter entry
* blit_copy (0x3FB44400), just as _XPutImage does. A loader child starts
* with a zeroed blitter context, so prime it once before the property.
* - The ROM XChangeGC entry is (display, gc): it serializes the GC value
* cache that XSetForeground/XSetFont marked dirty. The drawing
* primitives call the same serializer, but the explicit call is what the
* gate exercises.
*/
#include "x11m4.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
#define PARENT_X 100
#define PARENT_Y 100
#define PARENT_W 400
#define PARENT_H 300
/* Created at (40,40) 240x160, then configured to (20,20) 200x150. */
#define CHILD_X 20
#define CHILD_Y 20
#define CHILD_W 200
#define CHILD_H 150
#define IMG_W 64
#define IMG_H 64
#define IMG_BPL (IMG_W / 8)
/* The black fill leaves a margin so the CWBackPixel background is visible. */
#define FILL_W 160
#define FILL_H 120
/* XDrawString("xmore") at baseline (4,140), on the black bottom margin. */
#define TEXT_X 4
#define TEXT_Y 140
#define TEXT_LEN 5
#define TEXT_BAND_X 0
#define TEXT_BAND_Y 126
#define TEXT_BAND_W 64
#define TEXT_BAND_H 16
#define XA_STRING 31
#define XA_WM_NAME 39
#define PropModeReplace 0
#define INTERNATOM_SKIPPED 0xFFFFFFFFu
#define INTERNATOM_NONE 0xFFFFFFFEu
/*
* The wider-surface ABI, pinned here so a header edit cannot silently change
* the offsets the ROM request builders read (X11R4 32-bit structs: 4-byte
* fields). XWindowChanges.width=8; XSetWindowAttributes.background_pixel=4
* (CWBackPixel); XGCValues.font=60 (GCFont; the ROM walker reads byte 60).
*/
_Static_assert(__builtin_offsetof(XWindowChanges, width) == 8,
"XWindowChanges.width must be at byte 8");
_Static_assert(__builtin_offsetof(XSetWindowAttributes, background_pixel) == 4,
"XSetWindowAttributes.background_pixel must be at byte 4");
_Static_assert(__builtin_offsetof(XGCValues, font) == 60,
"XGCValues.font must be at byte 60");
#define IMG_CREATED 0x01
#define IMG_GOT 0x02
#define IMG_PIXEL 0x04
#define IMG_PUT 0x08
#define IMG_DESTROYED 0x10
#define IMG_USABLE 0x20
/* The ROM allocator (symbols/vt1200-v22.syms: malloc/free). */
extern void *malloc(unsigned int size);
extern void free(void *p);
static int xerrors;
/* The two explicit XChangeGC call sites (marker 11). */
static unsigned int gc_changes;
static int on_error(Display *d, XErrorEvent *e) {
(void)d;
(void)e;
xerrors++;
return 0;
}
/* The ROM sleep through a function pointer, as the M4 client does. */
static int (*volatile vt_sleep)(int) = sleep;
/* XImage.data is heap memory here, so the ROM destructor may free it. */
static XImage *heap_image;
/*
* The blitter is process-global and starts zeroed in a loader child. Prime
* it with a four-byte self-copy before XChangeProperty's value copy.
*/
static void prime_blitter(void) {
static unsigned int word;
blit_copy(&word, &word, 4);
}
static void clear_black(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 0);
XChangeGC(d, gc);
gc_changes++;
/* Leave the child's right/bottom margin to the CWBackPixel background. */
XFillRectangle(d, w, gc, 0, 0, FILL_W, FILL_H);
}
static void draw_white(Display *d, Window w, GC gc) {
XSetForeground(d, gc, 1);
XChangeGC(d, gc);
gc_changes++;
/* The drawing call and the text call, both after the GC change. The
* text sits on the black CWBackPixel margin so its pixels are countable. */
XFillRectangle(d, w, gc, 0, 0, 32, 32);
XDrawString(d, w, gc, TEXT_X, TEXT_Y, "xmore", TEXT_LEN);
}
/*
* Prove XDrawString with pixels: XGetImage the text band and count set bits.
* The band is black CWBackPixel background; white glyphs make the count
* nonzero. A solid white count (>= the band size) would mean the band was not
* contrasting, so the gate also requires it below the band size.
*/
static void text_pixels(Display *d, Window w) {
XImage *im = XGetImage(d, w, TEXT_BAND_X, TEXT_BAND_Y, TEXT_BAND_W,
TEXT_BAND_H, ~0L, XYPixmap);
unsigned int count = 0;
int y, x;
if (!im) {
MARK(12) = 0;
return;
}
if (im->data) {
for (y = 0; y < TEXT_BAND_H; y++) {
unsigned int *row = (unsigned int *)(void *)(im->data +
y * im->bytes_per_line);
for (x = 0; x < (TEXT_BAND_W / 8) / 4; x++) {
unsigned int v = row[x];
while (v) {
count += v & 1u;
v >>= 1;
}
}
}
}
MARK(12) = count;
XDestroyImage(im);
}
static void image_roundtrip(Display *d, Window w, GC gc) {
char *bytes;
XImage *got;
unsigned int flags = 0;
unsigned int pixel = 0;
int i;
int destroyed = 0;
bytes = (char *)malloc(IMG_BPL * IMG_H);
if (bytes) {
unsigned int *words = (unsigned int *)bytes;
for (i = 0; i < (IMG_BPL * IMG_H) / 4; i++)
words[i] = 0xFFFFFFFFu;
}
heap_image = XCreateImage(d, 0, 1, XYBitmap, 0, bytes, IMG_W, IMG_H, 32,
IMG_BPL);
if (!heap_image) {
if (bytes)
free(bytes);
MARK(7) = 0;
return;
}
flags |= IMG_CREATED;
heap_image->byte_order = LSBFirst;
heap_image->bitmap_bit_order = LSBFirst;
/* A 32-bit-aligned destination x (screen 100+20+40 = 160) is required by
* the server's 1-bit bitmap copy path, as the M4 xshow client found. */
if (XPutImage(d, w, gc, heap_image, 0, 0, 40, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
XSync(d, 0);
got = XGetImage(d, w, 40, 32, IMG_W, IMG_H, ~0L, XYPixmap);
if (!got) {
/* The call ran and failed. Destroy our half of the surface and leave
* the caller's stage at 12 (the text-pixel step), so the check names
* XGetImage. */
if (XDestroyImage(heap_image))
flags |= IMG_DESTROYED;
heap_image = 0;
MARK(7) = flags;
return;
}
flags |= IMG_GOT | IMG_USABLE;
/* The region is all white: the first 32 bits of row 0 are all ones. */
if (got->data && *(unsigned int *)(void *)got->data == 0xFFFFFFFFu) {
flags |= IMG_PIXEL;
pixel = 1;
}
/* Put the returned heap image back at child x=104 (screen 224). */
if (XPutImage(d, w, gc, got, 0, 0, 104, 32, IMG_W, IMG_H))
flags |= IMG_PUT;
if (XDestroyImage(got))
destroyed++;
if (XDestroyImage(heap_image))
destroyed++;
heap_image = 0;
if (destroyed == 2)
flags |= IMG_DESTROYED;
MARK(7) = (pixel << 8) | flags;
}
int xmore(void) {
Display *d;
Window root;
Window parent;
Window child;
GC gc;
Font font;
XSetWindowAttributes attrs = {0};
XWindowChanges wc;
int tries;
int i;
for (i = 0; i <= 14; i++)
MARK(i) = 0;
if (!vt_install_xg())
return -1;
d = 0;
for (tries = 0; tries < 40; tries++) {
d = XOpenDisplay("0::0");
if (d)
break;
vt_sleep(50);
}
if (!d)
return -1;
MARK(9) = 1;
XSetErrorHandler(on_error);
prime_blitter();
root = vt_root(d);
parent = XCreateSimpleWindow(d, root, PARENT_X, PARENT_Y, PARENT_W,
PARENT_H, 0, 0, 0);
MARK(0) = (unsigned)parent;
/* Background 1 (white) at creation: CWBackPixel must make it black. */
child = XCreateSimpleWindow(d, parent, 40, 40, 240, 160, 0, 0, 1);
MARK(1) = (unsigned)child;
MARK(9) = 2;
/* opcode 9: map both the parent's children (the child above). */
XMapSubwindows(d, parent);
MARK(9) = 3;
/*
* opcode 12 with the ROM's fixed CWX|CWY|CWWidth|CWHeight mask. The
* XWindowChanges record holds the same four values; the X11R4 client
* API's mask is implied by the entry.
*/
wc.x = CHILD_X;
wc.y = CHILD_Y;
wc.width = CHILD_W;
wc.height = CHILD_H;
wc.border_width = 0;
wc.sibling = 0;
wc.stack_mode = 0;
XConfigureWindow(d, child, wc.x, wc.y, (unsigned int)wc.width,
(unsigned int)wc.height);
/*
* The configure marker is client-computed: it records the four values
* passed to the ROM builder. The move is pixel-proven below; the size is
* not read back from the server.
*/
MARK(5) = ((unsigned int)wc.width << 16) | (unsigned int)wc.height;
MARK(9) = 4;
/*
* The property value first goes through the predefined XA_WM_NAME atom,
* so the XChangeProperty surface is exercised even if XInternAtom cannot
* complete below. Marker 4 is a plain post-call flag: the ROM builder
* never sets A8, so there is no return value or server read-back; zero X
* errors is the only runtime check.
*/
XChangeProperty(d, parent, XA_WM_NAME, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 5;
/* The struct was zero-initialized at its declaration; only
* CWBackPixel's byte 4 is selected here. */
attrs.background_pixel = 0;
XChangeWindowAttributes(d, child, CWBackPixel, &attrs);
/* Post-call flag only; the black margin is the real attribute proof. */
MARK(10) = 1;
MARK(9) = 6;
/*
* Map the top-level parent after the child is mapped, then let the WM
* frame it before drawing: an X11 map fills the background and would
* erase anything drawn while the window is still unmapped.
*/
XMapWindow(d, parent);
XSync(d, 0);
vt_sleep(300);
MARK(9) = 7;
font = XLoadFont(d, "fixed");
MARK(6) = (unsigned)font;
MARK(9) = 8;
/*
* The GC uses the server's default font. XLoadFont is still exercised
* above (marker 6); its returned value is a ROM font handle, not the
* server font XID, so passing it as GCFont makes CreateGC fail BadFont.
* The default GC font is the 6x13 cell the termtris client documents.
*/
gc = XCreateGC(d, child, 0, 0);
MARK(2) = (unsigned)gc;
MARK(9) = 9;
clear_black(d, child, gc);
MARK(9) = 10;
draw_white(d, child, gc);
MARK(9) = 11;
/* XGetImage the text band and count its white pixels (marker 12). */
text_pixels(d, child);
MARK(9) = 12;
image_roundtrip(d, child, gc);
/* Only a usable XGetImage advances the image stage. */
if ((MARK(7) & IMG_USABLE) != 0) {
XSync(d, 0);
MARK(8) = (unsigned)xerrors;
MARK(9) = 13;
} else {
MARK(8) = (unsigned)xerrors;
}
/*
* Last: the InternAtom surface. The skip marker and the live Display
* pointer are written before the call so a blocked _XSend still leaves
* the documented state behind. The marker proves only that the
* connection was live before the call; entry into the ROM function is
* not proven by it (the report's isolated probe is narrative evidence).
*/
MARK(13) = (unsigned)d;
MARK(11) = gc_changes;
MARK(14) = ((unsigned)FILL_W << 16) | (unsigned)FILL_H;
MARK(3) = INTERNATOM_SKIPPED;
MARK(9) = 14;
{
Atom a = XInternAtom(d, "WM_NAME", False);
if (a) {
MARK(3) = (unsigned)a;
XChangeProperty(d, parent, a, XA_STRING, 8, PropModeReplace,
(const unsigned char *)"xmore", 5);
MARK(4) = 1;
MARK(9) = 15;
} else {
MARK(3) = INTERNATOM_NONE;
}
}
/*
* Do not return: returning tears the process (and its windows) down before
* the harness reads the markers and VRAM. Keep the connection drained and
* hold the last completed stage so a failed call stays visible.
*/
for (;;) {
MARK(8) = (unsigned)xerrors;
MARK(11) = gc_changes;
XFlush(d);
vt_sleep(5);
}
}
+6
View File
@@ -3,3 +3,9 @@ int int_diff4(int *p) { return (int)(p + 1) - (int)p; }
long pd_char(char *a, char *b) { return a - b; }
long pd_int(int *a, int *b) { return a - b; }
int late(char *p, char *q) { return (char *)((unsigned)p + 24) == q; }
int late64(char *p, char *q) {
return (char *)((unsigned long long)(unsigned)p + 24) == q;
}
int late64s(char *p, char *q) {
return (char *)((long long)(int)p + 24) == q;
}
+35 -3
View File
@@ -13,14 +13,46 @@ grep -A2 'define.*@int_diff(' "$OUT/pdiff.ll" | grep -q 'ret i32 8'
grep -A2 'define.*@int_diff4' "$OUT/pdiff.ll" | grep -q 'ret i32 32'
grep -A6 'define.*@pd_char' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -A6 'define.*@pd_int' "$OUT/pdiff.ll" | grep -Eq 'sdiv|ashr|udiv'
grep -Eq 'add i32 %bit.base[0-9]*, 24' "$OUT/pdiff.ll"
# The final instcombine canonicalizes the lowered `inttoptr(add(ptrtoint, 24))`
# into `getelementptr i8, %p, 24`; llc treats a GEP index as a bit offset, so
# either shape carries the M0 24-bit addend. Scope the positive to `late`
# itself (the identical `late64` line must not satisfy it); keep the 192
# rejection file-wide.
grep -A6 'define.*@late(' "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192' \
"$OUT/pdiff.ll"; then
echo "M0 pipeline: FAIL: late GEP was scaled twice (192)" >&2
exit 1
fi
# The 64-bit pointer-int shapes (`(unsigned long long)(unsigned)p + 24` and
# `(long long)(int)p + 24`) must take the same 24-bit low word, not 192.
for fn in late64 late64s; do
grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 24|getelementptr i8, ptr %p, i32 24'
if grep -A6 "define.*@$fn(" "$OUT/pdiff.ll" \
| grep -Eq 'add i32 %bit\.base[0-9]*, 192|getelementptr i8, ptr %p, i32 192'; then
echo "M0 pipeline: FAIL: $fn over-scaled to 192" >&2
exit 1
fi
done
"$TMS_OPT" -passes=verify -disable-output "$OUT/pdiff.ll"
"$ROOT/scripts/tms-clang" -O2 -I "$ROOT/spike" -o "$OUT/xclient.ll" "$ROOT/spike/xclient.c"
test "$(grep -c getelementptr "$OUT/xclient.ll")" -eq 0
# The M7.1 barrier is gone after lowering, and any GEP the final instcombine
# creates from a lowered inttoptr is the `i8` bit-index form. A typed GEP here
# would mean a byte offset escaped the post-opt --scale.
if grep -q '__tms_bitptr' "$OUT/xclient.ll"; then
echo "M0 pipeline: FAIL: __tms_bitptr was not lowered" >&2
exit 1
fi
if grep 'getelementptr' "$OUT/xclient.ll" | grep -qv 'getelementptr i8'; then
echo "M0 pipeline: FAIL: a typed (byte) GEP escaped the post-opt scale" >&2
exit 1
fi
grep -Eq 'add i32 %bit.base[0-9]*, 1056' "$OUT/xclient.ll"
grep -Eq 'mul i32 [^,]+, 640' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit.addr[0-9]*, 320' "$OUT/xclient.ll"
grep -Eq 'add i32 %bit\.(base|addr)[0-9]*, 320' "$OUT/xclient.ll"
"$TMS_OPT" -passes=verify -disable-output "$OUT/xclient.ll"
"$ROOT/scripts/tms-clang" -O0 -o "$OUT/pdiff.o0.ll" "$ROOT/scripts/tests/m0/ptrdiff.c"
+3 -1
View File
@@ -98,7 +98,9 @@ check_insn urem SUB "unsigned remainder subtract"
check_insn squares MPYS "loop multiply"
# The driven loop must remain a loop (a backward branch), not a closed form.
if ! grep -Eq '^[[:space:]]*JA(LT|LE|GT|GE|LO|LS|HI|HS|EQ|NE)[[:space:]]' "$TMP/sumto.s"; then
# M5's JR relaxation may use the one-word relative form; both JA<cc> and JR<cc>
# keep the loop condition unchanged.
if ! grep -Eq '^[[:space:]]*J[AR](LT|LE|GT|GE|LO|LS|HI|HS|EQ|NE)[[:space:]]' "$TMP/sumto.s"; then
sed 's/^/ /' "$TMP/sumto.s" >&2
fail "_sumto has no conditional branch (loop was not kept)"
fi
+15 -7
View File
@@ -2,6 +2,9 @@
# M4 termtris gate: build the pinned termtris with this compiler, run the
# proven play_keys paths in MAME (board, move, panels, quit), and enforce the
# loop/event/quit/focus thresholds and the four snapshots.
#
# TERMTRIS_BUILD overrides the builder (default scripts/m4/termtris/build.sh);
# the M5 native gate points it at scripts/m5/native.sh.
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
@@ -28,23 +31,28 @@ if git -C "$VENDOR" rev-parse --git-dir >/dev/null 2>&1; then
fi
# The optimizer's switch-to-lookup-table transform creates a late byte-offset
# GEP that --normalize cannot distinguish from an already-scaled bit offset.
# tms-clang disables it; a dense char switch is the regression probe. The
# termtris init_game/runesc switches are the real instances.
# GEP. tms-bitaddr --scale recognizes the `switch.table.*` base and
# shifts its index into bits; a dense char switch is the regression probe.
# The termtris init_game/runesc switches are the real instances.
TMP=$(mktemp -d "${TMPDIR:-/tmp}/tt-switch.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
export TMS_CLANG TMS_OPT TMS_BITADDR
"$ROOT/scripts/tms-clang" -O2 -o "$TMP/switch.ll" "$ROOT/scripts/m4/switch.c" \
|| fail "tms-clang failed for the switch probe"
if grep -q 'switch\.table' "$TMP/switch.ll"; then
fail "switch-to-lookup table survived the driver pipeline (8x index bug)"
fi
grep -q 'switch\.table' "$TMP/switch.ll" \
|| fail "the switch probe no longer exercises a lookup table"
"$TMS_LLC" -march=tms34010 -O0 -filetype=asm "$TMP/switch.ll" \
-o "$TMP/switch.s" || fail "llc failed for the switch probe"
awk '/^_sw_tile:/ { on = 1; next } on && /-- End function/ { exit } on' \
"$TMP/switch.s" > "$TMP/sw_tile.s"
grep -Eq '^[[:space:]]*SLL[[:space:]]+3' "$TMP/sw_tile.s" \
|| { sed 's/^/ /' "$TMP/sw_tile.s" >&2; \
fail "switch-table index is not shifted into bits (8x index bug)"; }
grep -q 'CMPI' "$TMP/switch.s" || fail "the switch probe has no compare/branch"
echo "== build the pinned termtris with this compiler"
"$DIR/build.sh" || fail "termtris build failed"
BUILD=${TERMTRIS_BUILD:-$DIR/build.sh}
"$BUILD" || fail "termtris build failed"
echo "== run board/move/panels/quit in MAME"
TERMTRIS_NOBUILD=1 \
+15 -5
View File
@@ -42,17 +42,27 @@ for fn in le ule sum_le ge uge gt ugt ne lt ult; do
[ -s "$TMP/$fn.s" ] || fail "linked assembly has no _$fn body"
done
check_branch() { # check_branch FUNC MNEMONIC WHAT
if grep -Eq "^[[:space:]]*$2[[:space:]]" "$TMP/$1.s"; then
echo " ok _$1 uses $2 ($3)"
check_branch() { # check_branch FUNC JA<cc> WHAT
# M5's JR relaxation selects the one-word relative form for an in-range
# branch, keeping the condition code. Accept either spelling but require
# exactly the same <cc> suffix.
_cond=${2#JA}
[ "$_cond" != "$2" ] \
|| fail "check_branch expects a JA<cc> mnemonic, got $2"
if grep -Eq "^[[:space:]]*J[AR]${_cond}[[:space:]]" "$TMP/$1.s"; then
echo " ok _$1 uses JA/JR$_cond ($3)"
return 0
fi
sed 's/^/ /' "$TMP/$1.s" >&2
fail "_$1 does not use $2 ($3)"
fail "_$1 does not use JA/JR$_cond ($3)"
}
reject_branch() { # reject_branch FUNC ERE WHAT
if grep -Eq "^[[:space:]]*$2[[:space:]]" "$TMP/$1.s"; then
# The ERE names the absolute form; allow the relative prefix as well. The
# condition itself is unchanged, so a wrong signed/unsigned form still
# fails.
_re=$(printf '%s\n' "$2" | sed 's/^JA/J[AR]/')
if grep -Eq "^[[:space:]]*${_re}[[:space:]]" "$TMP/$1.s"; then
sed 's/^/ /' "$TMP/$1.s" >&2
fail "_$1 uses the wrong condition $2 ($3)"
fi
+72
View File
@@ -0,0 +1,72 @@
# M6 c-testsuite `single-exec` output subset.
#
# Curated list seeded by the M5 Task 12 list and expanded by M6 Task 8 with
# the float/double, long long, bitfield, varargs and aggregate tests the M6
# language/runtime work made runnable. One test name per line (no .c
# suffix); the `.c`, `.c.expected` and `.tags` live under the pinned
# vendor/conformance/c-testsuite/tests/single-exec tree. Every listed test is
# portable C89/C99 using only language features and shim conversions the M6
# path supports. Each test must return 0 and its captured output must equal
# `<name>.c.expected` byte for byte, including the `%f` and `%lld` output.
# Unsupported tests live in c-testsuite.skip, never here.
#
# Core language: integer arithmetic, control flow, pointers, arrays, structs,
# strings (expected output is empty; the status is 0).
00001
00004
00006
00007
00009
00010
00015
00017
00022
00025
00027
00029
00030
00034
00035
00038
00039
#
# Formatted output: %d/%i/%u/%c/%s/%ld through the conformance shim.
00056
00125
00132
00154
00156
00157
00163
00170
00173
00213
00214
00215
#
# M6 floats/doubles: float/double arithmetic, globals, struct members, %f and
# double sizeof. 00175 and 00195 compare the exact printed output.
00113
00119
00123
00175
00178
00195
#
# M6 64-bit integers: long long arithmetic/constants/conversions, int64_t,
# pointer-width interactions and the exact %lld/%llx-style output.
00081
00082
00104
00128
00135
00200
00203
00212
00217
00219
#
# M6 varargs, bitfields, aggregates, and sprintf output.
00140
00218
00186
+195
View File
@@ -0,0 +1,195 @@
#!/bin/sh
# M5 c-testsuite `single-exec` output-subset gate.
#
# scripts/tests/m5/c-testsuite.sh [LIST] [SKIP]
#
# LIST (default scripts/tests/m5/c-testsuite.list) names the curated
# vendor/conformance/c-testsuite/tests/single-exec tests. Every listed test
# runs through the Task 9 single-exec entry point
# (conformance/c-testsuite.sh -> run.sh --classify --expect-status 0
# --expect-output-file <name>.c.expected). The captured stdout must equal
# the .c.expected bytes exactly, main must return 0, the COFF loader readback
# must be clean and the completion magic must be present. A mismatch fails.
# A listed test that the classifier rejects is reported as a skip and fails
# the gate: unsupported tests belong in SKIP, never in LIST.
#
# SKIP (default scripts/tests/m5/c-testsuite.skip) accounts for every other
# single-exec test with a feature/reason. Rows are
# <name><TAB><feature>: <reason>
# Skips are reported separately and are never counted as passes. The gate
# checks that every skip names an existing test, is not also listed, and has a
# reason; a classifier-rejected test must carry the classifier's exact reason.
# LIST + SKIP must cover the pinned suite, so no test is silently dropped.
#
# The MAME boot dominates the runtime. Task 11's proven 300/600 injection
# frames are reused; the loader readback and completion magic checks remain.
# The suite runs serially because M4_SDK is shared.
#
# Overridable: C_TESTSUITE_DIR C_TESTSUITE_LOADER_AT C_TESTSUITE_LOADER_END
# M5_C_TESTSUITE_WORK M5_CONFORMANCE_DIR M5_CONFORMANCE_MODE
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
CONFORMANCE=$CONFORMANCE_DIR/c-testsuite.sh
CLASSIFY=$CONFORMANCE_DIR/classify.sh
SUITE_DIR=${C_TESTSUITE_DIR:-$ROOT/vendor/conformance/c-testsuite/tests/single-exec}
WORK=${M5_C_TESTSUITE_WORK:-$ROOT/build/m5-c-testsuite}
LOADER_AT=${C_TESTSUITE_LOADER_AT:-300}
LOADER_END=${C_TESTSUITE_LOADER_END:-600}
fail() {
echo "c-testsuite: FAIL: $*" >&2
exit 1
}
[ -f "$CONFORMANCE" ] || fail "missing conformance entry point: $CONFORMANCE"
[ -f "$CLASSIFY" ] || fail "missing classifier: $CLASSIFY"
[ -d "$SUITE_DIR" ] || fail "missing pinned c-testsuite tree: $SUITE_DIR (run scripts/fetch-conformance.sh)"
LIST=$HERE/c-testsuite.list
SKIP=$HERE/c-testsuite.skip
if [ $# -gt 0 ]; then
LIST=$1
shift
fi
if [ $# -gt 0 ]; then
SKIP=$1
shift
fi
[ $# -eq 0 ] || fail "unexpected trailing arguments: $*"
[ -f "$LIST" ] || fail "no c-testsuite.list ($LIST); Task 12 seeds it"
[ -f "$SKIP" ] || fail "no c-testsuite.skip ($SKIP); Task 12 seeds it"
mkdir -p "$WORK"
LOG=$WORK/c-testsuite.log
: > "$LOG"
list_count() {
awk '$0 !~ /^[[:space:]]*(#|$)/ { n++ } END { print n + 0 }' "$1"
}
LIST_COUNT=$(list_count "$LIST")
[ "$LIST_COUNT" -gt 0 ] || fail "c-testsuite.list is empty ($LIST)"
# One running log with the runner's per-test result rows, plus the individual
# runner logs kept under the work dir.
ONE_LIST=$WORK/one.list
pass=0
runner_skip=0
failed=0
total=0
while IFS= read -r name; do
case $name in
''|\#*) continue ;;
esac
case $name in
*/*|.*) fail "unsafe test name in $LIST: '$name'" ;;
esac
base=${name%.c}
src=$SUITE_DIR/$base.c
expected=$SUITE_DIR/$base.c.expected
[ -f "$src" ] || fail "missing c-testsuite source: $src"
[ -f "$expected" ] || fail "missing c-testsuite expected output: $expected"
total=$((total + 1))
printf '%s\n' "$base" > "$ONE_LIST"
one_log=$WORK/$base.log
set +e
LOADER_AT=$LOADER_AT LOADER_END=$LOADER_END \
"$CONFORMANCE" "$ONE_LIST" > "$one_log" 2>&1
rc=$?
set -e
cat "$one_log" >> "$LOG"
case $rc in
0)
pass=$((pass + 1))
;;
*)
# The wrapper exits 1 when its only test was classified as a skip
# (pass=0). Report the reason, but fail below: an unsupported test
# must be in c-testsuite.skip, not the list.
if grep -q '^CONFORMANCE: SKIP ' "$one_log"; then
reason=$(sed -n 's/^CONFORMANCE: SKIP id=[^ ]* reason=//p' "$one_log")
runner_skip=$((runner_skip + 1))
echo "c-testsuite: SKIP $base (listed but classifier-rejected: $reason)" >&2
else
failed=$((failed + 1))
echo "c-testsuite: FAIL $base (runner exit $rc; log $one_log)" >&2
fi
;;
esac
done < "$LIST"
# Validate the skip file and collect its coverage.
: > "$WORK/skip-reasons.txt"
skip=0
while IFS= read -r line; do
case $line in
''|\#*) continue ;;
esac
name=${line%% *}
reason=${line#* }
[ "$name" != "$line" ] || fail "malformed skip row (no tab): $line"
case $name in
*/*|.*) fail "unsafe test name in $SKIP: '$name'" ;;
esac
base=${name%.c}
[ -f "$SUITE_DIR/$base.c" ] || fail "skip names a missing test: $base"
if grep -Fxq "$base" "$LIST"; then
fail "test $base is both listed and skipped"
fi
[ -n "$reason" ] || fail "skip for $base has no reason"
case $reason in
*:?*) ;;
*) fail "skip for $base has no feature/reason: '$reason'" ;;
esac
set +e
classified=$("$CLASSIFY" "$SUITE_DIR/$base.c" 2>&1)
crc=$?
set -e
case $crc in
0)
# A classifier-supported test is only skipped for an explicit shim
# gap or because it is outside the curated subset.
case $reason in
libc:*|stderr:*|shim-format:*|runtime:*|unselected:*) ;;
*) fail "skip for $base does not name a shim gap or an unselected test: '$reason'" ;;
esac
;;
1)
[ "$reason" = "$classified" ] \
|| fail "skip reason for $base is stale: '$reason' != '$classified'"
;;
*)
fail "classifier error (exit $crc) on $base: $classified"
;;
esac
skip=$((skip + 1))
printf '%s\t%s\n' "$base" "$reason" >> "$WORK/skip-reasons.txt"
done < "$SKIP"
[ "$failed" -eq 0 ] || fail "$failed of $total listed tests failed"
[ "$pass" -gt 0 ] \
|| fail "no tests passed (pass=0 skip=$runner_skip total=$total); all-skip is not a pass"
[ "$runner_skip" -eq 0 ] \
|| fail "$runner_skip listed test(s) were classifier-rejected; move them to $SKIP"
suite_count=$(find "$SUITE_DIR" -maxdepth 1 -type f -name '*.c' | wc -l | tr -d ' ')
[ "$((pass + skip))" -eq "$suite_count" ] \
|| fail "list+skip cover $((pass + skip)) tests, suite has $suite_count; every test needs a pass or a skip"
if [ "$skip" -gt 0 ]; then
awk -F '\t' '{ printf "c-testsuite: SKIP %s reason=%s\n", $1, $2 }' \
"$WORK/skip-reasons.txt" >> "$LOG"
echo "c-testsuite: skipped $skip test(s) by reason:"
awk -F '\t' '{ split($2, a, ":"); print a[1] }' "$WORK/skip-reasons.txt" \
| sort | uniq -c | sort -rn | sed 's/^/ /'
fi
echo "c-testsuite: PASS pass=$pass skip=$skip total=$suite_count"
echo "c-testsuite: logs $WORK"
echo "c-testsuite: skip reasons $WORK/skip-reasons.txt"
+182
View File
@@ -0,0 +1,182 @@
# M6 c-testsuite `single-exec` skips.
#
# Every single-exec test that is not in c-testsuite.list is accounted for here
# as `<name><TAB><feature>: <reason>`, so no pinned test is silently dropped.
# A skipped test is never a pass. M6 Task 8 removed the float/long-long/
# bitfield skip rows for the tests that moved into the list; the remainder are
# either classifier-rejected (exact `feature: reason` text) or
# classifier-supported tests outside the curated output subset
# (`unselected:`) or an explicit shim gap
# (`libc:`/`stderr:`/`shim-format:`/`runtime:`).
00002 unselected: classifier-supported; outside the curated output subset
00003 unselected: classifier-supported; outside the curated output subset
00005 unselected: classifier-supported; outside the curated output subset
00008 unselected: classifier-supported; outside the curated output subset
00011 unselected: classifier-supported; outside the curated output subset
00012 unselected: classifier-supported; outside the curated output subset
00013 unselected: classifier-supported; outside the curated output subset
00014 unselected: classifier-supported; outside the curated output subset
00016 unselected: classifier-supported; outside the curated output subset
00018 unselected: classifier-supported; outside the curated output subset
00019 unselected: classifier-supported; outside the curated output subset
00020 unselected: classifier-supported; outside the curated output subset
00021 unselected: classifier-supported; outside the curated output subset
00023 unselected: classifier-supported; outside the curated output subset
00024 unselected: classifier-supported; outside the curated output subset
00026 unselected: classifier-supported; outside the curated output subset
00028 unselected: classifier-supported; outside the curated output subset
00031 unselected: classifier-supported; outside the curated output subset
00032 unselected: classifier-supported; outside the curated output subset
00033 unselected: classifier-supported; outside the curated output subset
00036 unselected: classifier-supported; outside the curated output subset
00037 unselected: classifier-supported; outside the curated output subset
00040 libc: calloc is not implemented by the conformance shim
00041 unselected: classifier-supported; outside the curated output subset
00042 unselected: classifier-supported; outside the curated output subset
00043 unselected: classifier-supported; outside the curated output subset
00044 unselected: classifier-supported; outside the curated output subset
00045 unselected: classifier-supported; outside the curated output subset
00046 unselected: classifier-supported; outside the curated output subset
00047 unselected: classifier-supported; outside the curated output subset
00048 unselected: classifier-supported; outside the curated output subset
00049 unselected: classifier-supported; outside the curated output subset
00050 unselected: classifier-supported; outside the curated output subset
00051 unselected: classifier-supported; outside the curated output subset
00052 unselected: classifier-supported; outside the curated output subset
00053 unselected: classifier-supported; outside the curated output subset
00054 unselected: classifier-supported; outside the curated output subset
00055 unselected: classifier-supported; outside the curated output subset
00057 unselected: classifier-supported; outside the curated output subset
00058 unselected: classifier-supported; outside the curated output subset
00059 unselected: classifier-supported; outside the curated output subset
00060 unselected: classifier-supported; outside the curated output subset
00061 unselected: classifier-supported; outside the curated output subset
00062 unselected: classifier-supported; outside the curated output subset
00063 unselected: classifier-supported; outside the curated output subset
00064 unselected: classifier-supported; outside the curated output subset
00065 unselected: classifier-supported; outside the curated output subset
00066 unselected: classifier-supported; outside the curated output subset
00067 unselected: classifier-supported; outside the curated output subset
00068 unselected: classifier-supported; outside the curated output subset
00069 unselected: classifier-supported; outside the curated output subset
00070 unselected: classifier-supported; outside the curated output subset
00071 unselected: classifier-supported; outside the curated output subset
00072 unselected: classifier-supported; outside the curated output subset
00073 unselected: classifier-supported; outside the curated output subset
00074 unselected: classifier-supported; outside the curated output subset
00075 unselected: classifier-supported; outside the curated output subset
00076 unselected: classifier-supported; outside the curated output subset
00077 unselected: classifier-supported; outside the curated output subset
00078 unselected: classifier-supported; outside the curated output subset
00079 unselected: classifier-supported; outside the curated output subset
00080 unselected: classifier-supported; outside the curated output subset
00083 unselected: classifier-supported; outside the curated output subset
00084 unselected: classifier-supported; outside the curated output subset
00085 unselected: classifier-supported; outside the curated output subset
00086 unselected: classifier-supported; outside the curated output subset
00087 unselected: classifier-supported; outside the curated output subset
00088 unselected: classifier-supported; outside the curated output subset
00089 unselected: classifier-supported; outside the curated output subset
00090 unselected: classifier-supported; outside the curated output subset
00091 unselected: classifier-supported; outside the curated output subset
00092 unselected: classifier-supported; outside the curated output subset
00093 unselected: classifier-supported; outside the curated output subset
00094 unselected: classifier-supported; outside the curated output subset
00095 unselected: classifier-supported; outside the curated output subset
00096 unselected: classifier-supported; outside the curated output subset
00097 unselected: classifier-supported; outside the curated output subset
00098 wide-char: wide characters are unsupported
00099 unselected: classifier-supported; outside the curated output subset
00100 unselected: classifier-supported; outside the curated output subset
00101 unselected: classifier-supported; outside the curated output subset
00102 unselected: classifier-supported; outside the curated output subset
00103 unselected: classifier-supported; outside the curated output subset
00105 unselected: classifier-supported; outside the curated output subset
00106 unselected: classifier-supported; outside the curated output subset
00107 unselected: classifier-supported; outside the curated output subset
00108 unselected: classifier-supported; outside the curated output subset
00109 unselected: classifier-supported; outside the curated output subset
00110 unselected: classifier-supported; outside the curated output subset
00111 unselected: classifier-supported; outside the curated output subset
00112 unselected: classifier-supported; outside the curated output subset
00114 unselected: classifier-supported; outside the curated output subset
00115 unselected: classifier-supported; outside the curated output subset
00116 unselected: classifier-supported; outside the curated output subset
00117 unselected: classifier-supported; outside the curated output subset
00118 unselected: classifier-supported; outside the curated output subset
00120 unselected: classifier-supported; outside the curated output subset
00121 unselected: classifier-supported; outside the curated output subset
00122 unselected: classifier-supported; outside the curated output subset
00124 unselected: classifier-supported; outside the curated output subset
00126 unselected: classifier-supported; outside the curated output subset
00127 unselected: classifier-supported; outside the curated output subset
00129 unselected: classifier-supported; outside the curated output subset
00130 unselected: classifier-supported; outside the curated output subset
00131 unselected: classifier-supported; outside the curated output subset
00133 unselected: classifier-supported; outside the curated output subset
00134 unselected: classifier-supported; outside the curated output subset
00136 unselected: classifier-supported; outside the curated output subset
00137 unselected: classifier-supported; outside the curated output subset
00138 unselected: classifier-supported; outside the curated output subset
00139 unselected: classifier-supported; outside the curated output subset
00141 unselected: classifier-supported; outside the curated output subset
00142 unselected: classifier-supported; outside the curated output subset
00143 unselected: classifier-supported; outside the curated output subset
00144 unselected: classifier-supported; outside the curated output subset
00145 unselected: classifier-supported; outside the curated output subset
00146 unselected: classifier-supported; outside the curated output subset
00147 unselected: classifier-supported; outside the curated output subset
00148 unselected: classifier-supported; outside the curated output subset
00149 unselected: classifier-supported; outside the curated output subset
00150 unselected: classifier-supported; outside the curated output subset
00151 unselected: classifier-supported; outside the curated output subset
00152 unselected: classifier-supported; outside the curated output subset
00153 unselected: classifier-supported; outside the curated output subset
00155 unselected: classifier-supported; outside the curated output subset
00158 unselected: classifier-supported; outside the curated output subset
00159 unselected: classifier-supported; outside the curated output subset
00160 unselected: classifier-supported; outside the curated output subset
00161 unselected: classifier-supported; outside the curated output subset
00162 unselected: classifier-supported; outside the curated output subset
00164 unselected: classifier-supported; outside the curated output subset
00165 unselected: classifier-supported; outside the curated output subset
00166 unselected: classifier-supported; outside the curated output subset
00167 unselected: classifier-supported; outside the curated output subset
00168 unselected: classifier-supported; outside the curated output subset
00169 unselected: classifier-supported; outside the curated output subset
00171 unselected: classifier-supported; outside the curated output subset
00172 unselected: classifier-supported; outside the curated output subset
00174 libc: sin() is not implemented by the conformance shim
00176 unselected: classifier-supported; outside the curated output subset
00177 unselected: classifier-supported; outside the curated output subset
00179 wide-char: wide characters are unsupported
00180 unselected: classifier-supported; outside the curated output subset
00181 unselected: classifier-supported; outside the curated output subset
00182 file-io: stdio/POSIX file I/O is unavailable under the bare loader
00183 unselected: classifier-supported; outside the curated output subset
00184 unselected: classifier-supported; outside the curated output subset
00185 unselected: classifier-supported; outside the curated output subset
00187 file-io: stdio/POSIX file I/O is unavailable under the bare loader
00188 unselected: classifier-supported; outside the curated output subset
00189 file-io: stdio/POSIX file I/O is unavailable under the bare loader
00190 unselected: classifier-supported; outside the curated output subset
00191 unselected: classifier-supported; outside the curated output subset
00192 unselected: classifier-supported; outside the curated output subset
00193 unselected: classifier-supported; outside the curated output subset
00194 unselected: classifier-supported; outside the curated output subset
00196 unselected: classifier-supported; outside the curated output subset
00197 unselected: classifier-supported; outside the curated output subset
00198 unselected: classifier-supported; outside the curated output subset
00199 unselected: classifier-supported; outside the curated output subset
00201 unselected: classifier-supported; outside the curated output subset
00202 unselected: classifier-supported; outside the curated output subset
00204 format-unsupported: printf %n, positional $, %e/%g/%a/%F, %j, long-double %L/%F and wide %ls/%lc are not implemented by the shim
00205 unselected: curated list not re-evaluated after the M7.1 .data extension
00206 unselected: classifier-supported; outside the curated output subset
00207 unselected: classifier-supported; outside the curated output subset
00208 wide-char: wide characters are unsupported
00209 unselected: classifier-supported; outside the curated output subset
00210 unselected: classifier-supported; outside the curated output subset
00211 unselected: classifier-supported; outside the curated output subset
00216 unselected: curated list not re-evaluated after the M7.1 .data extension
00220 wide-char: wide characters are unsupported
+118
View File
@@ -0,0 +1,118 @@
# M6 c-torture `execute` subset.
#
# One test name per line (no .c suffix), selected from
# vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute.
# The M6 gate runs each name at -O0 and a bounded subset at -O2 through the
# conformance harness and requires main to return 0 in MAME.
#
# M6 Task 8 removed the M5 "integer/control only" restriction: the list now
# includes the float/double, long long, bitfield, general-varargs and
# aggregate-by-value tests the M6 compiler/runtime made runnable. It is 79
# tests (59 M5 legacy + 20 M6 additions); the 40-60 curated target is a soft
# bound for this one-time expansion, and the 19 legacy tests that a first cut
# dropped are restored so no previously gated shape loses coverage. The full
# corpus classifier report (`c-torture.sh --scan`) is the selection report, not
# this gate.
#
# Test selection is runtime-verified, not classifier-only: several
# classifier-supported tests still hit the M2 `.data` initializer limit
# (aggregate/bitfield globals) or the 300/600 frame budget and are not listed.
#
# Integer arithmetic, conversions, and bit operations
20000313-1
20000503-1
20000519-2
20000715-2
20001009-1
20021118-3
20030128-1
20030821-1
20050410-1
20070724-1
20071205-1
20081112-1
920721-1
941025-1
950706-1
960219-1
961122-2
990324-1
991202-2
#
# Control flow: loops, conditionals, switch, recursion
20000205-1
20000412-2
20000412-4
20000511-1
20000731-2
20010206-1
20010422-1
20010723-1
20040706-1
20070212-2
920506-1
930123-1
960419-1
961017-1
980602-1
980929-1
990604-1
991202-1
#
# Arrays, pointers, and string literals
20000112-1
20000314-1
20000314-3
20000403-1
20000412-1
20000412-6
20000422-1
20000706-4
20001027-1
20010711-1
20011109-2
20011114-1
20011128-1
20020911-1
20021119-1
20050106-1
20090207-1
930429-1
931110-2
951115-1
960419-2
991227-1
#
# M6 floats/doubles: arithmetic, comparisons, struct/union members, globals,
# floats passed by value, and a double function pointer.
20000603-1
20000605-1
20020213-1
920501-8
930614-1
930614-2
#
# M6 64-bit integers: constants, add/sub/mul, shifts, divide/remainder and
# conversions through int.
20000402-1
20000523-1
20001108-1
20110418-1
20141125-1
#
# M6 general varargs: va_list passes through a second function, mixed
# int/double/long walks, many stack arguments and a va_list copy.
20000519-1
stdarg-4
va-arg-1
multi-ix
#
# M6 bitfields: packed struct fields, bitfield arithmetic and bitfield stores.
20000113-1
20001101
20040629-1
#
# M6 aggregates: struct/union passed and returned by value, including a
# float/char-array struct checked with memcmp.
20081103-1
921112-1
+200
View File
@@ -0,0 +1,200 @@
#!/bin/sh
# M5 GCC c-torture `execute` subset gate.
#
# scripts/tests/m5/c-torture.sh [LIST]
# scripts/tests/m5/c-torture.sh --scan [CORPUS_DIR]
#
# LIST is the curated allowlist (default: scripts/tests/m5/c-torture.list).
# Each non-comment line names a test under the pinned GCC 16.2.0
# gcc.c-torture/execute tree. The gate compiles every test through the Task 9
# conformance harness twice, once with tms-clang -O0 and once with -O2 (both
# the IR pipeline and llc), links the shim/entry, runs the COFF in MAME, and
# requires main to return 0 with the completion magic present. stdout is
# ignored because c-torture tests may print diagnostics on success; the status
# is the oracle. A test that cannot compile is not silently dropped: the
# classifier reports it as a skip with a reason, and a run with no passing
# test fails even when every test was skipped.
#
# --scan is the broader report mode: it runs the classifier over every .c in
# the corpus, writes build/m5-c-torture/c-torture-scan.txt, and prints the
# supported/skip counts by feature. It never compiles or runs a test, so it is
# a selection report, not the gate.
#
# The default MAME injection/exit frames are lower than Task 9's 2500/2700.
# The VT1200 OS is ready well before frame 300 (verified against the pinned
# loader); 300 leaves a wide margin while keeping the serial suite practical.
# The loader COFF readback and the completion magic are still required, so the
# lower frame does not weaken the pass condition.
#
# Overridable: C_TORTURE_DIR C_TORTURE_LOADER_AT C_TORTURE_LOADER_END
# M5_C_TORTURE_WORK M5_CONFORMANCE_DIR
# M5_CONFORMANCE_CLANG_OPT M5_CONFORMANCE_LLC_OPT (per pass)
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
CONFORMANCE_DIR=${M5_CONFORMANCE_DIR:-$HERE/conformance}
CONFORMANCE=$CONFORMANCE_DIR/c-torture.sh
CLASSIFY=$CONFORMANCE_DIR/classify.sh
SUITE_DIR=${C_TORTURE_DIR:-$ROOT/vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute}
WORK=${M5_C_TORTURE_WORK:-$ROOT/build/m5-c-torture}
LOADER_AT=${C_TORTURE_LOADER_AT:-300}
LOADER_END=${C_TORTURE_LOADER_END:-600}
fail() {
echo "c-torture: FAIL: $*" >&2
exit 1
}
[ -f "$CONFORMANCE" ] || fail "missing conformance entry point: $CONFORMANCE"
[ -f "$CLASSIFY" ] || fail "missing classifier: $CLASSIFY"
[ -d "$SUITE_DIR" ] || fail "missing pinned c-torture tree: $SUITE_DIR (run scripts/fetch-conformance.sh)"
SCAN=0
LIST=$HERE/c-torture.list
if [ $# -gt 0 ]; then
case $1 in
--scan)
SCAN=1
shift
[ $# -eq 0 ] || { SUITE_DIR=$1; shift; }
;;
-*)
fail "unknown option: $1"
;;
*)
LIST=$1
shift
;;
esac
fi
[ $# -eq 0 ] || fail "unexpected trailing arguments: $*"
[ -d "$SUITE_DIR" ] || fail "missing corpus: $SUITE_DIR"
mkdir -p "$WORK"
if [ "$SCAN" -eq 1 ]; then
REPORT=$WORK/c-torture-scan.txt
find "$SUITE_DIR" -maxdepth 1 -type f -name '*.c' | sort \
> "$WORK/c-torture-corpus.txt"
total=0
supported=0
skipped=0
{
echo "# M5 c-torture execute classifier scan"
echo "# corpus: $SUITE_DIR"
echo "# rows: status<TAB>test<TAB>reason"
} > "$REPORT"
while IFS= read -r src; do
name=$(basename "$src" .c)
total=$((total + 1))
set +e
reason=$("$CLASSIFY" "$src" 2>&1)
rc=$?
set -e
case $rc in
0)
supported=$((supported + 1))
printf 'supported\t%s\t\n' "$name" >> "$REPORT"
;;
1)
skipped=$((skipped + 1))
printf 'skip\t%s\t%s\n' "$name" "$reason" >> "$REPORT"
;;
*)
fail "classifier error (exit $rc) on $name: $reason"
;;
esac
done < "$WORK/c-torture-corpus.txt"
{
echo "# total $total supported $supported skip $skipped"
} >> "$REPORT"
echo "c-torture scan: total=$total supported=$supported skip=$skipped"
echo "c-torture scan: skipped tests by feature:"
awk -F '\t' '$1 == "skip" { split($3, a, ":"); print a[1] }' "$REPORT" \
| sort | uniq -c | sort -rn | sed 's/^/ /' || true
echo "c-torture scan: report $REPORT"
[ "$supported" -gt 0 ] || fail "no supported c-torture tests in $SUITE_DIR"
exit 0
fi
[ -f "$LIST" ] || fail "no c-torture.list ($LIST); Task 11 seeds it"
LIST_COUNT=$(awk '$0 !~ /^[[:space:]]*(#|$)/ { n++ } END { print n + 0 }' "$LIST")
[ "$LIST_COUNT" -gt 0 ] || fail "c-torture.list is empty ($LIST)"
# Each pass writes its own conformance log. The Task 9 runner prints one
# machine-readable result line per test, plus the suite summary.
run_pass() {
opt=$1
log=$2
set +e
LOADER_AT=$LOADER_AT LOADER_END=$LOADER_END \
M5_CONFORMANCE_CLANG_OPT=$opt \
M5_CONFORMANCE_LLC_OPT=$opt \
"$CONFORMANCE" "$LIST" > "$log" 2>&1
rc=$?
set -e
echo "$rc" > "$log.rc"
}
count() {
awk -v pat="$2" '$0 ~ pat { n++ } END { print n + 0 }' "$1"
}
run_pass -O0 "$WORK/c-torture-O0.log"
run_pass -O2 "$WORK/c-torture-O2.log"
bad=0
for opt in -O0 -O2; do
case $opt in
-O0) log=$WORK/c-torture-O0.log ;;
-O2) log=$WORK/c-torture-O2.log ;;
esac
rc=$(cat "$log.rc")
pass=$(count "$log" '^CONFORMANCE: PASS ')
skip=$(count "$log" '^CONFORMANCE: SKIP ')
# A test can print both a CONFORMANCE: FAIL row and the runner's
# "c-torture: FAIL <name>" line; a compile/link/MAME failure that exits
# before run.sh prints a result row only prints the latter. Count the
# union of test names so a failure is not counted twice.
: > "$WORK/c-torture-fail-names.log"
grep '^CONFORMANCE: FAIL id=c-torture/' "$log" 2>/dev/null \
| sed 's/^CONFORMANCE: FAIL id=c-torture\///; s/[[:space:]].*$//' \
>> "$WORK/c-torture-fail-names.log" || true
grep '^c-torture: FAIL ' "$log" 2>/dev/null \
| sed 's/^c-torture: FAIL //; s/[[:space:]].*$//' \
>> "$WORK/c-torture-fail-names.log" || true
failn=$(sort -u "$WORK/c-torture-fail-names.log" | wc -l | tr -d ' ')
[ "$pass" -gt 0 ] || {
echo "c-torture: $opt no tests passed (pass=0 skip=$skip); all-skip is not a pass" >&2
bad=1
}
[ "$failn" -eq 0 ] || {
echo "c-torture: $opt $failn test(s) failed" >&2
bad=1
}
[ "$rc" -eq 0 ] || {
echo "c-torture: $opt conformance runner exited $rc" >&2
bad=1
}
TOTAL=$((pass + skip + failn))
[ "$TOTAL" -eq "$LIST_COUNT" ] || {
echo "c-torture: $opt produced $TOTAL result rows, list has $LIST_COUNT" >&2
bad=1
}
if [ "$skip" -gt 0 ]; then
echo "c-torture: $opt skipped $skip test(s):" >&2
grep '^CONFORMANCE: SKIP ' "$log" | sed 's/^/ /' >&2 || true
fi
eval "PASS_${opt#-}=$pass"
eval "SKIP_${opt#-}=$skip"
eval "FAIL_${opt#-}=$failn"
done
if [ "$bad" -ne 0 ]; then
echo "c-torture: logs $WORK" >&2
exit 1
fi
echo "c-torture: PASS O0 pass=$PASS_O0 skip=$SKIP_O0 total=$LIST_COUNT O2 pass=$PASS_O2 skip=$SKIP_O2 total=$LIST_COUNT"
echo "c-torture: logs $WORK"
+79
View File
@@ -0,0 +1,79 @@
#!/bin/sh
# c-testsuite single-exec entry point (M5 Task 12 seeds the list).
#
# c-testsuite.sh [LIST]
#
# Each non-comment line of LIST names a test under the pinned
# vendor/conformance/c-testsuite/tests/single-exec tree. The test is
# classified first; unsupported tests are reported as skips (never passes).
# A supported test must return 0 and its stdout must equal
# <name>.c.expected. A run with no passing test is a failure, even if every
# test was skipped. This tier requires the native TI-COFF link (--mode native);
# an asm/GSPA fallback is a failure, so a native-object regression cannot hide
# here. All compile, link, MAME and compare work lives in run.sh.
#
# Default list: scripts/tests/m5/c-testsuite.list
# Overridable: C_TESTSUITE_DIR M5_CONFORMANCE_DIR
set -eu
ROOT=$(cd "$(dirname "$0")/../../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
RUN=$HERE/run.sh
CLASSIFY=$HERE/classify.sh
LIST=${1:-$ROOT/scripts/tests/m5/c-testsuite.list}
SUITE_DIR=${C_TESTSUITE_DIR:-$ROOT/vendor/conformance/c-testsuite/tests/single-exec}
fail() {
echo "c-testsuite: FAIL: $*" >&2
exit 1
}
[ -f "$RUN" ] || fail "missing runner: $RUN"
[ -f "$CLASSIFY" ] || fail "missing classifier: $CLASSIFY"
if [ ! -f "$LIST" ]; then
fail "no c-testsuite.list ($LIST); Task 12 seeds it"
fi
[ -d "$SUITE_DIR" ] || fail "missing pinned c-testsuite tree: $SUITE_DIR (run scripts/fetch-conformance.sh)"
pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-testsuite.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
''|\#*) continue ;;
esac
total=$((total + 1))
base=${name%.c}
src=$SUITE_DIR/$base.c
expected=$SUITE_DIR/$base.c.expected
[ -f "$expected" ] || expected=$SUITE_DIR/$base.expected
[ -f "$src" ] || fail "missing c-testsuite source: $src"
[ -f "$expected" ] || fail "missing c-testsuite expected output: $expected"
if "$RUN" --id "c-testsuite/$base" --classify --mode native \
--expect-status 0 --expect-output-file "$expected" "$src" \
> "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
cat "$ONE_LOG"
# Exit 2 is a skip only with a real SKIP row (see c-torture.sh).
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-testsuite: FAIL $base (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
[ "$total" -gt 0 ] || fail "c-testsuite.list is empty"
[ "$failed" -eq 0 ] || fail "$failed of $total tests failed"
[ "$pass" -gt 0 ] \
|| fail "no tests passed (pass=0 skip=$skip total=$total); all-skip is not a pass"
echo "c-testsuite: PASS pass=$pass skip=$skip total=$total"
+74
View File
@@ -0,0 +1,74 @@
#!/bin/sh
# c-torture conformance entry point (M5 Task 11 seeds the list).
#
# c-torture.sh [LIST]
#
# Each non-comment line of LIST names a test under the pinned
# vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute tree.
# The test is classified first; unsupported tests are reported as skips (never
# passes), and supported tests must return 0 (stdout is ignored here). A run
# with no passing test is a failure, even if every test was skipped. All
# compile, link, MAME and compare work lives in run.sh.
#
# Default list: scripts/tests/m5/c-torture.list
# Overridable: C_TORTURE_DIR M5_CONFORMANCE_DIR
set -eu
ROOT=$(cd "$(dirname "$0")/../../../.." && pwd)
HERE=$(cd "$(dirname "$0")" && pwd)
RUN=$HERE/run.sh
CLASSIFY=$HERE/classify.sh
LIST=${1:-$ROOT/scripts/tests/m5/c-torture.list}
SUITE_DIR=${C_TORTURE_DIR:-$ROOT/vendor/conformance/gcc-16.2.0/gcc/testsuite/gcc.c-torture/execute}
fail() {
echo "c-torture: FAIL: $*" >&2
exit 1
}
[ -f "$RUN" ] || fail "missing runner: $RUN"
[ -f "$CLASSIFY" ] || fail "missing classifier: $CLASSIFY"
if [ ! -f "$LIST" ]; then
fail "no c-torture.list ($LIST); Task 11 seeds it"
fi
[ -d "$SUITE_DIR" ] || fail "missing pinned c-torture tree: $SUITE_DIR (run scripts/fetch-conformance.sh)"
pass=0
skip=0
failed=0
total=0
ONE_LOG=$(mktemp "${TMPDIR:-/tmp}/c-torture.XXXXXX")
trap 'rm -f "$ONE_LOG"' EXIT HUP INT TERM
while IFS= read -r name; do
case $name in
''|\#*) continue ;;
esac
total=$((total + 1))
src=$SUITE_DIR/$name.c
[ -f "$src" ] || fail "missing c-torture source: $src"
if "$RUN" --id "c-torture/$name" --classify \
--expect-status 0 --ignore-output "$src" > "$ONE_LOG" 2>&1; then
cat "$ONE_LOG"
pass=$((pass + 1))
else
rc=$?
cat "$ONE_LOG"
# Exit 2 is a skip only when the runner printed a real SKIP row.
# run.sh also uses 2 for a native-COFF loader rejection; treating a
# bare 2 as a skip would turn a genuine failure into a pass-like row.
if [ "$rc" -eq 2 ] && grep -q '^CONFORMANCE: SKIP ' "$ONE_LOG"; then
skip=$((skip + 1))
else
failed=$((failed + 1))
echo "c-torture: FAIL $name (runner exit $rc, no SKIP row)" >&2
fi
fi
done < "$LIST"
[ "$total" -gt 0 ] || fail "c-torture.list is empty"
[ "$failed" -eq 0 ] || fail "$failed of $total tests failed"
[ "$pass" -gt 0 ] \
|| fail "no tests passed (pass=0 skip=$skip total=$total); all-skip is not a pass"
echo "c-torture: PASS pass=$pass skip=$skip total=$total"
+99
View File
@@ -0,0 +1,99 @@
#!/bin/sh
# Classify a C source for features the M6 conformance path cannot run.
#
# classify.sh FILE
#
# Prints "feature: reason" and exits 1 when the source uses an unsupported
# feature; prints nothing and exits 0 when it is acceptable. Exits 2 for
# usage, unreadable-source, grep or skip-table errors, so callers can tell a
# real skip apart from a classifier failure. The reasons come from skip.tsv
# so the manifest, suite runners and reports agree.
#
# M6 implements floats/doubles, 64-bit integers, bitfields, general varargs
# and aggregates, so those are no longer skipped. The remaining skips are
# genuine M6 non-goals: 128-bit integers, non-local jumps, signals, wide
# characters, stdio/POSIX file I/O and the printf conversions the shim does
# not implement. This is deliberately conservative: a false positive skips a
# test (and says why), while a false negative could turn an unsupported test
# into a fake pass. Comments are scanned; printf conversions are checked
# inside string literals only.
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
SKIPS=$HERE/skip.tsv
[ $# -eq 1 ] || { echo "usage: $0 FILE.c" >&2; exit 2; }
SRC=$1
[ -f "$SRC" ] || { echo "classify: missing source: $SRC" >&2; exit 2; }
[ -f "$SKIPS" ] || { echo "classify: missing $SKIPS" >&2; exit 2; }
feature=
match() {
[ -z "$feature" ] || return 0
if grep -Eqi -- "$2" "$SRC"; then
feature=$1
else
st=$?
[ "$st" -eq 1 ] || {
echo "classify: grep failed (status $st) on $SRC" >&2
exit 2
}
fi
return 0
}
# A printf conversion is only meaningful inside a string literal. Scan the
# double-quoted literals instead of the whole source so a C modulo expression
# (`x % e`, `0 % a++`, `(c || b) % g`) is not mistaken for a conversion.
# Escaped quotes are split so a conversion after \" is still seen.
match_formats() {
[ -z "$feature" ] || return 0
set +e
literals=$(sed 's/\\"/""/g' "$SRC" | grep -o '"[^"]*"')
st=$?
set -e
[ "$st" -le 1 ] || {
echo "classify: string-literal scan failed (status $st) on $SRC" >&2
exit 2
}
if printf '%s\n' "$literals" | grep -Eq -- "$2"; then
feature=$1
else
st=$?
[ "$st" -eq 1 ] || {
echo "classify: grep failed (status $st) on $SRC" >&2
exit 2
}
fi
return 0
}
# Order is only cosmetic; the first match names the primary blocker. Most
# matches are case-insensitive so macro spellings are not missed. The
# format-unsupported scan is case-sensitive because %L/%e/%g/%a/%F are
# distinct conversions and %ld/%lld/%lf are supported; the regex spells out
# the uppercase forms it does match.
match int128 '__int128|__uint128|__int128_t|__uint128_t'
match setjmp '(^|[^A-Za-z0-9_])(setjmp|longjmp|sigsetjmp|siglongjmp)([^A-Za-z0-9_]|$)'
match signal '(^|[^A-Za-z0-9_])(signal|sigaction|sigemptyset|sigaddset|sigprocmask)([^A-Za-z0-9_]|$)'
match wide-char '(^|[^A-Za-z0-9_])(wchar|wchar_t|wint_t|wprintf|wscanf)([^A-Za-z0-9_]|$)|L"|L'"'"''
# %n (also %hhn/%lln), positional arguments, the floating conversions without
# shim support (%e/%g/%a/%F, including %lF), %j (intmax_t is 64-bit here while
# the shim reads 32), long double and wide strings are genuinely unsupported.
# %z/%t are supported: size_t is unsigned int and ptrdiff_t is int on this
# target, so the shim's 32-bit read is correct. Field width, precision, * and
# %lld/%llu/%f are implemented and must not be skipped.
match_formats format-unsupported '%[-+ #0-9.*]*\$|%[-+ #0-9.*]*l?[eEgGaAF]|%[-+ #0-9.*]*j[diouxX]|%[-+ #0-9.*]*(hh|h|ll|l)?n|%[-+ #0-9.*]*L[diouxXeEfgGaAF]|%[-+ #0-9.*]*l[sc]'
match file-io '(^|[^A-Za-z0-9_])(FILE|fopen|fclose|fread|fwrite|fprintf|freopen|fflush|fseek|ftell|fgetc|fputc|fgets|fputs|remove|rename|tmpfile|tmpnam)([^A-Za-z0-9_]|$)|(^|[^A-Za-z0-9_])(open|creat)[[:space:]]*\('
[ -n "$feature" ] || exit 0
reason=$(awk -F '\t' -v f="$feature" '$1 == f { print $2; exit }' "$SKIPS") \
|| { echo "classify: cannot read $SKIPS" >&2; exit 2; }
[ -n "$reason" ] || {
echo "classify: no reason for feature '$feature' in $SKIPS" >&2
exit 2
}
printf '%s: %s\n' "$feature" "$reason"
exit 1
@@ -0,0 +1,146 @@
-- conformance-check.lua -- load the conformance COFF with the M4 loader and
-- publish the shim's result block.
--
-- The loader is scripts/m4/run.sh's loader (vendor/vt1200/dwt/loader/loader.lua),
-- loaded through M4_LOADER_LUA. The test's entry writes:
-- 01B00000 status
-- 01B00020 out_len
-- 01B00040 magic 0x434F4E46
-- 01B00060 err_len
-- 01B10000 output bytes (bit addresses, 8 bits apart; 16 KiB ends at
-- 01B2FFFF, so it cannot reach stderr)
-- 01B30000 stderr bytes (bit addresses, 8 bits apart; 16 KiB)
--
-- The block is above the linker-managed .bss region (01A00000..01A80000), so
-- test globals cannot overwrite it. The runner rejects len >= the 16 KiB cap
-- (or errlen >= the cap) because the shim truncates there.
--
-- The result is written to CONF_RESULT in a stable, shell-readable form:
-- status=<8 hex>
-- len=<decimal>
-- magic=<8 hex>
-- loader=<8 hex> (loader result block status at 01882D00)
-- out=<uppercase hex bytes>
-- errlen=<decimal>
-- err=<uppercase hex bytes>
--
-- The runner compares this file against the manifest/expected result. A
-- missing magic is a failure, never a pass.
dofile(os.getenv("M4_LOADER_LUA"))
local machine = manager.machine
local cpu = machine.devices[':maincpu']
local prog = cpu.spaces['program']
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local AT = tonumber(os.getenv("LOADER_AT") or "2500")
local RESULT = os.getenv("CONF_RESULT") or "conformance-result.txt"
local STATUS = 0x01B00000
local LEN = 0x01B00020
local MAGIC = 0x01B00040
local ERRLEN = 0x01B00060
local OUT = 0x01B10000
local ERR = 0x01B30000
local CAP = 16384
local MAGIC_VAL = 0x434F4E46
local LOADER_STATUS = 0x01882D00
local frames = 0
local done = false
local function rd32(a)
local ok, v = pcall(function() return prog:read_u32(a) end)
if ok then return v end
return 0xDEADBEEF
end
local function rd8(a)
local ok, v = pcall(function() return prog:read_u8(a) end)
if ok then return v end
return 0
end
-- Read raw_len bytes at bit address `base` (8 bits apart). Keep the raw
-- length for the runner (it rejects len >= CAP), but never loop over an
-- implausible value. Returns the full hex dump and its 128-byte preview.
local function dump_bytes(base, raw_len)
local bytes = {}
local shown = {}
local n = 0
local nread = raw_len
if nread < 0 or nread > CAP then
nread = 0
end
for i = 0, nread - 1 do
local b = rd8(base + i * 8)
bytes[#bytes + 1] = string.format("%02X", b)
if i < 128 then
shown[#shown + 1] = string.format("%02X", b)
end
n = n + 1
end
local shownhex = table.concat(shown)
if n > 128 then
shownhex = shownhex .. "..."
end
return table.concat(bytes), shownhex
end
local function dump(tag)
local status = rd32(STATUS)
local raw_len = rd32(LEN)
local raw_errlen = rd32(ERRLEN)
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
local outhex, shownhex = dump_bytes(OUT, raw_len)
local errhex, errshownhex = dump_bytes(ERR, raw_errlen)
print(string.format(
"CONF: %s status=%08X len=%d magic=%08X loader=%08X out=%s errlen=%d err=%s",
tag, status, raw_len, magic, loader, shownhex,
raw_errlen, errshownhex))
local f, err = io.open(RESULT, "w")
if not f then
print("CONF: cannot write result " .. tostring(RESULT) ..
": " .. tostring(err))
machine:exit()
return
end
f:write(string.format("status=%08X\n", status))
f:write(string.format("len=%d\n", raw_len))
f:write(string.format("magic=%08X\n", magic))
f:write(string.format("loader=%08X\n", loader))
f:write("out=" .. outhex .. "\n")
f:write(string.format("errlen=%d\n", raw_errlen))
f:write("err=" .. errhex .. "\n")
f:close()
if magic == MAGIC_VAL and loader == 0 then
print("CONF MAME: PASS")
else
print("CONF MAME: FAIL")
end
end
emu.register_frame_done(function()
frames = frames + 1
if frames <= AT or done then
return
end
local magic = rd32(MAGIC)
local loader = rd32(LOADER_STATUS)
-- A successful run publishes the magic. A loader error after injection
-- is final even if the app never starts. Otherwise wait for ENDF.
if magic == MAGIC_VAL or (frames > AT + 60 and loader ~= 0)
or frames >= ENDF then
done = true
dump(frames >= ENDF and "timeout" or "result")
machine:exit()
end
end, "m5-conformance-check")
+10
View File
@@ -0,0 +1,10 @@
; data-pad.asm -- keep the linked .data section a whole number of 16-bit words.
;
; llc emits an odd-length byte array (for example a 7-byte string literal)
; without a trailing word, so the concatenated .data section can end on an
; odd byte. The VT1200 COFF loader rejects a section whose bit size is not a
; whole number of words (status 4). This object is linked last in both the
; native and asm paths. GSPA aligns a .word directive to a 16-bit boundary,
; so this pads any preceding odd byte and then contributes exactly one word.
.data
.word 0
+72
View File
@@ -0,0 +1,72 @@
; entry.asm -- M5 conformance entry, linked at bit 018A0000.
;
; Calls the test's main(1, argv) through the M4 TI ABI and publishes the
; result for the MAME check:
;
; 01B00000 status main's return value
; 01B00020 out_len maintained by shim.c
; 01B00040 magic 0x434F4E46 after main returns
; 01B00060 err_len maintained by shim.c
; 01B10000 output shim.c's 16 KiB output buffer (ends at 01B2FFFF)
; 01B30000 error shim.c's 16 KiB stderr buffer
;
; The result block is above the linker-managed RAM region
; (01A00000..01A80000), so a test's .bss cannot overwrite it. That region is
; 64 KiB and this file reserves 4 KiB for _cstack; Tasks 11/12 should keep the
; sum of globals and stack under those limits.
;
; exit()/abort() in shim.c publish status and magic themselves and spin, so
; an abnormal test still leaves an observable result. argv is a real
; two-element vector: { "conformance", NULL }.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
; Clear the result cells that live outside every loaded section.
movi 01B00000h, a1
sub a0, a0
move a0, *a1, 1
movi 01B00020h, a1
move a0, *a1, 1
movi 01B00040h, a1
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
; argv[0] = "conformance", argv[1] = NULL.
movi _conformance_argv, a0
movi _conformance_name, a1
move a1, *a0, 1
sub a1, a1
move a1, *a0(32), 1
; main(1, argv): arguments are pushed in reverse order on A14.
move a14, -*sp, 1
move a0, *a14+, 1
movi 1, a1
move a1, *a14+, 1
calla _main
setf 16, 1, 0
setf 32, 0, 1
movi 01B00000h, a1
move a8, *a1, 1
movi 01B00040h, a1
movi 434F4E46h, a0
move a0, *a1, 1
rets
.data
_conformance_name:
.byte 063h, 06Fh, 06Eh, 066h, 06Fh, 072h, 06Dh, 061h
.byte 06Eh, 063h, 065h, 000h
.even
.bss _conformance_argv, 64, 1
.bss _cstack, 32768, 16
+57
View File
@@ -0,0 +1,57 @@
/*
* heap.c -- optional bounded allocator for the conformance shim.
*
* This object is linked only for tests whose source references
* malloc/calloc/free, so adding the allocator does not shift the hot shim
* code that the shipped 300/600-frame gates time. The arena is the 64 KiB gap
* between the linker RAM region (01A00000..01A80000) and the result block
* (01B00000); it lies outside every loaded section. free() is a no-op because
* each conformance test is a single short-lived process.
*/
#include <stddef.h>
#define CONF_HEAP_START 0x01A80000UL
#define CONF_HEAP_END 0x01B00000UL
static unsigned int heap_next;
/* Sizes are bytes; the target's pointers are bit addresses, so advance the
* cursor by 8 bits per byte. Align to a 16-bit word. */
void *malloc(size_t n)
{
unsigned int p;
n = (n + 1) & ~(size_t)1;
if (n == 0)
n = 2;
if (heap_next == 0)
heap_next = CONF_HEAP_START;
if (n > (CONF_HEAP_END - heap_next) / 8)
return 0;
p = heap_next;
heap_next += n * 8;
return (void *)p;
}
void *calloc(size_t nmemb, size_t size)
{
size_t total;
char *p;
size_t i;
if (nmemb != 0 && size > (size_t)~0 / nmemb)
return 0;
total = nmemb * size;
p = (char *)malloc(total);
if (!p)
return 0;
for (i = 0; i < total; i++)
p[i] = 0;
return p;
}
void free(void *ptr)
{
(void)ptr;
}
@@ -0,0 +1,14 @@
#ifndef CONFORMANCE_ASSERT_H
#define CONFORMANCE_ASSERT_H
/* The freestanding conformance runtime has no libc assert; abort() publishes
* the terminal status, so a failed assertion is an honest nonzero result. */
void abort(void);
#ifdef NDEBUG
#define assert(expr) ((void)0)
#else
#define assert(expr) ((expr) ? (void)0 : abort())
#endif
#endif
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff. Show more