148 Commits
m0 ... 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
arti 5d980dc6e3 tests/docs: final M4 review fixes 2026-11-12 12:23:04 +00:00
arti 1511919437 tests/docs: fix M4 review findings in bands, symbols and diff check 2026-11-12 12:04:36 +00:00
arti 2d5ed90fb2 tests: M4 Xlib images, events and the termtris integration 2026-11-12 11:49:32 +00:00
arti 1a91329864 tests: M4 termtris integration and varargs ABI gate
Build the pinned termtris branch (be5b323) with this compiler, assemble
and link it with the TI 1987 GSPA/GSPLNK and RTS.LIB, and run the proven
play_keys board/move/panels/quit paths in MAME with the M4 loader.  Add
the contiguous-stack varargs MAME probe and the switch-to-lookup driver
regression check.  The termtris build found the i8/i16 argument, i1/
anyext load, nested-data, MULHS and late-GEP gaps fixed in the compiler.
2026-11-12 10:51:15 +00:00
arti fb0159620e tests: validate the image blitter copy and assert window focus 2026-11-12 09:40:45 +00:00
arti 26697b9585 tests: M4 1-bit XImage, real key events, and the MAME image gate 2026-11-12 09:21:17 +00:00
arti 7946519828 symbols: correct XMapWindow, add XImage/XG entries and validation 2026-11-12 07:19:42 +00:00
arti 8cb060cdb4 tests: M4 X11R4 XImage/XEvent/error-event layout 2026-11-12 06:53:29 +00:00
arti 7a89a1fe4c tests: M4 function-pointer/indirect-call gate
Add the fnptr C callback test (direct symbol, volatile local pointer and
global pointer), its GSPA entry and marker script, and scripts/tests/m4/
fnptr.sh.  The gate compiles at the default -O2 pipeline, requires all four
markers to be 42 in MAME, and checks the linked assembly: _apply calls through
an A register (CALL, never CALLA) after the argument push, while _fnptr_test
keeps the direct CALLA and materialises inc with MOVI.  It also pins the GSPA
0x0920 encoding and requires dis34 to decode the call as 'call aN'.
2026-11-12 06:40:12 +00:00
arti d8efad2479 tests: use an unsigned helper for the wide multiply marker
The full-width marker called the signed mul helper with a constant whose
product overflows int, which is UB and made the assertion rely on wrap-around.
Add mulu(unsigned, unsigned) for marker 10; the low-32 product and MPYS
selection are unchanged.  Check the optimized IR has no nsw on mulu.
2026-11-12 06:21:31 +00:00
arti 00522b56fc tests: exercise wide 32-bit products and unsigned umul16
Add runtime markers for a full-width 32x32 multiply (0x12345678 * 0x9abcdef0
= 0x242d2080) and for a wide-dividend remainder, so a 16-bit-truncated MPYS or
a wrong FS1 cannot still produce the expected small results.  Compute the 16x16
unsigned product in unsigned arithmetic to remove the signed-overflow
annotation, and reject a regressed nuw nsw multiply in the optimized IR.
2026-11-12 06:17:29 +00:00
arti 7cd9a48ee3 tests: M4 multiply/divide and -O2 loop gates
Add a runtime marker test for 32x32 multiply, the 16x16 MPYU path, signed and
unsigned divide/remainder, and for sumto/squares compiled through the ordinary
tms-clang -O2 driver.  The linked assembly is also checked for MPYS/MPYU/
DIVS/DIVU and for a surviving sumto loop.
2026-11-12 06:04:56 +00:00
arti cfe751ccab driver: keep -O2 loops for the i64-less target
Scripts/tms-clang runs the generic opt pipeline without a target machine, so
the target cannot veto IndVarSimplify's exit-value replacement through TTI.
That rewrite turns sumto's closed form into an i33 multiply, which llc cannot
select.  Disable only that rewrite with -replexitval=never and document why.
2026-11-12 06:04:56 +00:00
arti 57ea80a5c0 tests: exercise every signed and unsigned predicate at runtime 2026-11-12 05:46:38 +00:00
arti 28c9ee7e3c tests: M4 unsigned runtime and private-label gates 2026-11-12 05:38:22 +00:00
arti dbf71bdc5f docs: M4 Xlib images, events and termtris integration plan 2026-11-12 05:23:33 +00:00
arti 24f877362b docs: finalize M3 limitations and M4 prerequisites 2026-11-11 20:30:37 +00:00
arti 2681be26c0 tests: anchor the M3 Xlib displacement checks 2026-11-11 20:06:58 +00:00
arti ed58040fbd docs: M3 control flow and first Xlib window 2026-11-11 19:56:19 +00:00
arti 09db9e22e9 tests: M3 branches and first Xlib window in MAME 2026-11-11 19:46:00 +00:00
arti b34016a9f3 docs: correct M3 ROM bit displacements and unaligned-load carry-forward 2026-11-11 19:14:05 +00:00
arti 2187f59b20 tests: M3 Xlib Display/Screen layout 2026-11-11 19:07:44 +00:00
arti d1ba1e4d86 docs: M3 control flow and first Xlib window plan 2026-11-11 17:54:01 +00:00
arti 2d4919db36 docs: finalize M2 ABI and tail-call notes 2026-11-11 17:36:17 +00:00
arti f1a604d70e docs: correct M2 branch and epilogue guidance 2026-11-11 17:15:43 +00:00
arti 3a188b35fb docs: M2 TI ABI, ROM strlen and golden ABI check 2026-11-11 17:05:33 +00:00
arti fa00b8740b docs: finish the M2 loader and returned reconciliation 2026-11-11 16:59:30 +00:00
arti b614e70851 docs: reconcile M2 plan with JAUC, returned, loader and .data alignment 2026-11-11 16:59:23 +00:00
arti 0008d7be20 tests: M2 TI ABI and ROM strlen in MAME 2026-11-11 16:50:06 +00:00
arti d4f165fa7d docs: record the M2 .data width and pointer-init rules 2026-11-11 16:35:43 +00:00
arti 3f30806a6d docs: require width-based .data emission for i8/i16 scalars 2026-11-11 16:24:29 +00:00
arti e7ba50d7a3 docs: add caller-side rejection tests to M2 2026-11-11 16:10:38 +00:00
arti 469b1d870e docs: require a spill-slot frame assertion in m2-spill 2026-11-11 15:55:18 +00:00
arti e60a1fdee9 docs: pin the M2 callee stack arithmetic in m2-args 2026-11-11 15:54:59 +00:00
arti 5e8dbffb01 docs: move the M2 spill test to Task 3 2026-11-11 15:21:09 +00:00
arti c0746338b0 docs: M2 TI ABI and ROM call implementation plan 2026-11-11 14:57:27 +00:00
arti 7749cc810b scripts: fix stale M1 comments and tighten the harness checks
Preserve the dis34 output on a failed round-trip instead of claiming a
deleted temp file is kept, require GSPA "No Warnings" in addition to
"No Errors", and correct the six-function and M1 pipeline comments.
2026-11-11 10:15:34 +00:00
arti eacaab68f6 docs: correct the GEP scaling warning and M1 data limits
Raw clang IR has byte GEP offsets that llc treats as bits, so addresses
are 8x too small; always run tms-clang/tms-bitaddr --scale first.
Document that M1 supports only zero-initialized globals and rejects
.data/string literals loudly, and defer the spec's .data initializer
probe to M2.
2026-11-11 10:15:32 +00:00
arti 937a8cc800 tms-bitaddr: make --normalize reject typed and vector GEPs
--normalize lowers GEP offsets as already-scaled bit offsets.  A typed
GEP still carries a DataLayout byte offset and a vector GEP has no
scalar lowering, so accepting either produced addresses 8x too small.
Check all instruction and constant-expression GEPs and fail clearly;
--scale still scales typed GEPs normally.  Add positive and negative
tool tests.
2026-11-11 10:15:30 +00:00
arti 56d6a71cb7 docs: M1 minimal backend and test convention 2026-11-11 09:53:23 +00:00
arti 755b3cb7b2 tests: link M1 char helpers and check MOVB 2026-11-11 08:53:41 +00:00
arti b638ab0fad tests: M1 dis34 round-trip 2026-11-11 08:43:17 +00:00
arti 6f776e1758 tests: pin the M1 .bss origin and second pointer marker 2026-11-11 08:39:58 +00:00
arti e0a721e3e1 tests: M1 GSPA/MAME smoke test 2026-11-11 08:31:19 +00:00
arti e081921b72 plan: M1 minimal TMS34010 backend 2026-11-11 06:47:05 +00:00
273 changed files with 36789 additions and 188 deletions

No files matched your search

+1640 -59
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,386 @@
# TMS34010 M1 — Minimal Backend 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:** `llc -march=tms34010` emits GSPA-compatible assembly for a leaf `int add(int, int)`, `int load(int *)` and `char` load/store, and that assembly assembles, links and runs in MAME. No TI ABI yet.
**Architecture:** Fill in the M0 target skeleton with TableGen register/instruction definitions, a minimal SelectionDAG selector, a provisional register-argument test convention, and an asm printer for GSPA syntax. Use `llc -filetype=asm` and the existing GSPA/gsplnk + COFF loader path. Object emission and the full TI ABI are later milestones.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `tms34010`), C++17, CMake/Ninja, `llc`, GSPA/gsplnk under 2ine, MAME, `dis34`, `llvm-lit`/FileCheck.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§7.4–§7.6, M1)
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `tms34010` (clone `build/llvm-m1`). Project plans/tests live in **`tms-c-compiler`**, branch `m1`.
- **M1 calling convention is a test convention, not the TI ABI:** integer/pointer arguments in `A0, A1, A2, A3`; return value in `A0`; leaf functions only; no calls, no stack arguments, no callee-saves, no structures/floats/varargs. M2 replaces this with A8/A13/A14/A15, `RETS 2`, and `FS1 = 32`.
- M1 compiles at `-O2`; any function needing a stack frame, a call, a structure, float, or an unsupported operation is a hard error, not a silent fallback.
- Output is **assembly only**: `llc -march=tms34010 -filetype=asm`. No LLVM object writer, `MCCodeEmitter` or linker in M1; GSPA assembles, gsplnk links, the existing COFF loader loads.
- M1 assembles with the **proven 1987 GSPA/GSPLNK 2.00 under DOSBox** (the path exercised by `vendor/vt1200/harness/c-hello/build.sh`), not the external 2ine r5.01 tools. 2ine is an M2 speed-up. The asm printer targets GSPA 2.00 syntax.
- GSPA syntax: hex constants `0…h`, lowercase mnemonics accepted, `movi` long form for 32-bit constants, field-select `,1` on 32-bit `MOVE`; the M1 entry sets `SETF 32,0,1` before calling compiled code.
- Symbols use the GSPA/TI leading underscore (`_add`); code is linked at a fixed bit address.
- No ROM/Xlib imports, no `malloc`, no `strlen`, no TI runtime in M1. M2 owns those.
- The M0 `patches/llvm` mirror is frozen; M1 uses the full compiler repo, not the patch mirror.
- Tests: LLVM lit/FileCheck for asm; a GSPA/2ine assemble-link step; a MAME run with marker words; a `dis34` round-trip of the emitted asm.
## Review Focus
1. **Test convention leakage:** no code path may claim TI ABI compatibility; calls/stack args must fail loudly. Tests in Task 2 and Task 4.
2. **`-O2` stack/spill/frame:** leaf functions must not silently use an unimplemented frame; `FrameLowering` must reject frame indices it cannot lower. Tests in Task 2/3.
3. **GSPA syntax and field select:** 32-bit `MOVE` must carry `,1`; `MOVB` is the 8-bit access and sign-extends. Tests in Task 3/4.
4. **Symbol/link address:** `_add` label, absolute `CALLA`, and bit-address placement must be consistent with the linker. Test in Task 4.
5. **Asm/encoding agreement:** GSPA's encoding of the emitted asm must match `dis34` for `ADD`, `MOVE`, `MOVB`, `RETS`; a mismatch means the asm printer is wrong. Test in Task 5.
---
### Task 1: M1 compiler checkout, build, and failing `llc` test
**Files:**
- Create: `build/llvm-m1/llvm/test/CodeGen/TMS34010/m1-add.ll` (compiler repo)
- Create: `build/llvm-m1/llvm/test/CodeGen/TMS34010/m1-call.ll`, `m1-frame.ll`, `m1-late-gep.ll` (compiler repo)
- Modify: `patches/llvm` is **not** changed in M1.
**Interfaces:**
- Consumes: M0 `tms34010` branch.
- Produces: a built `llc` that lists `tms34010`; the failing test that every later task makes pass.
- [ ] **Step 1: Clone the compiler repo and build**
```sh
mkdir -p build
git clone --depth 1 --branch tms34010 \
gitea@git.wut.ee:opencode.siil.arti.ee/llvm-tms34010.git \
build/llvm-m1
cmake -S build/llvm-m1/llvm -B build/llvm-m1-build -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON \
-DLLVM_ENABLE_PROJECTS=clang \
-DLLVM_TARGETS_TO_BUILD="X86;TMS34010" \
-DLLVM_INCLUDE_TESTS=ON -DLLVM_INCLUDE_EXAMPLES=OFF \
-DLLVM_INCLUDE_BENCHMARKS=OFF
ninja -C build/llvm-m1-build llc opt clang llvm-config FileCheck count not
```
Expected: build succeeds; `build/llvm-m1-build/bin/llc --version` lists `tms34010`.
- [ ] **Step 2: Write the failing asm test**
`build/llvm-m1/llvm/test/CodeGen/TMS34010/m1-add.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @add(i32 %a, i32 %b) {
entry:
%r = add i32 %a, %b
ret i32 %r
}
; CHECK-LABEL: _add:
; CHECK: ADD A{{[0-9]+}}, A{{[0-9]+}}
; CHECK: RETS 0
```
- [ ] **Step 3: Run it to verify it fails**
```sh
build/llvm-m1-build/bin/llvm-lit -v \
build/llvm-m1-build/test/CodeGen/TMS34010 --filter='m1-add'
```
Expected: FAIL — `llc` reports that the target cannot emit assembly / no instruction selector (the M0 `addPassesToEmitFile` is still a stub).
- [ ] **Step 4: Commit the failing test in the compiler repo**
```sh
git -C build/llvm-m1 add llvm/test/CodeGen/TMS34010/m1-add.ll
git -C build/llvm-m1 commit -m "tms34010: add failing M1 add codegen test"
```
### Task 2: Minimal `add` codegen (registers, ISel, asm printer)
**Files:**
- Create/modify under `build/llvm-m1/llvm/lib/Target/TMS34010/`:
- `TMS34010.td`, `TMS34010RegisterInfo.td`, `TMS34010InstrInfo.td`
- `TMS34010RegisterInfo.{h,cpp}`, `TMS34010InstrInfo.{h,cpp}`
- `TMS34010ISelLowering.{h,cpp}`, `TMS34010ISelDAGToDAG.cpp`
- `TMS34010FrameLowering.{h,cpp}`
- `TMS34010AsmPrinter.cpp`, `TMS34010MCInstLower.{h,cpp}`
- `MCTargetDesc/TMS34010MCAsmInfo.{h,cpp}`, `TMS34010InstPrinter.{h,cpp}`, `TMS34010MCTargetDesc.{h,cpp}`
- `TMS34010Subtarget.{h,cpp}`, `TMS34010TargetMachine.{h,cpp}`, CMake files
- Test: `build/llvm-m1/llvm/test/CodeGen/TMS34010/m1-add.ll`
**Interfaces:**
- Consumes: `llc`/M0 target skeleton.
- Produces: `TMS34010TargetLowering` with a provisional `LowerFormalArguments`/`LowerReturn`; `TMS34010InstrInfo` with `ADD`/`RETS`/`MOVI`; `TMS34010AsmPrinter` emitting GSPA asm; `TMS34010Subtarget` wired into a `CodeGenTargetMachineImpl`.
- [ ] **Step 1: Define registers and the minimal instructions**
`TMS34010RegisterInfo.td`: define `A0`–`A15` and `B0`–`B15` (B regs reserved for a later task), an `ARegs` register class (use A0–A7 in M1 patterns). `TMS34010InstrInfo.td`: define `MOVI` (32-bit immediate, 3 words), `ADD` (register), `RETS` (with N immediate), `CLR`, `NOP`; include `AsmString` for GSPA syntax. Keep the encodings in the definitions, but M1 only needs the asm printer.
- [ ] **Step 2: Wire the target machine and subtarget**
Switch `TMS34010TargetMachine` to `CodeGenTargetMachineImpl` with the M0 data layout string, `TMS34010Subtarget` and `TargetLoweringObjectFileELF`; implement `createPassConfig` (`addInstSelector`, asm printer), `getSubtargetImpl`, `getObjFileLowering`, and `addInstSelector` returning a `TMS34010ISelDag`. Register `MCAsmInfo`, `MCInstrInfo`, `MCRegisterInfo`, `MCSubtargetInfo`, `MCInstPrinter`; no code emitter.
- [ ] **Step 3: Implement the provisional convention and patterns**
`TMS34010TargetLowering`:
- `addRegisterClass(MVT::i32, &TMS34010::ARegsRegClass)`, `computeRegisterProperties`.
- `LowerFormalArguments`: `i32`/pointer args 0..3 → `CCValAssign::getReg` `A0..A3`; more args → `llvm_unreachable`/`report_fatal_error("M1 supports at most four register arguments")`. M1 accepts only 32-bit scalar/pointer arguments; narrow C values are promoted/truncated in IR.
- `LowerReturn`: `i32`/pointer result → `A0`; `void` is allowed; anything else → `report_fatal_error`.
- `LowerCall`: `report_fatal_error("M1 has no calls; M2 adds the TI ABI")`.
- `CanLowerReturn` only for `i32`/pointer.
TableGen patterns: `add i32` → `ADD`; `ret` with A0 → `RETS 0`; `i32` constants → `MOVI`. `TMS34010FrameLowering` has no prologue/epilogue and `getFrameIndexReference` calls `report_fatal_error` for any frame index (M1 has no stack).
M1 is asm-only: define the instruction encodings in TableGen for future use, but do not add an `MCCodeEmitter` or object writer. GSPA/dis34 validate the asm in Task 5.
`m1-call.ll` pins the call refusal:
```llvm
; RUN: not llc -march=tms34010 -O2 -filetype=asm < %s 2>&1 | FileCheck %s
; CHECK: M1 has no calls
declare i32 @callee(i32)
define i32 @caller(i32 %x) {
%r = call i32 @callee(i32 %x)
ret i32 %r
}
```
`m1-late-gep.ll` pins the §7.3.1 contract at `llc`: a surviving GEP offset is in bits, not bytes.
```llvm
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define i32 @late(ptr %p) {
%g = getelementptr i8, ptr %p, i32 24
%v = ptrtoint ptr %g to i32
ret i32 %v
}
; CHECK: ADDI 24
; CHECK-NOT: ADDI 192
```
`m1-frame.ll` pins the no-stack refusal:
```llvm
; RUN: not llc -march=tms34010 -O0 -filetype=asm < %s 2>&1 | FileCheck %s
; CHECK: M1 has no stack frame
define i32 @frame(i32 %n) {
%a = alloca i32
store i32 %n, ptr %a
%v = load i32, ptr %a
ret i32 %v
}
```
- [ ] **Step 4: Run the lit tests to verify they pass**
```sh
build/llvm-m1-build/bin/llvm-lit -v \
build/llvm-m1-build/test/CodeGen/TMS34010 --filter='m1-(add|call|frame|late-gep)'
```
Expected: PASS — the `add` asm, the call/alloca refusals, and `ADDI 24` (not 192) for the bit-offset GEP.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-m1 add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m1-add.ll \
llvm/test/CodeGen/TMS34010/m1-call.ll llvm/test/CodeGen/TMS34010/m1-frame.ll \
llvm/test/CodeGen/TMS34010/m1-late-gep.ll
git -C build/llvm-m1 commit -m "tms34010: minimal add codegen with GSPA asm"
```
### Task 3: Loads, stores and 8-bit accesses
**Files:**
- Modify: `build/llvm-m1/llvm/lib/Target/TMS34010/TMS34010InstrInfo.td`, `TMS34010ISelLowering.cpp`, `TMS34010ISelDAGToDAG.cpp`, `TMS34010FrameLowering.cpp`
- Create: `build/llvm-m1/llvm/test/CodeGen/TMS34010/m1-load.ll`, `m1-char.ll`
**Interfaces:**
- Consumes: Task 2 selector/asm printer.
- Produces: `MOVE` (32-bit load/store) and `MOVB` (8-bit load/store) patterns with GSPA field select.
- [ ] **Step 1: Write the failing tests**
`m1-load.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @load(ptr %p) {
%v = load i32, ptr %p
ret i32 %v
}
; CHECK-LABEL: _load:
; CHECK: MOVE *A{{[0-9]+}}, A{{[0-9]+}}, 1
; CHECK: RETS 0
```
`m1-char.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @loadb(ptr %p) {
%v = load i8, ptr %p
%r = sext i8 %v to i32
ret i32 %r
}
define void @storeb(ptr %p, i32 %v) {
%t = trunc i32 %v to i8
store i8 %t, ptr %p
ret void
}
; CHECK-LABEL: _loadb:
; CHECK: MOVB *A{{[0-9]+}}, A{{[0-9]+}}
; CHECK-LABEL: _storeb:
; CHECK: MOVB A{{[0-9]+}}, *A{{[0-9]+}}
```
- [ ] **Step 2: Run them to verify they fail**
```sh
build/llvm-m1-build/bin/llvm-lit -v \
build/llvm-m1-build/test/CodeGen/TMS34010 --filter='m1-(load|char)'
```
Expected: FAIL — no load/store patterns or `MOVE`/`MOVB` definitions.
- [ ] **Step 3: Add `MOVE`/`MOVB` and selection**
Define `MOVE` with a field-select immediate and `MOVB` in the `.td`; add DAG patterns for `load i32`/`store i32` → `MOVE` with `,1`, and `load i8`/`store i8` → `MOVB`. Set `i8`/`i16` load/store legalization to custom where needed. Keep `-O2` leaf-only; any frame index remains a hard error.
- [ ] **Step 4: Run the tests to verify they pass**
Run the same lit filter. Expected: PASS.
- [ ] **Step 5: Commit**
```sh
git -C build/llvm-m1 add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m1-load.ll llvm/test/CodeGen/TMS34010/m1-char.ll
git -C build/llvm-m1 commit -m "tms34010: add MOVE/MOVB load-store codegen"
```
### Task 4: Assemble, link and run in MAME
**Files:**
- Create: `scripts/m1/add.c`, `scripts/m1/load.c`, `scripts/m1/late.c`, `scripts/m1/const_gep.c`, `scripts/m1/entry.asm`, `scripts/m1/link.cmd`, `scripts/m1/run.sh` (project repo)
- Create: `scripts/tests/m1/run.sh` (project repo)
- Reuse: `vendor/vt1200`, `dwt/loader`, `harness/c-hello` patterns
**Interfaces:**
- Consumes: `llc` asm from Tasks 2–3; GSPA/GSPLNK 2.00 under DOSBox; existing COFF loader.
- Produces: a MAME run whose marker words prove `add(20,22) == 42`, a word load, the late-GEP offset 24, and a `&arr[1]` constant-GEP relocation.
- [ ] **Step 1: Write the harness**
`scripts/m1/entry.asm` sets `SETF 32,0,1`, loads `A0 = 20`, `A1 = 22`, `CALLA _add`, stores `A0` at marker `0x018A8000`, repeats a `load` test, then calls `_second` and stores the returned `&arr[1]`, and `RETS`. Link `.text` at bit `0x018A0000` with `gspa`/`gsplnk` 2.00 under DOSBox and a `link.cmd` written with CRLF.
`add.c` is `int add(int a,int b){return a+b;}`, `load.c` is `int load(int *p){return *p;}`, `late.c` is `int late(char *p, char *q){return (char *)((unsigned)p + 24) == q;}`, and `const_gep.c` is `static int arr[4]; int *second(void){return &arr[1];}`. The harness pipeline is:
```sh
TMS_CLANG=$PWD/build/llvm-m1-build/bin/clang \
TMS_OPT=$PWD/build/llvm-m1-build/bin/opt \
TMS_BITADDR=$PWD/tools/tms-bitaddr/tms-bitaddr \
scripts/tms-clang -O2 -o /tmp/add.ll scripts/m1/add.c
build/llvm-m1-build/bin/llc -march=tms34010 -O0 -filetype=asm \
/tmp/add.ll -o /tmp/add.s
```
`llc -O0` is deliberate: the IR is already scaled/normalized by `tms-clang`, and M1 does not want a second optimization pipeline recreating GEPs. The target must still treat a surviving GEP offset as bits (`m1-late-gep.ll`). Repeat for `load.c`, `late.c` and `const_gep.c`; check the `late.s` for `ADDI 24` (not 192), and the `const_gep.s` for `@arr+32` (bits, not `+4` bytes). Concatenate with `entry.asm`, assemble/link, and load via `dwt/loader/loader.lua`/MAME.
The SDK is the 1987 DOSBox path:
```sh
sudo apt-get install -y dosbox mtools
IMG="$PWD/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img"
mkdir -p build/m1-sdk
mcopy -s -n -i "$IMG" "::/A2/*" build/m1-sdk/
mcopy -s -n -i "$IMG" "::/C2/*" build/m1-sdk/
```
Invoke `gspa`/`gsplnk` in DOSBox the way `vendor/vt1200/harness/c-hello/build.sh` does; keep the linker command file CRLF.
- [ ] **Step 2: Run it to verify it fails**
Run `scripts/tests/m1/run.sh`. Expected: FAIL because `llc` does not yet emit the expected asm or the harness is missing.
- [ ] **Step 3: Fix the asm/link integration**
Adjust the asm printer's directives/labels or the linker command as needed; if `late.c`/`const_gep.c` expose missing GEP or global-address lowering, fix it in the compiler repo (target ISel/asm printer), not in the harness. Keep the harness in the project repo. Do not add ROM calls or TI ABI.
- [ ] **Step 4: Run it to verify it passes**
Expected: marker `42` (and the loaded word marker) in MAME; `scripts/tests/m1/run.sh` prints `M1 MAME: PASS`.
- [ ] **Step 5: Commit both repos**
```sh
git -C build/llvm-m1 add llvm/lib/Target/TMS34010
git -C build/llvm-m1 commit -m "tms34010: align asm output with GSPA link path"
git add scripts/m1 scripts/tests/m1
git commit -m "tests: M1 GSPA/MAME smoke test"
```
### Task 5: `dis34` round-trip of the emitted assembly
**Files:**
- Create: `scripts/m1/dis-roundtrip.sh` (project repo)
- Create: `scripts/tests/m1/dis-roundtrip.sh` (project repo)
**Interfaces:**
- Consumes: the linked/extracted `.text` bytes and `tools/smart34010/dis34`.
- Produces: a byte/mnemonic check that GSPA's encoding of the emitted `ADD`/`MOVE`/`MOVB`/`RETS` matches `dis34`.
- [ ] **Step 1: Write the failing check**
The script extracts the linked `.text` bytes, runs `dis34`, and greps for the emitted instructions at the expected addresses. Initially it fails because the harness/asm path is not yet complete.
- [ ] **Step 2: Run it to verify it fails**
Run `scripts/tests/m1/dis-roundtrip.sh`. Expected: FAIL.
- [ ] **Step 3: Reconcile asm and encoding**
If a mnemonic or operand is wrong, fix the asm printer (compiler repo); if the byte extraction/address is wrong, fix the script. Do not add an LLVM object writer or MCCodeEmitter in M1.
- [ ] **Step 4: Run it to verify it passes**
Expected: `M1 dis34 round-trip: PASS`.
- [ ] **Step 5: Commit**
```sh
git add scripts/m1/dis-roundtrip.sh scripts/tests/m1/dis-roundtrip.sh
git commit -m "tests: M1 dis34 round-trip"
```
### Task 6: Document and push M1
**Files:**
- Modify: `README.md` (project repo) — M1 status/commands
- Modify: `build/llvm-m1/TMS34010.md` (compiler repo) — M1 backend/test convention
- Modify: `scripts/build-llvm.sh` (project repo) — optional `LLVM_FORK`/branch path
- Push: compiler repo `tms34010`, project repo `m1`
**Interfaces:**
- Consumes: all previous tasks.
- Produces: a documented M1 snapshot and branches others can clone.
- [ ] **Step 1: Update the docs**
State clearly: M1 is a **test-only register convention**, no TI ABI, no calls/ROM; M2 is the ABI. Document `llc -march=tms34010 -O2 -filetype=asm`, the GSPA/2ine path, and the MAME test. Do not claim `clang -c` or object output works.
- [ ] **Step 2: Run the M1 gates from the documented commands**
Run the lit filter, `scripts/tests/m1/run.sh`, and `scripts/tests/m1/dis-roundtrip.sh` using the documented build path. Expected: all green.
- [ ] **Step 3: Commit and push**
```sh
git -C build/llvm-m1 push origin tms34010
git add README.md docs scripts
git commit -m "docs: M1 minimal backend and test convention"
git push origin m1
```
---
## Execution Handoff
This plan is M1 only. The TI ABI (A8/A13/A14/A15, dual stack, `RETS 2`, `FS1`), ROM imports, Xlib and real clients are M2–M5 and get separate plans. The compiler repo is the canonical source for target code; this project repo holds the plans, wrappers, symbols and integration tests.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,685 @@
# TMS34010 M3 — Control Flow and the First Xlib Window 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:** A compiled C program calls the ROM Xlib (`XOpenDisplay`, `XCreateSimpleWindow`, `XMapWindow`, `XSync`), creates and maps a window, and that window appears in MAME; the backend also gains integer control flow (branches, comparisons, loops) for real C.
**Architecture:** M3 keeps the M2 asm-only path and TI ABI. It adds `JAcc`-based branches with GSPA-safe basic-block labels, `CMP`/condition-code lowering for `BRCOND`/`BR_CC`/`SETCC`/`SELECT_CC`, and the integer ALU/shift operations C control flow needs. It then adds a ROM-verified minimal `Display`/`Screen` layout and the four proven Xlib entry points, and an M3 harness that compiles C, links the `JAUC` stubs, loads the COFF in MAME, and checks both ABI markers and a window pixel.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m3`), C++17, CMake/Ninja, `llc`, GSPA/GSPLNK 2.00 under DOSBox, COFF loader, MAME, `dis34`, `llvm-lit`/FileCheck, 1987 TI compiler as a differential oracle.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§4.2, §7.3.1, §7.4–§7.7, §7.9, M3, M4)
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `m3`, created from `m2` at `39512c272d0f`. Use the existing full-fork checkout `build/llvm-clean` and build tree `build/llvm-clean-build`; do not clone another LLVM tree.
- Project plans/tests live in **`tms-c-compiler`**, branch `m3`, created from `m2` at `2d4919d` plus the M3 plan commit. The M2 branches stay the default snapshot until M3 is reviewed; do not merge M2 into `m0`.
- The M2 TI ABI is unchanged: A8 return, A13 FP, A14 STK, A15 SP; reverse argument pushes; first argument at `FP(-32)`; old-STK save/restore; `RETS 2/0`; callee-saved A0–A12 except A8; `SETF 16,0,0` + `SETF 32,0,1` at entry and after every call; `.data` width/alignment rules.
- M3 output is still **assembly only**: `llc -march=tms34010 -filetype=asm`; GSPA/GSPLNK 2.00 under DOSBox; the existing COFF loader. No LLVM object writer, `MCCodeEmitter`, asm parser or linker.
- **Branches use `JAcc` absolute 3-word forms in M3** (`JAUC`/`JAEQ`/`JALT`/…). Do not add `JR` relative branches or branch relaxation in M3; `JR`/relaxation is a later code-size task. GSPA resolves the absolute target.
- **Basic-block labels must be GSPA-valid.** GSPA 2.00 rejects dotted ELF names (`.L`, `_.str`). Set the MC private/linker-private prefixes so block labels are `LBB…`/`L…` with no dot; test a two-block function through GSPA.
- **Flags are modeled with a reserved `ST` pseudo-register:** `CMP`/`CMPI` define it, conditional branches and `SETCC` sequences use it. Do not silently drop the compare-to-branch dependency.
- **CMP operand order:** for `icmp <pred> a, b` the compare must compute `a - b` (the branch condition reads the flags for `a <pred> b`). The signed/unsigned conditions map to the TMS34010 condition codes in `dis34`: `uc/p/ls/hi/lt/ge/le/gt/c/nc/eq/ne/v/nv/n/nn` (0–15).
- M3 scalar control flow: i32/pointer values, signed and unsigned integer compares, `and`/`or`/`xor`/`shl`/`lshr`/`ashr`/`sub`/`neg`/`not`; no switch tables, indirect branches, floats, i64, or function pointers in M3.
- **Xlib is ROM-v2.2 only.** Use the four known-good entries from `symbols/vt1200-v22.syms`: `XOpenDisplay 0x3F9C2570`, `XCreateSimpleWindow 0x3FD41B90`, `XMapWindow 0x3FD64F60`, `XSync 0x3FD9F6B0`. (`0x3FD645B0` is `XRaiseWindow`, not `XMapWindow`; the M4 correction verified it.) The stubs are `JAUC <address>h`; `CALLA _XOpenDisplay` reaches the ROM function.
- **Display/Screen layout is ROM-specific:** xhello's `*a11(0480h)`/`*a10(040h)` are **bit displacements**, so `Display.screens` is the 32-bit pointer at **byte 0x90** (bit `0x480`) and `Screen.root` is the 32-bit root id at **byte 0x8** (bit `0x40`). M3 uses a minimal `scripts/m3/vt1200_xlib.h` with byte pads 0x90/0x8 and `_Static_assert`s, returning the ROM's bit offsets `0x480`/`0x40`; do not assume the host X11R7 `_XDisplay` layout matches the ROM. The full X11R4 `XImage`/`XEvent` headers are M4.
- `XOpenDisplay("0::0")` must run in the loader-created `create_process` child, not the rdebug dispatcher; the M2 `_start`/loader path satisfies this.
- `XCreateSimpleWindow` takes 9 arguments: `display, parent, x, y, width, height, border_width, border, background`; the first argument is at `FP(-32)`, the ninth at `FP(-288)`; `RETS 2`.
- M3 must observe a window, not only markers: the harness creates the window with **background pixel 1 (white)**, maps it, calls `XSync`, and checks a pixel inside the client area in emulated VRAM (base bit `0x04000000`, VRAM pitch 2048 bits on the default VR319 monitor, LSB-first). No fake pass.
- The M2 `m2-*` suite must stay green; M3 adds an `m3-*` suite. Do not regress the single-basic-block ABI tests.
- Tests: LLVM lit/FileCheck for branch/compare/op shapes; a GSPA assemble/link probe for block labels; a MAME run with branch results and a window pixel; a `dis34` round-trip; a TI-compiler golden check for branch/struct/call shape.
## Review Focus
1. **Branch target and label correctness:** GSPA block labels must have no dot; `JAUC`/`JCC` must target the right block; a wrong label jumps into data. Tests in Task 1 (`m3-branch`, GSPA probe) and Task 2 (`m3-loop`).
2. **Compare polarity and signedness:** the `CMP` operand order and `JALT`/`JALO`/`JAHI`/`JAEQ` mapping must match the C predicate; a reversed condition silently returns the wrong value. Tests in Task 2 (`m3-setcc`, `m3-if`, `m3-unsigned`) and Task 4 (`sumto(10)==55`, `max(20,22)==22`, `lt(5,7)==1` in MAME).
3. **Stack/FS invariants on every path:** prologue, multiple return blocks, loops and calls must keep A14/A15 balanced and FS0/FS1 correct; the old-STK/`RETS` rules still apply. Tests in Task 2 (loop returns) and Task 4 (MAME).
4. **Display/Screen offsets and root retrieval:** `Display.screens` at byte 0x90 (bit displacement 0x480), then `Screen.root` at byte 0x8 (bit 0x40); a wrong screen/root pointer yields no window or a crash. Tests in Task 3 (static asserts + TI golden) and Task 4 (window).
5. **Nine-argument `XCreateSimpleWindow` order:** all nine slots, first at `FP(-32)`, last at `FP(-288)`; a wrong order maps the wrong rectangle or parent. Tests in Task 4 (`dis34` push count and MAME window).
6. **The window really appears:** the loader child, the X server, `XSync`, a white client-area pixel; marker-only success is not enough. Test in Task 4.
---
### Task 1: Branch infrastructure, unconditional branches, GSPA-safe block labels
**Files:**
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/TMS34010InstrInfo.td`, `TMS34010InstrInfo.cpp`, `TMS34010InstrInfo.h`
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/MCTargetDesc/TMS34010MCAsmInfo.cpp`
- Test: `build/llvm-clean/llvm/test/CodeGen/TMS34010/m3-branch.ll`
**Interfaces:**
- Consumes: M2 target, MCInstLower's `MO_MachineBasicBlock` lowering, asm printer.
- Produces: `JUncond` (`JAUC <target>`), a `brtarget` operand, `AnalyzeBranch`/`InsertBranch`/`RemoveBranch`, GSPA-safe block labels.
- [ ] **Step 1: Check out the M3 branches**
The controller creates compiler `m3` from `m2` at `39512c272d0f` and project `m3` from `m2` at `2d4919d` plus the M3 plan commit.
```sh
cd /home/arti/code/tms-c-compiler
git checkout m3
git -C build/llvm-clean checkout m3
git -C build/llvm-clean rev-parse --short HEAD # based on 39512c272d0f
git rev-parse --short HEAD # plan commit on top of 2d4919d
```
If a branch is missing, create it with `git checkout -b m3 m2` (project) or `git -C build/llvm-clean checkout -b m3 m2` (compiler).
- [ ] **Step 2: Write the failing branch test**
`m3-branch.ll`:
```llvm
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define void @spin() {
entry:
br label %loop
loop:
br label %loop
}
; CHECK-LABEL: _spin:
; CHECK: [[L:LBB[0-9_]+]]:
; CHECK: JAUC [[L]]
```
The self-loop keeps the unconditional branch through code layout; a `br` to the immediate fallthrough can be removed by block placement even at `-O0`. This is a compile-only shape test; the executable branch tests are in Task 2 and Task 4.
- [ ] **Step 3: Run it red**
```sh
build/llvm-clean-build/bin/llvm-lit -v \
build/llvm-clean-build/test/CodeGen/TMS34010 --filter='m3-branch'
```
Expected: FAIL — `Cannot select: br` (M2 has no branch).
- [ ] **Step 4: Add `JUncond`, the branch target operand, and block-label prefixes**
In `TMS34010InstrInfo.td`:
```tablegen
def JUncond : TMS34010Inst<(outs), (ins brtarget:$target), "JAUC $target",
[(br bb:$target)]> {
let isBranch = 1;
let isTerminator = 1;
let isBarrier = 1;
let Size = 6;
}
```
`brtarget` is the standard `Target.td` branch-target operand; the `br` pattern selects the unconditional branch. `JAUC` is the GSPA unconditional absolute jump (the M2 ROM stub already uses it; bare `ja` is rejected by GSPA 2.00).
In `TMS34010MCAsmInfo.cpp`, set GSPA-safe label prefixes (the default `.L`/`l` contains a dot):
```cpp
PrivateGlobalPrefix = "L";
LinkerPrivateGlobalPrefix = "L";
```
The base asm printer then emits block labels such as `LBB0_1`; verify the actual spelling with the test and adjust the prefix if needed (no dot, GSPA-valid).
- [ ] **Step 5: Implement the branch hooks**
In `TMS34010InstrInfo`:
- `analyzeBranch(MBB, TBB, FBB, Cond)`: if the last terminator is `JUncond`, set `TBB` to its target and `FBB` to null; leave `Cond` empty. Return false. (M3 branches are self-contained `JAcc` instructions; do not invent a separate condition instruction.)
- `insertBranch(MBB, TBB, FBB, Cond, DL)`: insert `JUncond` for `TBB`; M3 has no conditional branch yet, so `FBB` must be null.
- `removeBranch(MBB)`: remove `JUncond` terminators.
- Keep `getInstSizeInBytes` at the `Size` field (bytes); `JUncond` is 6 bytes.
The MCInstLower already lowers `MO_MachineBasicBlock` to the block symbol; the InstPrinter prints the expression; the `PrivateGlobalPrefix` handles the label text.
- [ ] **Step 6: Run the lit test and the GSPA label probe**
```sh
build/llvm-clean-build/bin/llvm-lit -v \
build/llvm-clean-build/test/CodeGen/TMS34010 --filter='m3-branch'
```
Expected: PASS. Then:
```sh
build/llvm-clean-build/bin/llc -march=tms34010 -O0 -filetype=asm \
build/llvm-clean/llvm/test/CodeGen/TMS34010/m3-branch.ll -o /tmp/m3-branch.s
printf '\t.end\n' >> /tmp/m3-branch.s
# assemble under DOSBox with the M1 recipe; require No Errors, No Warnings
```
The GSPA listing must show the two `JAUC LBB…` instructions and the matching `LBB…:` label, with no `.L`/`_` dotted label.
- [ ] **Step 7: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010/m3-branch.ll
git -C build/llvm-clean commit -m "tms34010: add JAcc branches and GSPA-safe block labels"
```
### Task 2: Comparisons, conditional branches, SETCC/SELECT, loops, and integer ALU
**Files:**
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/TMS34010RegisterInfo.td` (reserved `ST`)
- Modify: `TMS34010InstrInfo.td` (`CMP`, `CMPI`, `JAEQ`…`JANN`, `AND`/`OR`/`XOR`, `SLL`/`SRL`/`SRA`, `SUB`, `NEG`, `NOT`)
- Modify: `TMS34010ISelLowering.cpp/.h` (`LowerBR_CC`, `LowerBRCOND`, `LowerSETCC`, `LowerSELECT_CC`, operation actions)
- Modify: `TMS34010InstrInfo.cpp` (conditional `AnalyzeBranch`/`InsertBranch`/`RemoveBranch`)
- Test: `m3-if.ll`, `m3-setcc.ll`, `m3-loop.ll`, `m3-unsigned.ll`, `m3-ops.ll`
**Interfaces:**
- Consumes: Task 1's `JUncond`, block labels, asm printer.
- Produces: `CMP`/`CMPI` with a reserved `ST` flag register; the 16 `JA<cc>` branch instructions; `SETCC`/`SELECT_CC`/`BRCOND` lowering; ALU/shift patterns.
- [ ] **Step 1: Write the failing tests**
`m3-setcc.ll`:
```llvm
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define i32 @lt(i32 %a, i32 %b) {
entry:
%c = icmp slt i32 %a, %b
%r = zext i1 %c to i32
ret i32 %r
}
; CHECK-LABEL: _lt:
; CHECK: CMP
; CHECK: JALT
; CHECK: MOVI 0
; CHECK: MOVI 1
; CHECK: RETS 2
```
`m3-if.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @max(i32 %a, i32 %b) {
entry:
%c = icmp sgt i32 %a, %b
%r = select i1 %c, i32 %a, i32 %b
ret i32 %r
}
; CHECK-LABEL: _max:
; CHECK: CMP
; CHECK: JAGT
; CHECK: RETS 2
```
`m3-loop.ll` (a real phi/loop, run at `-O0` to keep the loop shape):
```llvm
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define i32 @sumto(i32 %n) {
entry:
br label %loop
loop:
%i = phi i32 [ 1, %entry ], [ %i.next, %loop ]
%s = phi i32 [ 0, %entry ], [ %s.next, %loop ]
%s.next = add i32 %s, %i
%i.next = add i32 %i, 1
%c = icmp sle i32 %i, %n
br i1 %c, label %loop, label %exit
exit:
ret i32 %s
}
; CHECK-LABEL: _sumto:
; CHECK: CMP
; CHECK: JALE
; CHECK: JAUC
; CHECK: RETS 2
```
`m3-unsigned.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @ult(i32 %a, i32 %b) {
entry:
%c = icmp ult i32 %a, %b
%r = zext i1 %c to i32
ret i32 %r
}
define i32 @ugt(i32 %a, i32 %b) {
entry:
%c = icmp ugt i32 %a, %b
%r = zext i1 %c to i32
ret i32 %r
}
; CHECK-LABEL: _ult:
; CHECK: JALO
; CHECK-LABEL: _ugt:
; CHECK: JAHI
```
`m3-ops.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @ops(i32 %a, i32 %b) {
entry:
%s = sub i32 %a, %b
%an = and i32 %s, %a
%o = or i32 %an, %b
%x = xor i32 %o, %s
%l = shl i32 %x, 3
%r = lshr i32 %l, 2
%q = ashr i32 %r, 1
ret i32 %q
}
; CHECK: SUB
; CHECK: AND
; CHECK: OR
; CHECK: XOR
; CHECK: SLL
; CHECK: SRL
; CHECK: SRA
; CHECK: RETS 2
```
- [ ] **Step 2: Run them red**
```sh
build/llvm-clean-build/bin/llvm-lit -v \
build/llvm-clean-build/test/CodeGen/TMS34010 --filter='m3-(if|setcc|loop|unsigned|ops)'
```
Expected: FAIL — `Cannot select: brcond`, `setcc`, ALU/shift opcodes.
- [ ] **Step 3: Add the reserved status register and instructions**
In `TMS34010RegisterInfo.td`, add a reserved non-allocatable `ST` pseudo-register (`Register<32>` with `Namespace = "TMS34010"`; not in `ARegs`/`ARegsAll`/`BRegs`). Reserve it in `getReservedRegs`.
In `TMS34010InstrInfo.td`, add:
- `CMP` (`CMP $src, $dst`, 1 word, `isCompare = 1`, `Defs = [ST]`; encoding base `0x4800`).
- `CMPI` (`CMPI $imm, $dst`, 3 words, `Defs = [ST]`; encoding base `0x0B60`, word form `0x0B40`).
- `AND`/`OR`/`XOR` (`$src, $dst`, base `0x5000`/`0x5400`/`0x5600`; `XOR` self is `CLR`).
- `SUB` (`SUB $src, $dst`, base `0x4400`), `NEG` (`NEG $dst`, base `0x03A0`), `NOT` (`NOT $dst`, base `0x03E0`).
- `SLL`/`SRL`/`SRA` register forms (`0x6200`/`0x6600`/`0x6400`) and immediate-constant forms if needed for the patterns.
- 16 absolute conditional branches: `JAEQ`, `JANE`, `JALT`, `JALE`, `JAGT`, `JAGE`, `JALO`/`JAC`, `JAHS`/`JANC`, `JALS`, `JAHI`, `JAP`, `JAN`, `JAV`, `JANV`, `JANN`, and `JAUC`; each `(ins brtarget:$target)`, `isBranch=1`, `isTerminator=1`, `Uses=[ST]` (except `JAUC`), `Size=6`; conditional branches are **not** `isBarrier` (they fall through), while `JAUC` is `isBarrier=1`; asm `"JA<cc> $target"` (GSPA mnemonics; `UC` unconditional).
Add patterns for the register/immediate ALU forms where the SelectionDAG can select them directly; otherwise lower them in `TMS34010ISelLowering`/`ISelDAGToDAG`.
- [ ] **Step 4: Lower comparisons and branches**
In `TMS34010TargetLowering`:
- `setOperationAction(ISD::SETCC, MVT::i32, Expand)`; `SELECT`/`SELECT_CC` `Expand`; `BR_CC`/`BRCOND` `Custom`.
- Override `LowerBR_CC` and `LowerBRCOND`:
- For `icmp <pred> a, b`, emit `CMP b, a` (so the flags represent `a - b`), then the `JA<cc>` selected from the predicate and signedness; the target is the `BR_CC`/`BRCOND` destination. Use `CMPI` when `b` is a constant.
- For a general `BRCOND` value (not an `ISD::SETCC`), emit `CMPI 0, value` + `JANE`/`JAEQ` as appropriate.
- Keep the `ST` dependency: `CMP`/`CMPI` define `ST`; the branch uses it.
- Let `SETCC`/`SELECT_CC` expand to the generic `BRCOND`/`SELECT`/PHI form; the `SETCC` result is 0/1 (`ZeroOrOneBooleanContent`). The `m3-setcc` sequence should be `MOVI 0`; a conditional `JA<cc>` over the `MOVI 1`; the join label.
- The condition mapping (TMS34010 `cc` from `dis34`): signed `LT/GE/LE/GT` = `JALT/JAGE/JALE/JAGT`; unsigned `LT/GE/LE/GT` = `JALO` (`JAC`)/`JAHS` (`JANC`)/`JALS`/`JAHI`; equality `JAEQ`/`JANE`.
Extend `analyzeBranch`/`insertBranch`/`removeBranch` for `JA<cc>`: a conditional branch has `TBB` = target, `FBB` = fallthrough, `Cond` empty (the compare is fused in the branch instruction); `insertBranch` emits the `JA<cc>`; `removeBranch` removes it. Keep the `MachineBlockPlacement` conservative.
- [ ] **Step 5: Build and run the tests**
```sh
ninja -C build/llvm-clean-build llc opt clang llvm-config FileCheck count not
build/llvm-clean-build/bin/llvm-lit -v \
build/llvm-clean-build/test/CodeGen/TMS34010 --filter='m3-(if|setcc|loop|unsigned|ops)'
```
Expected: 5/5 PASS. Also run the M2 suite (`--filter='m2-'`) and confirm it remains 37/37.
- [ ] **Step 6: Commit**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010
git -C build/llvm-clean commit -m "tms34010: add integer comparisons, branches and ALU ops"
```
### Task 3: Xlib `Display`/`Screen` layout and header
**Files:**
- Create: `scripts/m3/vt1200_xlib.h`, `scripts/m3/layout.c`, `scripts/m3/layout-ti.c`
- Test: `scripts/tests/m3/layout.sh` (or the M3 harness markers; see Task 4)
**Interfaces:**
- Consumes: `xhello.asm`'s proven offsets (display+0x480, screen+0x40).
- Produces: `Display`/`Screen`/`Window`/`XID` types, the four Xlib prototypes, `vt1200_root()`, and static offset assertions.
- [ ] **Step 1: Write the failing offset test**
`scripts/m3/vt1200_xlib.h`:
```c
#ifndef VT1200_XLIB_H
#define VT1200_XLIB_H
typedef unsigned int XID;
typedef unsigned int Window;
/* ROM v2.2 layout (xhello.asm): Display.screens is the pointer at byte 0x90
(bit 0x480); Screen.root is the 32-bit root id at byte 0x8 (bit 0x40). */
typedef struct {
unsigned char pad[0x90]; /* bit 0x480 */
void *screens;
} Display;
typedef struct {
unsigned char pad[0x8]; /* bit 0x40 */
unsigned int root;
} Screen;
extern Display *XOpenDisplay(const char *name);
extern Window XCreateSimpleWindow(Display *display, Window parent,
int x, int y, unsigned width,
unsigned height, unsigned border_width,
unsigned long border,
unsigned long background);
extern int XMapWindow(Display *display, Window window);
extern int XSync(Display *display, int discard);
static unsigned int vt1200_root(Display *d) {
return ((Screen *)((Display *)d)->screens)->root;
}
int layout_screens(void);
int layout_root(void);
#endif
```
`scripts/m3/layout.c`:
```c
#include "vt1200_xlib.h"
_Static_assert(__builtin_offsetof(Display, screens) == 0x90,
"Display.screens must be at byte 0x90 (bit 0x480)");
_Static_assert(__builtin_offsetof(Screen, root) == 0x8,
"Screen.root must be at byte 0x8 (bit 0x40)");
int layout_screens(void) { return (int)__builtin_offsetof(Display, screens) * 8; }
int layout_root(void) { return (int)__builtin_offsetof(Screen, root) * 8; }
```
`scripts/m3/layout-ti.c` (K&R, for the 1987 compiler):
```c
struct display { char pad[0x90]; void *screens; };
struct screen { char pad[0x8]; unsigned int root; };
int layout_screens() { return (int)&((struct display *)0)->screens; }
int layout_root() { return (int)&((struct screen *)0)->root; }
```
- [ ] **Step 2: Run it red/verify the target layout**
```sh
scripts/tms-clang -O0 -o /tmp/opencode/m3-layout.ll scripts/m3/layout.c
build/llvm-clean-build/bin/llc -march=tms34010 -O0 -filetype=asm \
/tmp/opencode/m3-layout.ll -o /tmp/opencode/m3-layout.s
```
Expected initially: the `_Static_assert`s fail if the target's struct layout pads `Display.screens` away from byte 0x90 (bit 0x480) or `Screen.root` away from byte 0x8 (bit 0x40). Fix the header (the padded structs are the intended ROM layout) or the target's struct layout if the padded struct itself is laid out wrongly. Do not use the host X11R7 `_XDisplay` layout.
- [ ] **Step 3: Build the TI golden**
Compile `scripts/m3/layout-ti.c` with the 1987 TI compiler (`gspcpp`/`gspcc`/`gspcg` under DOSBox, the `c-hello/build.sh` pattern). Store the LF-normalized asm as `scripts/m3/layout-ti.s`. The two functions must return `0x480` and `0x40`; check the asm's `MOVI` constants.
- [ ] **Step 4: Add the layout gate**
`scripts/tests/m3/layout.sh`:
- compile `layout.c` with `tms-clang` + `llc`; require exit 0 (the static asserts);
- check `layout.s` and `layout-ti.s` contain the constants `0x480`/`0x40` (allowed spellings: `480h`, `1152`, etc.);
- fail loudly on a mismatch.
Run it; expected PASS.
- [ ] **Step 5: Commit**
```sh
git add scripts/m3/vt1200_xlib.h scripts/m3/layout.c scripts/m3/layout-ti.c \
scripts/m3/layout-ti.s scripts/tests/m3/layout.sh
git commit -m "tests: M3 Xlib Display/Screen layout"
```
### Task 4: Xlib client, ROM imports, branch/Xlib MAME harness, window
**Files:**
- Create: `scripts/m3/xhello.c`, `branch.c`, `entry.asm`, `link.cmd`, `run.sh`, `m3-check.lua`, `dis-roundtrip.sh`, `validate-syms.sh`
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp/.h` (misaligned accesses)
- Test: `build/llvm-clean/llvm/test/CodeGen/TMS34010/m3-unaligned.ll`
- Create: `scripts/tests/m3/run.sh`, `scripts/tests/m3/dis-roundtrip.sh`
- Test: the MAME window and the branch markers
**Interfaces:**
- Consumes: Tasks 1–3's branches, layout, and the M2 `.data`/ABI/loader.
- Produces: `M3 MAME: PASS` with the Xlib markers, branch results, and a white window pixel; `M3 dis34 round-trip: PASS`.
- [ ] **Step 1: Fix the packed-struct unaligned-load gap (compiler)**
`vt1200_root()` loads the `Display.screens` pointer and `Screen.root` from packed structs (`clang` `PackStruct = 1` → every field load is `align 1`). The DAG legalizer currently splits those into four `zext i8` loads, and M2/M3 only has a sign-extending `MOVB`, so `llc` aborts. Add `TMS34010TargetLowering::allowsMisalignedMemoryAccesses` returning true for i16/i32/pointers in address space 0 (the ISA allows misaligned accesses; spec §7.5), so the existing `MOVE`/FS0 forms select directly. Add a focused lit test (`m3-unaligned.ll`: `load i32, ptr %p, align 1` and `store i32 ..., align 1` → `MOVE`/`MOVE ...,1`; a pointer load; an i16 align-1 load). Also add a `vt1200_root` probe to `layout.c` (or a small TU) that calls the helper and require the selected asm to contain the `0480h`/`040h` bit displacements. Do not paper over this with `__attribute__((aligned(2)))`.
- [ ] **Step 2: Write the C client and branch test**
`scripts/m3/xhello.c`:
```c
#include "vt1200_xlib.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
int xhello(void) {
Display *d = XOpenDisplay("0::0");
MARK(0) = (unsigned int)d;
if (!d)
return -1;
unsigned int root = vt1200_root(d);
MARK(1) = root;
Window w = XCreateSimpleWindow(d, root, 100, 100, 400, 200, 2, 0, 1);
MARK(2) = (unsigned int)w;
XMapWindow(d, w);
int s = XSync(d, 0);
MARK(3) = (unsigned int)s;
return (int)w;
}
```
`scripts/m3/branch.c`:
```c
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
int sumto(int n) {
int s = 0;
int i;
for (i = 1; i <= n; i++)
s += i;
return s;
}
int max2(int a, int b) { return a > b ? a : b; }
int lt(int a, int b) { return a < b; }
int branch_test(void) {
MARK(4) = (unsigned int)sumto(10);
MARK(5) = (unsigned int)max2(20, 22);
MARK(6) = (unsigned int)lt(5, 7);
MARK(7) = (unsigned int)layout_screens();
MARK(8) = (unsigned int)layout_root();
return 0;
}
```
The `layout_screens`/`layout_root` functions come from `layout.c` (Task 3); compile it into the M3 image.
- [ ] **Step 3: Write the entry and linker command**
`scripts/m3/entry.asm`:
```asm
.text
.globl _start
_start:
setf 16, 0, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _branch_test
calla _xhello
rets
.bss _cstack, 32768, 16 ; 4096 bytes
```
`scripts/m3/link.cmd` (CRLF; same shape as M2):
```text
-a
-o M3.OUT
-m M3.MAP
-e _start
M3.obj
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 018A9000h, length = 40000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
```
- [ ] **Step 4: Validate the ROM symbols**
`scripts/m3/validate-syms.sh`:
- require the four entries in `symbols/vt1200-v22.syms`;
- require each address in the ROM bit range `3F200000h..3FFFFFFFh` and 16-bit aligned;
- run `dis34 -b <addr> -s <byte-offset>` for each and require a plausible function prologue (first instruction is a `MOVE`/`MMTM`/`SETF`/`CMP`/`ADDI`, not data);
- record the known-good `xhello.asm` evidence in `symbols/README.md`.
This is a regression check, not a re-extraction; the four entries are proven by `xhello.asm`. M4 extends the table for `XImage`/`XEvent`.
- [ ] **Step 5: Write the M3 runner and check**
`scripts/m3/run.sh` adapts `scripts/m2/run.sh` with:
- `M3_WORK=${M3_WORK:-$ROOT/build/m3}`, `M3_COFF`, `M3_SDK`;
- compile `xhello.c`, `branch.c`, `layout.c` with `scripts/tms-clang -O2` + `llc -march=tms34010 -O0 -filetype=asm` (keep `layout.c` compiled with the client; the static asserts must pass);
- generate `rom-imports.asm` from `symbols/vt1200-v22.syms`;
- concatenate `entry.asm`, the three `.s` files, and `rom-imports.asm`; assemble/link with GSPA/GSPLNK under DOSBox; require `No Errors`, `No Warnings`; `_start=018A0000`, `.bss` origin `018A9000`, non-empty `.data`, loader `.text`/`.data` 0 differing;
- run MAME with `VT1200_SKIP_LEVEL1=1`, the loader, `LOADER_AT=2500`, `LOADER_END=3400` (adjust if the X server/window needs more frames), `M3_LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua`, `-autoboot_script $ROOT/scripts/m3/m3-check.lua`.
`scripts/m3/m3-check.lua` reads at frame `ENDF-1`:
| marker | expected |
|---|---|
| `0x018A8000` | nonzero Display pointer |
| `0x018A8020` | nonzero root window id |
| `0x018A8040` | nonzero window id |
| `0x018A8060` | `XSync` result (diagnostic only; do not gate the pass on it) |
| `0x018A8080` | `55` (`sumto(10)`) |
| `0x018A80A0` | `22` (`max2(20,22)`) |
| `0x018A80C0` | `1` (`lt(5,7)`) |
| `0x018A80E0` | `0x480` (`layout_screens`) |
| `0x018A8100` | `0x40` (`layout_root`) |
Then read the VRAM pixel inside the window: the window is at `(100,100)`, 400×200; background pixel 1 (white). On the default VR319 monitor the VRAM base is bit `0x04000000` and the row pitch is 2048 bits; read a 32-bit word containing `(150,150)` and require the bit `1 << (150 & 31)` to be set. Print `M3: ...` and exactly `M3 MAME: PASS` on success. The window must be observed; a markers-only pass is not enough.
- [ ] **Step 6: Write the `dis34` round-trip**
`scripts/m3/dis-roundtrip.sh` adapts the M2 COFF parser and symbol lookup. It must require:
- the `_XOpenDisplay`/`_XCreateSimpleWindow`/`_XMapWindow`/`_XSync` `JAUC` stubs at `3F9C2570`/`3FD41B90`/`3FD64F60`/`3FD9F6B0`;
- a `CALLA _XOpenDisplay` with one argument push; `CALLA _XCreateSimpleWindow` with **nine** `MOVE ...,*A14+,1` pushes in order (the first argument at the top of the program stack); `CALLA _XMapWindow` with two; `CALLA _XSync` with two;
- the `SETF 16,0,0` + `SETF 32,0,1` after each call; `RETS 2` for the nine-argument function;
- the branch code: `CMP`, `JALT`/`JAGT`/`JALE`/`JALO`/`JAHI`, `JAUC`, and the `LBB…` labels (no dot);
- the `.data` bytes `30 3A 3A 30 00` (`"0::0"`);
- the old-STK push-count `(pushes+1)*32` for the branch/Xlib functions; the `rets 1` negative control.
- [ ] **Step 7: Run the M3 gates**
```sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
```
Expected: `M3 MAME: PASS` with `display/root/window/sync`, `sum=55 max=22 lt=1`, `screens=0x480 root=0x40`, and the window pixel white; `M3 dis34 round-trip: PASS`.
- [ ] **Step 8: Commit**
```sh
git add scripts/m3 scripts/tests/m3
git commit -m "tests: M3 branches and first Xlib window in MAME"
```
### Task 5: Encoding/differential checks, docs, and push
**Files:**
- Create: `scripts/tests/m3/diff/ti-branch.c`, `ti-branch.s`, `ti-xhello.c`, `ti-xhello.s`, `check.sh`
- Modify: `README.md` (project), `build/llvm-clean/TMS34010.md` (compiler), `symbols/README.md`
- Push: compiler `m3`, project `m3`
**Interfaces:**
- Consumes: all previous tasks.
- Produces: stored TI goldens for branch/struct/call shape, documented M3, pushed `m3` branches.
- [ ] **Step 1: Produce the TI goldens**
Using the 1987 compiler under DOSBox, compile K&R versions:
`scripts/tests/m3/diff/ti-branch.c`:
```c
int sumto(n) int n; { int s; int i; s = 0; for (i = 1; i <= n; i++) s = s + i; return s; }
int max2(a, b) int a; int b; { if (a > b) return a; return b; }
```
`ti-xhello.c`: the K&R Xlib client with the same `Display`/`Screen` padded structs and the four calls.
Store the LF-normalized asm as `ti-branch.s`/`ti-xhello.s`.
- [ ] **Step 2: Write the differential check**
`scripts/tests/m3/diff/check.sh`:
- generate our `branch.s`/`xhello.s` with `scripts/tms-clang -O2` + `llc -O0`;
- in both the TI golden and our asm require: a loop back-edge (`JALE`/`JLE` and `JAUC`/`JRU`), `max2`'s conditional branch, the `sumto` `RETS 2`/`max2` `RETS 2`, the nine `XCreateSimpleWindow` argument pushes, and the `Display`/`Screen` offsets `0x480`/`0x40`;
- accept TI spelling variants (`0FFE0h`, `ADDK`, `JRU`/`JAUC`); do not require byte-for-byte equality. No DOSBox in CI.
- [ ] **Step 3: Update the docs**
- Project `README.md`: M3 status; branch/loop support and its limits (i32/pointer, signed/unsigned compares, `and/or/xor/shift/sub`); the Xlib four-call window; the `Display`/`Screen` offsets; the commands for `scripts/tests/m3/run.sh`, `dis-roundtrip.sh`, `diff/check.sh`; M3 non-goals (XImage/XEvent/real client/structs by value/function pointers/floats/i64/object writer); the `m3` branch and M2 default; the M2/M1 snapshots.
- Compiler `TMS34010.md`: `JAcc` branches, the `ST` flag register, the condition mapping, GSPA-safe `LBB` labels, the `CMP` order, the `SETCC`/`SELECT_CC` approach, the new ALU/shift instructions, and the Xlib client evidence.
- `symbols/README.md`: the four Xlib entries are validated by `xhello.asm` and `validate-syms.sh`; M4 extends the table.
- [ ] **Step 4: Run every M3 gate**
```sh
ninja -C build/llvm-clean-build llc opt clang llvm-config FileCheck count not
build/llvm-clean-build/bin/llvm-lit -v \
build/llvm-clean-build/test/CodeGen/TMS34010 --filter='(m2|m3)-'
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
scripts/tests/m3/diff/check.sh
tools/tms-bitaddr/tests/run.sh
```
Expected: all green; the M2 suite remains 37/37; M3 adds 5 branch tests plus the layout/harness gates.
- [ ] **Step 5: Commit and push**
```sh
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "docs: M3 branches and Xlib window"
git -C build/llvm-clean push origin m3
git add README.md symbols scripts/tests/m3 scripts/m3
git commit -m "docs: M3 control flow and first Xlib window"
git push origin m3
```
Do not force-push, merge into `m0`, or change the default branch; the controller changes the remote default after the final M3 review if the user asks.
---
## Execution Handoff
M3 is the first two halves of the remaining Xlib path: integer control flow (needed by real C) and the four-call window. M4 owns the real client, `XImage`/`XEvent`, the full X11R4 headers, structs by value and function pointers. M5 owns the native COFF path, floats, varargs, bitfields, `long long` and the `JR`/branch-relaxation code-size pass. The compiler repo is canonical for target code; this project repo holds the plans, wrappers, symbols and integration tests.
@@ -0,0 +1,548 @@
# TMS34010 M4 — Xlib Images, Events, and the termtris Integration 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:** A compiled C program displays a 1-bit `XImage` through the ROM Xlib, handles real X events and keyboard input, and exits cleanly; the project also builds the WIP `termtris` VT1200 client with this compiler and runs its move/panels/quit acceptance in MAME.
**Architecture:** M4 keeps the M3 asm-only path and TI ABI. It fills the scalar gaps real clients need (zero-extending narrow loads, module-unique private labels, unsigned/`<=` runtime coverage, 32-bit multiply/divide through `rts.lib`), adds function pointers/indirect `CALL`, adds the X11R4-compatible `XImage`/`XEvent`/`XErrorEvent` layouts, corrects the ROM symbol table, and implements the mandatory per-process XG block so a loader child can receive events. Two small clients prove the image and event paths; the pinned `termtris` branch is a third, full-game integration test.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m4`), C++17, CMake/Ninja, `llc`, GSPA/GSPLNK 2.00 under DOSBox, COFF loader, MAME, `dis34`, `llvm-lit`/FileCheck, 1987 TI compiler, the pinned `termtris` branch.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (§4.2, §7.3.1, §7.4–§7.7, §7.9, M4, M5)
## Global Constraints
- Compiler work happens in **`llvm-tms34010`**, branch `m4`, created from `m3` at `73c85350a401`. Use `build/llvm-clean` and `build/llvm-clean-build`; do not clone another LLVM tree.
- Project plans/tests live in **`tms-c-compiler`**, branch `m4`, created from `m3` at `24f8773` plus the M4 plan commit. `m3` stays the default snapshot until M4 is reviewed; do not merge M2/M3 into `m0`.
- The M3 TI ABI, `.data`, branch/loop, FS0/FS1 and old-STK rules are unchanged. M4 adds: function pointers/indirect calls, zero-extending narrow loads, module-unique private labels, 32-bit multiply/divide, XImage/XEvent/error-handler layouts, the XG block, and the wider Xlib.
- Output remains **assembly only**: `llc -march=tms34010 -filetype=asm`; GSPA/GSPLNK 2.00 under DOSBox; the existing COFF loader. No LLVM object writer/MCCodeEmitter (M5).
- **ROM v2.2 only.** Use the termtris `xlib.h` table and the ROM disassembly. Correct the table: **`XMapWindow = 0x3FD64F60`** (request opcode 8); **`0x3FD645B0` is `XRaiseWindow`** (ConfigureWindow, opcode 12, value-mask `0x40`/`CWStackMode`, value 0/`Above`), not a mapping entry. The M3 table/`xhello` used `0x3FD645B0` under the `XMapWindow` name; its MAME gate still saw a solid-white client area, so re-run that gate with `0x3FD64F60` and record whether the old pass depended on server-side create/configure behavior. The M3 harness/docs/dis34 expectations are updated.
- **Per-process XG block is mandatory before `XOpenDisplay` in a loader child.** The termtris fix: `proc = *(u32*)0x001B3900; pp = *(u32*)(proc+0x100); *(u32*)pp = (u32)zeroed_1KiB;`. Without it `_XEnq` sees `XG == NULL` and `XNextEvent` delivers garbage/nothing. The ROM is untouched.
- Known text/event/GC entries (termtris `xlib.h`): `XOpenDisplay 0x3F9C2570`, `XCreateSimpleWindow 0x3FD41B90`, `XSelectInput 0x3FD97D50`, `XSync 0x3FD9F6B0`, `XFlush 0x3F9B1030`, `XNextEvent 0x3F9C1CF0`, `XLookupString 0x3F9A9C30`, `XCreateGC 0x3F997000`, `XSetForeground 0x3FD99A60`, `XFillRectangle 0x3F99E8F0`, `XDrawString 0x3FDA0000`, `XPending 0x3FD67620`, `XGetInputFocus 0x3FD55210`, `XLoadFont 0x3FD4AE80`, `XCopyArea 0x3FD3E220`, `sleep 0x3FB33A20`. The `XImage` entries (`XCreateImage`, `XPutImage`, `XDestroyImage`, optional `XGetImage`) and `XSetErrorHandler`/`XSetIOErrorHandler` must be extracted/validated before use; do not guess.
- `XMapWindow` is the mapping API for new clients; the M4 image/event clients use the true entry. The termtris client uses `XMapWindow 0x3FD64F60`.
- The **termtris additional integration** is pinned at branch `termtris`, commit `be5b323f5d2cc4f7a7d25e7143c67bd9828ccbdf`. Its `apps/termtris` tree is GPLv3; vendor/read it with `COPYING` intact and test only. Build it with **this compiler**, not its TI r5.01/2ine path. Its acceptance is the proven `play_keys` run: `move`/`panels`/`quit`, `loops >= 100`, `events >= 6`, `focus` = the window, `quit = 1` for `q`, and the captured frames.
- The **primary M4 acceptance** is the image/event client: a 1-bit `XImage` (LSBFirst) appears in MAME, no X errors are reported by the handler, and a real key press is delivered and processed. The termtris run is the additional, full-game integration test.
- `XImage` data is `unsigned char`; zero-extending `unsigned char`/`unsigned short` loads must work. The program stack is A14 (grows up); the system stack A15; `RETS 2/0` and FS0/FS1 apply to indirect calls too.
- X11 headers: use an X11R4-compatible subset (system Xlib/Xutil or a vendored minimal header). `Display.screens` remains byte `0x90` (bit `0x480`); `Screen.root` byte `0x8` (bit `0x40`). Verify the `XImage`/`XEvent`/`XErrorEvent` field offsets with `_Static_assert`s and a TI/host golden before relying on them.
- The M2/M3 tests must stay green. Add `m4-*` lit tests and `scripts/tests/m4/*` gates.
- No XImage/XEvent/the full Xlib beyond the listed calls; no floats/i64/varargs/bitfields/structs by value/native COFF in M4. The termtris compile may expose a gap; fix it or rule it out explicitly in the report.
## Review Focus
1. **Function pointer/indirect call ABI:** `CALL Rs`; the call-site old-STK save iff args; argument order; A8 return; FS0/FS1; the callee `RETS`. A wrong `CALL` target or stack leaves the caller corrupted. Tests in Task 3 (`m4-fnptr`, a C callback) and Task 7 (termtris callbacks).
2. **XImage/XEvent/GC/XErrorEvent layout and semantics:** `XImage.byte_order`/`bitmap_bit_order` LSBFirst, `data`, `bytes_per_line`; `XEvent.type`/`xkey` fields; `XErrorEvent` fields. A wrong field or offset yields a black/garbled image or no key. Tests in Task 4 (static offsets) and Task 6 (image pixel/no-X-errors/key).
3. **The XG block/event loop:** without `vt_install_xg()` before `XOpenDisplay` the loader child receives no events; the termtris tree documents the exact failure. Tests in Task 5 (XG gate) and Tasks 6/7 (keys/focus/quit).
4. **`XMapWindow` vs `XRaiseWindow`:** the M3 table's `XMapWindow` (`0x3FD645B0`) is actually `XRaiseWindow` (ConfigureWindow opcode 12); the real `XMapWindow` is `0x3FD64F60` (opcode 8). Use it for new clients and correct the M3 harness/docs. Tests in Task 5 and the M3 re-run.
5. **Narrow loads/unsigned/multiply/loop prerequisites:** `unsigned char` XImage data, `unsigned short`, `<=`/unsigned branches, and the `-O2` closed-form loop/multiply. A missing feature aborts a real client. Tests in Tasks 1/2 and the termtris run.
6. **The termtris integration:** the pinned branch, the function-pointer callbacks, the event loop, the keys/panels/quit, the screenshots, the `loops/events/focus/quit` markers. Test in Task 7.
7. **X11R4 layout vs the ROM:** the byte/bit `Display`/`Screen` and the `XImage`/`XEvent` fields; a header mismatch produces plausible but wrong data. Tests in Task 4 (static asserts) and Task 6.
---
### Task 1: M4 branches, zero-extending narrow loads, private labels, and unsigned runtime
**Files:**
- Modify: `build/llvm-clean/llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp`, `TMS34010InstrInfo.td`
- Modify: `TMS34010TargetMachine.cpp` / `TMS34010AsmPrinter.cpp` (private symbol naming)
- Test: `build/llvm-clean/llvm/test/CodeGen/TMS34010/m4-zext.ll`, `m4-private.ll` (or a two-TU shell test)
- Create: `scripts/m4/unsigned.c`, `scripts/m4/private-a.c`, `private-b.c`, `scripts/tests/m4/{unsigned,private}.sh`
**Interfaces:**
- Consumes: M3 target and tests.
- Produces: `ZEXTLOAD i8/i16` selection; module-unique private symbols; runtime `JALS`/`JAHS`/`JANE`/`JAGE`/`JALE`/`JALO`/`JAHI` coverage.
- [ ] **Step 1: Write the failing tests**
`m4-zext.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @zext8(ptr %p) {
%v = load i8, ptr %p, align 1
%r = zext i8 %v to i32
ret i32 %r
}
define i32 @zext16(ptr %p) {
%v = load i16, ptr %p, align 1
%r = zext i16 %v to i32
ret i32 %r
}
; CHECK-LABEL: _zext8:
; CHECK: MOVB *A{{[0-9]+}}, A{{[0-9]+}}
; CHECK: ANDI 255
; CHECK-LABEL: _zext16:
; CHECK: MOVE *A{{[0-9]+}}, A{{[0-9]+}}, 0
; CHECK: ANDI 65535
```
The `ANDI` forms are the 1's-complement immediates; the masks must be exact. `m4-private` compiles two TUs with the same private string literal and requires the GSPA link to succeed (no duplicate private label).
`scripts/m4/unsigned.c`:
```c
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n)*0x20u))
int le(int a, int b) { return a <= b; }
unsigned ule(unsigned a, unsigned b) { return a <= b; }
int sum_le(int n) { int s = 0, i; for (i = 0; i <= n; i++) s += i; return s; }
int unsigned_test(void) {
MARK(0) = (unsigned)le(5, 7);
MARK(1) = (unsigned)ule(7u, 5u);
MARK(2) = (unsigned)sum_le(10);
return 0;
}
```
`scripts/m4/private-a.c` and `private-b.c` each define a string literal and a function returning it, e.g. `char *a(void) { return "same"; }`; the linker must resolve both without a duplicate label.
- [ ] **Step 2: Run them red**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean-build/test/CodeGen/TMS34010 --filter='m4-(zext|private)'
```
Expected: FAIL — `Cannot select: ... zext from i8/i16`, and the two-TU private link collides.
- [ ] **Step 3: Implement the zext loads and private naming**
- Set `ZEXTLOAD i8/i16` legal and add patterns: `MOVB` (which sign-extends) + `ANDI 255`, and FS0 `MOVE16` + `ANDI 65535`; reuse `ANDI` (the M4 `.td` fix already complements the immediate). Add the `ANDI` immediate 1's complement if needed.
- Make private/string-literal symbols module-unique so two TUs with the same `.str`/private name do not collide in GSPA's flat symbol table. Keep public names unchanged; the sanitizer remains GSPA-valid. The two-TU test must assemble and link with `No Errors, No Warnings`.
- [ ] **Step 4: Run the MAME unsigned test**
Build `unsigned.c` with `tms-clang -O2` + `llc -O0`, link with the M3 `scripts/m4` harness/entry (a minimal entry calling `_unsigned_test`), and check `le(5,7)=1`, `ule(7,5)=0`, `sum_le(10)=55`. The assembly must contain `JALE`/`JALS` (or the correct unsigned `<=` form) and `JAHS`/`JAHI`.
- [ ] **Step 5: Run the suite and commit**
```sh
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean-build/test/CodeGen/TMS34010 --filter='(m2|m3|m4)-'
```
Expected: all green (the M3 suite plus the new tests). Commit the compiler changes and the project harness/tests; the report.
### Task 2: 32-bit multiply/divide and the `-O2` loop pipeline
**Files:**
- Modify: `TMS34010InstrInfo.td`, `TMS34010ISelLowering.cpp/.h`, `TMS34010TargetMachine.cpp` (TTI/pass policy)
- Create: `scripts/m4/mul.c`, `scripts/m4/loop.c`, `scripts/tests/m4/mul.sh`
- Link: the 1987 `RTS.LIB` (the `_mul`/`_div`/`_mod` entries) or a target sequence
**Interfaces:**
- Consumes: Task 1 and M3's `JAcc`/`ST`.
- Produces: `MPYS`/`MPYU` 16×16; 32×32 multiply/divide via `rts.lib` libcalls or a sequence; an `-O2` loop policy that does not produce an unsupported i33 multiply.
- [ ] **Step 1: Write the failing tests**
`m4-mul.ll` (or C through `tms-clang`):
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @mul(i32 %a, i32 %b) {
%r = mul i32 %a, %b
ret i32 %r
}
; CHECK: MPYS
; CHECK: MPYU
```
`scripts/m4/loop.c`:
```c
int sumto(int n) { int s = 0, i; for (i = 1; i <= n; i++) s += i; return s; }
int squares(int n) { int s = 0, i; for (i = 0; i < n; i++) s += i * i; return s; }
```
Compile with the **default** `tms-clang -O2` (no `-replexitval=never`) and require success + correct MAME results (`sumto(10)=55`, `squares(5)=30`).
- [ ] **Step 2: Run it red**
```sh
scripts/tms-clang -O2 -o /tmp/opencode/m4-mul.ll scripts/m4/mul.c
build/llvm-clean-build/bin/llc -march=tms34010 -O0 -filetype=asm ...
```
Expected: `Cannot select: mul` / `umul_lohi` / the i33 multiply / missing `_mul`.
- [ ] **Step 3: Implement the arithmetic and loop policy**
- Add `MPYS`/`MPYU` 16×16 and the 32×32 multiply/divide/remainder libcalls. Prefer linking the 1987 `RTS.LIB` `_mul`/`_div`/`_mod` entries (reuse the TI runtime; no new libc); wire the `TargetLowering` libcall names and the M4 `link.cmd` (`-l RTS.LIB`). If the runtime entry names differ, extract them from the SDK `RTS.LIB`/map and record them.
- Address the `IndVarSimplify` exit-value i33 multiply: add a target `TargetTransformInfo`/pass policy that makes the closed-form replacement unprofitable for this target, or lower the i33/i64 multiply through the runtime. The M3 `m3` harness may keep `-replexitval=never`, but M4's ordinary `-O2` loop must compile.
- Keep the M3 `shouldFoldConstantShiftPairToMask` behavior; the multiply/divide tests.
- [ ] **Step 4: Run the MAME multiply/loop tests**
`mul(6,7)=42`, `sumto(10)=55`, `squares(5)=30`; the `-O2` pipeline without the exit-value wrapper. Record the `RTS.LIB` link line and the symbols.
- [ ] **Step 5: Run the suite and commit**
Commit the compiler arithmetic/policy and the M4 tests; the report.
### Task 3: Function pointers and indirect calls
**Files:**
- Modify: `TMS34010InstrInfo.td` (`CALL Rs`), `TMS34010ISelLowering.cpp/.h` (`LowerCall` indirect), `TMS34010MCInstLower.cpp` if needed
- Test: `m4-fnptr.ll`, `scripts/m4/fnptr.c`, `scripts/tests/m4/fnptr.sh`
**Interfaces:**
- Consumes: M3 `LowerCall`/`CALLA`/frames; Task 1/2.
- Produces: `CALL Rs` (1-word indirect call; GSPA `CALL $rs`), function addresses as bit addresses, function-pointer parameters/returns, callback ABI.
- [ ] **Step 1: Write the failing test**
`m4-fnptr.ll`:
```llvm
; RUN: llc -march=tms34010 -O2 -filetype=asm < %s | FileCheck %s
define i32 @inc(i32 %x) {
%r = add i32 %x, 1
ret i32 %r
}
define i32 @apply(ptr %f, i32 %x) {
%r = call i32 %f(i32 %x)
ret i32 %r
}
; CHECK-LABEL: _apply:
; CHECK: CALL A{{[0-9]+}}
; CHECK: RETS 2
```
`scripts/m4/fnptr.c`:
```c
typedef int (*fn)(int);
int inc(int x) { return x + 1; }
int apply(fn f, int x) { return f(x); }
int fnptr_test(void) { return apply(inc, 41); } /* 42 */
```
- [ ] **Step 2: Run it red**
Expected: `M2/M3 supports only direct calls` fatal for the indirect call.
- [ ] **Step 3: Implement indirect calls**
- Define `CALL` (`CALL $rs`, 1 word, `isCall`, `Uses=[A14]`, `Defs=[A8,A14]`, 2 bytes) and the asm printer.
- Extend `LowerCall`: accept a `RegisterSDNode`/`CopyFromReg` callee; emit the same old-STK/argument/`CALL Rs`/FS0-FS1/`A8` sequence as `CALLA`; reject only unsupported callee shapes. A function pointer is a 32-bit bit address; `MOVI _inc, A?` or `MOVI 0xADDR, A?` materializes it.
- Keep the direct `CALLA` path and the `getCallPreservedMask`.
- Test a function pointer from a global symbol and from an absolute address (`((fn)0x3F...)`), the latter used by the Xlib header.
- [ ] **Step 4: Run the MAME callback test**
`fnptr_test()=42`; the termtris function-pointer callbacks (`term_reset` etc.) are the integration case. Record the `CALL` encoding/`dis34`.
- [ ] **Step 5: Commit**
Commit the compiler/test changes; the report.
### Task 4: X11R4-compatible headers and XImage/XEvent/error-event layouts
**Files:**
- Create: `scripts/m4/x11m4.h` (or vendor an X11R4 subset), `scripts/m4/layout.c`, `scripts/m4/layout-ti.c`
- Create: `scripts/tests/m4/layout.sh`
- Reuse: the Task 3 `vt1200_xlib.h` byte/bit layout
**Interfaces:**
- Consumes: the M3 `Display`/`Screen` layout (byte 0x90/0x8).
- Produces: `XImage`, `XEvent`/`XKeyEvent`/`XExposeEvent`/`XFocusChangeEvent`/`XButtonEvent`, `XErrorEvent`, `GC`/`Visual`, the function prototypes/constants, and verified field offsets.
- [ ] **Step 1: Write the failing layout test**
`scripts/m4/x11m4.h` contains at least:
```c
typedef struct _XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask, green_mask, blue_mask;
void *obdata;
struct funcs *f;
} XImage;
typedef union _XEvent {
int type;
struct { int type; unsigned long serial; int send_event; void *display;
unsigned long window, root, subwindow; unsigned long time;
int x, y, x_root, y_root; unsigned state; unsigned keycode;
int same_screen; } xkey;
struct { int type; unsigned long serial; int send_event; void *display;
unsigned long window; int x, y, width, height, count; } xexpose;
/* xfocus/xbutton/... as needed */
} XEvent;
typedef struct _XErrorEvent {
int type;
void *display;
unsigned long resourceid, serial;
unsigned char error_code, request_code, minor_code;
} XErrorEvent;
```
`scripts/m4/layout.c`:
```c
#include "x11m4.h"
_Static_assert(__builtin_offsetof(Display, screens) == 0x90, "...");
_Static_assert(__builtin_offsetof(Screen, root) == 0x8, "...");
_Static_assert(__builtin_offsetof(XImage, data) == 20, "...");
_Static_assert(__builtin_offsetof(XImage, byte_order) == 24, "...");
_Static_assert(__builtin_offsetof(XImage, bytes_per_line) == 40, "...");
_Static_assert(__builtin_offsetof(XEvent, type) == 0, "...");
_Static_assert(sizeof(XEvent) >= 96, "...");
```
Use the actual 32-bit X11R4/system header field offsets; if the system header's `XImage`/`XEvent` match the ROM, assert them; otherwise document the ROM-verified subset. The `XImage` size must cover what `XCreateImage` returns; the `XEvent` buffer is the termtris `vt_u32 evbuf[24]` (96 bytes).
- [ ] **Step 2: Run it red/verify**
Compile with `scripts/tms-clang -O0` + `llc`; the static asserts must pass. If a field offset differs, fix the header (or the target if the packed struct is wrong) and report it. Do not use the host 64-bit layout without the 32-bit type mapping.
- [ ] **Step 3: Build the TI/host golden**
Compile `layout-ti.c` (the `Display`/`Screen`/`XImage`/`XEvent` offset functions) with the 1987 compiler; store the asm; require the same constants. The 1987 compiler's `&` is bit-addressed; convert to byte offsets consistently.
- [ ] **Step 4: Run the layout gate and commit**
`scripts/tests/m4/layout.sh` compiles the static asserts, checks the target and TI golden constants, and fails loudly. Commit the header/layout test.
### Task 5: ROM symbols, `XMapWindow` correction, and the XG block
**Files:**
- Modify: `symbols/vt1200-v22.syms`, `symbols/README.md`
- Modify: `scripts/m3/xhello.c`/`scripts/m3/dis-roundtrip.sh`/M3 docs (the `XMapWindow`/`XRaiseWindow` correction)
- Create: `scripts/m4/xgfix.c`, `scripts/m4/validate-syms.sh`, `scripts/tests/m4/symbols.sh`
**Interfaces:**
- Consumes: the termtris `xlib.h` table and the M3 loader.
- Produces: the corrected/extended v2.2 symbol table; `vt_install_xg()`; a symbol-validation gate.
- [ ] **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`, `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.
- [ ] **Step 2: Implement the XG fix**
`scripts/m4/xgfix.c` (the termtris fix):
```c
int vt_install_xg(void) {
unsigned int proc = *(volatile unsigned int *)0x001B3900u;
if (proc < 0x100u || proc > 0x01FFFFFFu) return 0;
unsigned int pp = *(volatile unsigned int *)(proc + 0x100u);
if (pp < 0x100u || pp > 0x01FFFFFFu) return 0;
static unsigned int xg[256]; /* 1 KiB zeroed .bss */
*(volatile unsigned int *)pp = (unsigned int)xg;
return 1;
}
```
Call it **before** `XOpenDisplay` in the event/image clients and the termtris build.
- [ ] **Step 3: Validate the symbols**
`scripts/m4/validate-syms.sh` checks the v2.2 entries are in ROM range, 16-bit aligned, and start with a plausible function prologue (`dis34`); the termtris `xlib.h` is the evidence. Add a test that `0x3FD645B0` is reported as `XRaiseWindow` (ConfigureWindow opcode 12), so the correction is pinned.
- [ ] **Step 4: Run the M3 correction and the symbol gate**
Re-run `scripts/tests/m3/run.sh`/`dis-roundtrip.sh`; the M3 window still appears with the true `XMapWindow 0x3FD64F60`. Run `scripts/tests/m4/symbols.sh`; all entries validated. Commit.
### Task 6: The M4 image/event client and the MAME image/key gate
**Files:**
- Create: `scripts/m4/xshow.c`, `scripts/m4/entry.asm`, `scripts/m4/link.cmd`, `scripts/m4/run.sh`, `scripts/m4/m4-check.lua`, `scripts/m4/dis-roundtrip.sh`
- Create: `scripts/tests/m4/run.sh`, `scripts/tests/m4/dis-roundtrip.sh`
- Reuse: `scripts/m4/x11m4.h`, `xgfix.c`, `validate-syms.sh`
**Interfaces:**
- Consumes: Tasks 1–5.
- Produces: `M4 MAME: PASS` — a 1-bit `XImage` displayed, no X errors, a real key press processed, focus/window markers, and the window/image pixel evidence.
- [ ] **Step 1: Write the image/event client**
`scripts/m4/xshow.c` (the `xshow` shape, VT1200 Xlib):
```c
#include "x11m4.h"
static volatile unsigned int *MARK(unsigned n) { return (volatile unsigned int *)(0x018A8000u + n*0x20u); }
static int xerrors;
static int on_error(void *d, XErrorEvent *e) { xerrors++; return 0; }
int xshow(void) {
if (!vt_install_xg()) return -1;
Display *d = XOpenDisplay("0::0");
MARK(0)[0] = (unsigned)d; if (!d) return -1;
Window w = XCreateSimpleWindow(d, vt_root(d), 20, 20, 640, 480, 0, 0, 0);
MARK(1)[0] = (unsigned)w;
XSelectInput(d, w, ExposureMask | KeyPressMask | ButtonPressMask | StructureNotifyMask);
GC gc = XCreateGC(d, w, 0, 0);
XSetForeground(d, gc, 1);
/* 1-bit checker image, LSBFirst */
int bpl = ((640 + 31) / 32) * 4;
static unsigned char data[480 * 80]; /* 640/8 = 80 bytes/row */
for (int y = 0; y < 480; y++) for (int x = 0; x < 640; x++)
if (((x/32) ^ (y/32)) & 1) data[y*80 + (x>>3)] |= 1u << (x & 7);
XImage *img = XCreateImage(d, 0, 1, XYBitmap, 0, (char *)data, 640, 480, 32, bpl);
MARK(2)[0] = (unsigned)img; if (!img) return -1;
img->byte_order = LSBFirst; img->bitmap_bit_order = LSBFirst;
XSetErrorHandler(on_error);
XMapWindow(d, w);
XPutImage(d, w, gc, img, 0, 0, 0, 0, 640, 480);
XSync(d, 0);
for (;;) {
XEvent ev;
while (XPending(d)) {
XNextEvent(d, &ev);
MARK(4)[0]++;
if (ev.type == KeyPress) {
char buf[8]; unsigned long ks = 0;
int n = XLookupString(&ev.xkey, buf, 8, &ks, 0);
MARK(5)[0] = (unsigned)ev.xkey.keycode;
MARK(6)[0] = (unsigned)ks;
if (buf[0] == 'q') { MARK(3)[0] = 1; return 0; }
} else if (ev.type == Expose) {
XPutImage(d, w, gc, img, 0, 0, 0, 0, 640, 480);
}
}
MARK(7)[0] = (unsigned)xerrors;
XFlush(d);
sleep(5); /* the ROM sleep; keep the process alive */
}
}
```
Use the exact Task 4 field names/offsets; `XCreateImage`'s `visual` may be 0 for a 1-bit default; if the ROM requires the default visual, use `DefaultVisual` or the display's default; verify. The window is at (20,20), 640×480; the image checker is LSB-first; the key `q` quits. The `XSetErrorHandler` is a function pointer (Task 3); the `on_error` increments.
- [ ] **Step 2: Entry/link/runner**
`scripts/m4/entry.asm` sets FS0/FS1, STK/FP, calls `_xshow`, `rets`; `_cstack` `.bss` 32768 bits. `link.cmd` places `.text`/`.data` > prog at `018A0000h`, `.bss` > ram at `018A9000h`; link `RTS.LIB` if the compiler/libcall path needs it. `scripts/m4/run.sh` compiles `xshow.c`/`layout.c`/`xgfix.c` with `tms-clang -O2` + `llc -O0`, generates the ROM stubs/function-pointer addresses, GSPA/GSPLNK under DOSBox, loads in MAME with `VT1200_SKIP_LEVEL1=1`, the loader, `LOADER_AT=2500`, `LOADER_END=3400` (adjust), the `VT1200_MONITOR=VR319` pin, and `m4-check.lua`.
`scripts/m4/m4-check.lua` reads the markers: display/window/image nonzero, `xerrors==0`, `events>0`, the keycode/keysym for a `q` injected key, the quit marker, and the image checker at several window pixels (e.g. (30,30) and (50,50) alternate; the checker pattern at 32-pixel cells). Use the VRAM base bit `0x04000000`, VR319 2048-bit pitch, LSB-first; the window is at (20,20). Require `M4 MAME: PASS`; markers alone are not enough.
- [ ] **Step 3: Write the `dis34` round-trip**
`scripts/m4/dis-roundtrip.sh` checks the linked bytes for `CALL`/`CALLA` (the indirect call), the `XOpenDisplay`/`XCreateSimpleWindow`/`XSelectInput`/`XCreateGC`/`XSetForeground`/`XCreateImage`/`XSetErrorHandler`/`XMapWindow`/`XPutImage`/`XSync`/`XNextEvent`/`XLookupString` calls, the 9-argument `XCreateSimpleWindow` order, the `XSetErrorHandler` callback pointer, the `SETF`/`RETS`/old-STK rules, and the checker data in `.data`/`.bss`. The image client's `CALL` encoding is the Task 3 contract.
- [ ] **Step 4: Run the gates**
```sh
scripts/tests/m4/run.sh
scripts/tests/m4/dis-roundtrip.sh
```
Expected: `M4 MAME: PASS` with the image checker, `xerrors=0`, a real key event, and the window; `M4 dis34 round-trip: PASS`.
- [ ] **Step 5: Commit**
Commit the client/harness/tests; the report.
### Task 7: The pinned `termtris` additional integration test
**Files:**
- Fetch: `https://git.wut.ee/opencode.energia.arti.ee/vt1200.git`, branch `termtris`, commit `be5b323f5d2cc4f7a7d25e7143c67bd9828ccbdf`, into `vendor/vt1200-termtris` (test-only, GPLv3 `COPYING` intact)
- Create: `scripts/m4/termtris/build.sh`, `scripts/m4/termtris/play_keys.lua` (adapted from the vendored `apps/termtris/tests/play_keys.lua`), `scripts/m4/termtris/play_keys.sh`
- Create: `scripts/tests/m4/termtris.sh`
**Interfaces:**
- Consumes: Tasks 1–6; the termtris `apps/termtris/src/vt1200/{xlib.h,xgfix.c,main.c,x11.c,compat.c}`, `src/game.c`, `src/pieces.h`, `src/game.h`, `src/term.h`, `src/vt1200/scoredb.c`, `src/vt1200/stdio.h`, `src/vt1200/inttypes.h`.
- Produces: the termtris board, panels, move, and quit in MAME, with the proven `play_keys` marker acceptance.
- [ ] **Step 1: Fetch and pin**
```sh
git clone --depth 1 --branch termtris \
https://git.wut.ee/opencode.energia.arti.ee/vt1200.git \
vendor/vt1200-termtris
git -C vendor/vt1200-termtris rev-parse HEAD # be5b323...
```
Keep `vendor/` ignored; the project test references the pinned checkout. The termtris `VT1200.md`/spec/plan and `apps/termtris/tests/play_keys.{sh,lua}` are the reference.
- [ ] **Step 2: Build termtris with this compiler**
`scripts/m4/termtris/build.sh` compiles the termtris sources with `tms-clang -O2 -I vendor/vt1200-termtris/apps/termtris/src -I .../src/vt1200` + `llc -O0`, concatenates the M4 entry (`_start` calls `_main`; `.data` is copied by the loader; `_cstack`) with the termtris `.s` and the function-pointer Xlib header, links with GSPA/GSPLNK (RTS.LIB for multiply/divide), and emits `build/termtris.coff`/`.map`.
- [ ] **Step 3: Run the play_keys acceptance**
Adapt the termtris `play_keys.lua`/`play_keys.sh`: the `move`/`panels`/`quit` modes, the tablet click + `A/D/S/W/0/P/R/H/Q` injection, the `DIAG_LOOPS/EVENTS/FOCUS/REV/QUIT/TICK` addresses from the M4 `.map`, `LOADER_AT=2500`, `LOADER_END=3200`, `LOADER_SNAP=1`, `VT1200_SKIP_LEVEL1=1`, the loader, and the M4 COFF. Require:
- `loops >= 100` and `events >= 6` for `move`/`panels`;
- `quit = 0` for `move`/`panels`, `quit = 1` for `quit`;
- `focus` = the termtris window (nonzero);
- the board/panels/move/quit screenshots.
The termtris's proven values were `move loops=333 events=18`, `panels loops=323 events=12`, `quit loops=277 events=10 quit=1`; the M4 run may differ in counts, but the thresholds and quit/focus must hold.
- [ ] **Step 4: Record and commit**
The termtris build proves: function pointers (`term_*` callbacks/absolute Xlib pointers), indirect calls, `XSelectInput`/`XNextEvent`/`XLookupString`, the XG block, `XCreateGC`/`XSetForeground`/`XFillRectangle`/`XDrawString`, the timer/sleep, multiply/divide, `sprintf`/compat, and the loader/child. If a termtris feature is genuinely outside M4, report it with a ruling and a specific follow-up; do not weaken the thresholds or fake the run.
Commit the M4 termtris scripts/tests and a short report; keep the vendored tree ignored.
### Task 8: Differential/dis34, docs, and push
**Files:**
- Create: `scripts/tests/m4/diff/{ti-fnptr.c,ti-fnptr.s,ti-image.c,ti-image.s,check.sh}`
- Modify: `README.md` (project), `build/llvm-clean/TMS34010.md` (compiler), `symbols/README.md`
- Push: compiler `m4`, project `m4`
**Interfaces:**
- Consumes: all previous tasks.
- Produces: stored TI goldens for function-pointer/call/image/struct-offset shape, M4 docs, and pushed `m4` branches.
- [ ] **Step 1: Produce the TI goldens**
Compile K&R/ANSI C for a function-pointer apply/callback and the Xlib image-call shape with the 1987 compiler; store `ti-fnptr.s`/`ti-image.s`; no DOSBox in CI. The check compares ABI shape: `CALL Rs`/indirect call, the old-STK push, the argument/return/`RETS 2`, the `XCreateImage`/`XPutImage` 10/9 argument pushes, the `Display`/`Screen`/`XImage` offsets (byte 0x90/0x8; the XImage fields).
- [ ] **Step 2: Write the diff check**
`scripts/tests/m4/diff/check.sh` generates our asm with `tms-clang` + `llc` and greps the stored goldens; accept TI spelling variants; fail loudly. Add negative controls for the `CALL`/the image argument order.
- [ ] **Step 3: Update the docs**
README M4: function pointers/indirect calls; zext narrow loads; multiply/divide/`rts.lib`; the image/event clients; the XG fix; the corrected `XMapWindow`/`XRaiseWindow`; the `XImage`/`XEvent` layouts; the termtris additional integration and its pinned branch; commands; M4 non-goals (XImage/XEvent beyond the tested calls, native COFF, floats/i64/varargs/structs by value; the M4/M5 boundary). TMS34010.md: the `CALL Rs` ABI, function pointers, zext patterns, multiply/divide libcalls, the TTI/loop policy, the XImage/XEvent lowering, the XG/ROM notes. symbols README: the corrected/extended v2.2 entries and the evidence.
- [ ] **Step 4: Run every M4 gate**
```sh
ninja -C build/llvm-clean-build llc opt clang llvm-config FileCheck count not
build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean-build/test/CodeGen/TMS34010 --filter='(m2|m3|m4)-'
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/m4/diff/check.sh
tools/tms-bitaddr/tests/run.sh
scripts/tests/m3/run.sh
scripts/tests/m3/dis-roundtrip.sh
```
All green; the M3 gates still pass with the corrected `XMapWindow`/`XRaiseWindow`.
- [ ] **Step 5: Commit and push**
```sh
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/CodeGen/TMS34010 TMS34010.md
git -C build/llvm-clean commit -m "tms34010: M4 function pointers, XImage/events and termtris support"
git -C build/llvm-clean push origin m4
git add README.md symbols scripts/m4 scripts/tests/m4 scripts/m3
git commit -m "tests: M4 Xlib images, events and the termtris integration"
git push origin m4
```
Do not force-push, merge into `m0`, or change the default; the controller updates the git.wut.ee default to `m4` after the final review if the user asks.
---
## Execution Handoff
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.
@@ -345,12 +358,15 @@ non-constant pointer expression by 8×.
`harness/sdk-scratch/dis2as34.py`). Emit section sizes and labels in bits.
- Linker command files are CRLF; `SECTIONS` origins are bit addresses.
- **Constant GEPs** become `symbol + bit_addend` (for example
`inttoptr(add(ptrtoint(@.str), 16))`). Before M1 relies on it, verify that
GSPA/gsplnk can carry and relocate a bit addend in both a `MOVI` immediate
and a `.data` initializer. Fallbacks if they cannot: leave `symbol+addend`
entirely to link time, materialize the addend at runtime (`MOVI symbol;
ADDI addend`), or pre-resolve in the linker script. Test a string literal
with an offset, `&arr[1]`, and a global pointer initializer.
`inttoptr(add(ptrtoint(@.str), 16))`). M1 verifies the `MOVI` immediate
form with `&arr[1]`. M1 does not emit `.data`, `.rodata` or string literals
at all: any non-null initializer makes `llc` fail loudly. Verifying a
`symbol+bit_addend` relocation in a `.data` initializer, a string literal
with an offset, and a global pointer initializer is **deferred to M2**
along with `.data` support. Fallbacks if GSPA/gsplnk cannot carry the
addend then: leave `symbol+addend` entirely to link time, materialize the
addend at runtime (`MOVI symbol; ADDI addend`), or pre-resolve in the
linker script.
- Later: native `as34`/`ld34` plus a COFF converter/loader extension, or an
LLVM MC COFF writer. `ld34` output is not COFF, so this is a separate step.
@@ -386,8 +402,9 @@ non-constant pointer expression by 8×.
verifier test; M1 adds the same program through `llc`, checking that late GEPs
carry bit offsets and are not scaled twice (§7.3.1). The spike only reached
`opt`; this is a new gate.
- **Constant-GEP relocation test**: `symbol + bit_addend` in `MOVI` and in
`.data`, plus `&arr[1]` and a global pointer initializer.
- **Constant-GEP relocation test**: M1 covers `symbol + bit_addend` in a
`MOVI` with `&arr[1]`. The `.data` initializer, string-literal and global
pointer initializer parts are deferred to M2 with `.data` support.
- MAME end-to-end: compile a C file, assemble/link, load via
`dwt/loader/loader.lua`, check markers and frame. This is the CI gate.
- Real unit: `dwt/loader/hostload.py`, rdebug. Periodic/optional confirmation,
@@ -430,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
+80 -16
View File
@@ -1,28 +1,92 @@
#!/bin/sh
# Build the pinned LLVM 23.1.5 fork from a clean clone and the committed
# patch series. Intended for CI and for verifying that patches/llvm is the
# complete fork delta.
# Build the TMS34010 LLVM compiler.
#
# Two modes:
#
# upstream + patches (M0, default)
# ./scripts/build-llvm.sh
# Clones llvmorg-23.1.5 into build/llvm-clean, applies patches/llvm and
# builds it. This mode owns its clone and resets it, but refuses to touch
# a checkout whose origin is not llvm-project.
#
# compiler fork (M1 and later)
# LLVM_SRC=$PWD/build/llvm-clean LLVM_BRANCH=tms34010 \
# ./scripts/build-llvm.sh
# LLVM_REPO=gitea@git.wut.ee:opencode.siil.arti.ee/llvm-tms34010.git \
# LLVM_BRANCH=tms34010 ./scripts/build-llvm.sh
# Build the fork branch in place. Fork mode never checks out, resets,
# cleans or patches the source tree; it only configures and builds it.
#
# Environment:
# LLVM_SRC source tree (default build/llvm-clean)
# LLVM_BUILD build tree (default build/llvm-clean-build)
# LLVM_REPO git URL to clone when LLVM_SRC does not exist
# LLVM_BRANCH branch to clone/build; setting this (or LLVM_REPO) selects
# fork mode
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
mkdir -p build
SRC=${LLVM_SRC:-build/llvm-clean}
BUILD=${LLVM_BUILD:-build/llvm-clean-build}
REPO=${LLVM_REPO:-}
BRANCH=${LLVM_BRANCH:-}
TAG=llvmorg-23.1.5
if [ ! -d "$SRC/.git" ]; then
git clone --depth 1 --branch "$TAG" \
https://github.com/llvm/llvm-project.git "$SRC"
fi
git -C "$SRC" checkout --detach "$TAG"
git -C "$SRC" reset --hard
git -C "$SRC" clean -fdx
origin_url() {
git -C "$1" config --get remote.origin.url 2>/dev/null || true
}
PATCHROOT=$(pwd)/patches/llvm
for p in "$PATCHROOT"/*.patch; do
[ -e "$p" ] || continue
git -C "$SRC" apply "$p"
done
if [ -n "$REPO" ] || [ -n "$BRANCH" ]; then
echo "== compiler fork mode: $SRC${BRANCH:+ (branch $BRANCH)}"
if [ ! -e "$SRC/.git" ]; then
[ -n "$REPO" ] || {
echo "build-llvm: $SRC is not a git checkout; set LLVM_REPO to clone it" >&2
exit 1
}
if [ -n "$BRANCH" ]; then
git clone --branch "$BRANCH" "$REPO" "$SRC"
else
git clone "$REPO" "$SRC"
fi
fi
if [ -n "$BRANCH" ]; then
CURRENT=$(git -C "$SRC" rev-parse --abbrev-ref HEAD)
if [ "$CURRENT" != "$BRANCH" ]; then
echo "build-llvm: $SRC is on '$CURRENT', not '$BRANCH'" >&2
echo "build-llvm: check the branch out first; fork mode never" >&2
echo "build-llvm: modifies the source tree" >&2
exit 1
fi
fi
else
echo "== upstream + patches mode: $SRC (tag $TAG)"
if [ -e "$SRC/.git" ]; then
URL=$(origin_url "$SRC")
case "$URL" in
*llvm-project*) ;;
*)
echo "build-llvm: refusing to reset $SRC: origin is" >&2
echo "build-llvm: '${URL:-<none>}', not llvm-project." >&2
echo "build-llvm: use LLVM_REPO/LLVM_BRANCH for a compiler fork" >&2
echo "build-llvm: checkout (default mode must not reset it)" >&2
exit 1
;;
esac
else
git clone --depth 1 --branch "$TAG" \
https://github.com/llvm/llvm-project.git "$SRC"
fi
git -C "$SRC" checkout --detach "$TAG"
git -C "$SRC" reset --hard
git -C "$SRC" clean -fdx
PATCHROOT=$(pwd)/patches/llvm
for p in "$PATCHROOT"/*.patch; do
[ -e "$p" ] || continue
git -C "$SRC" apply "$p"
done
fi
cmake -S "$SRC/llvm" -B "$BUILD" -G Ninja \
-DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON \
@@ -30,4 +94,4 @@ cmake -S "$SRC/llvm" -B "$BUILD" -G Ninja \
-DLLVM_TARGETS_TO_BUILD="X86;TMS34010" \
-DLLVM_INCLUDE_TESTS=ON -DLLVM_INCLUDE_EXAMPLES=OFF \
-DLLVM_INCLUDE_BENCHMARKS=OFF
ninja -C "$BUILD" clang opt llvm-config FileCheck count not
ninja -C "$BUILD" clang opt llc llvm-config FileCheck count not
+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
View File
@@ -0,0 +1 @@
int add(int a, int b) { return a + b; }
+22
View File
@@ -0,0 +1,22 @@
; char-test.asm -- run the compiled char helpers and publish their results.
;
; Appended after char.s so _loadb/_storeb (and every earlier function) keep
; their linked addresses. _start calls this instead of calling _second
; directly, which is the same one-word-size calla; _char_test calls _second
; and returns its result in A0 so the existing second() marker still works.
;
; storeb(018A8080, 0x81) writes the byte 0x81
; loadb(018A8080) returns the sign-extended 0xFFFFFF81
.text
.globl _char_test
_char_test:
calla _second ; A0 = &arr[1]
move a0, a3 ; save it for the second() marker
movi 018A8080h, a0 ; p = storeb/loadb marker byte
movi 81h, a1 ; v = 0x81 (low byte stored by MOVB)
calla _storeb
calla _loadb ; A0 is still 018A8080
movi 018A8060h, a2
move a0, *a2, 1 ; 32-bit loadb marker
move a3, a0 ; restore &arr[1]
rets
+2
View File
@@ -0,0 +1,2 @@
int loadb(char *p) { return *p; }
void storeb(char *p, int v) { *p = v; }
+3
View File
@@ -0,0 +1,3 @@
static int arr[4];
int *second(void) { return &arr[1]; }
+232
View File
@@ -0,0 +1,232 @@
#!/bin/sh
# M1 dis34 round-trip.
#
# scripts/m1/dis-roundtrip.sh
#
# Extracts the linked .text bytes from build/m1/m1.coff (using the COFF
# section table, not a hard-coded file offset), disassembles them with the
# VT1200 tree's dis34 at the linked bit address, and checks that GSPA encoded
# the assembly llc printed:
#
# _add ADD A0, A1 ; MOVE A1, A0 ; RETS 0
# _load MOVE *A0, A0, 1 ; RETS 0
# _late ADDI 24, A0 ; RETS 0
# _second MOVI _arr+32, A0 ; RETS 0
# _loadb MOVB *A0, A0 ; RETS 0
# _storeb MOVB A1, *A0 ; RETS 0
#
# This verifies the 1987 GSPA assembler's encoding, not a dormant LLVM Inst
# encoding. Overridable: M1_COFF DIS34
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
COFF=${M1_COFF:-$ROOT/build/m1/m1.coff}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
fail() {
echo "M1 dis34 round-trip: FAIL: $*" >&2
exit 1
}
[ -f "$COFF" ] || fail "linked COFF not found: $COFF (run scripts/m1/run.sh)"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/m1-dis34.XXXXXX")
FAIL_LOG=${M1_DIS_FAIL_LOG:-${TMPDIR:-/tmp}/m1-dis34-failure.txt}
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
# Read little-endian fields out of the COFF. od keeps this dependency-free.
read_u8s() {
od -An -v -tu1 -j "$1" -N "$2" "$COFF"
}
u16() {
read_u8s "$1" 2 | awk '{ print $1 + 256 * $2 }'
}
u32() {
read_u8s "$1" 4 | awk '{ print $1 + 256 * $2 + 65536 * $3 + 16777216 * $4 }'
}
echo "== parse the COFF section table ($COFF)"
nscns=$(u16 2)
opthdr=$(u16 16)
[ "$nscns" -gt 0 ] 2>/dev/null || fail "COFF has no sections (nscns='$nscns')"
[ "$opthdr" -gt 0 ] 2>/dev/null || fail "COFF has no optional header (opthdr='$opthdr')"
TEXT_ADDR=
TEXT_BITS=
TEXT_PTR=
sh_base=$((20 + opthdr))
i=0
while [ "$i" -lt "$nscns" ]; do
o=$((sh_base + i * 40))
name=$(dd if="$COFF" bs=1 skip="$o" count=8 2>/dev/null | tr -d '\000')
if [ "$name" = ".text" ]; then
TEXT_ADDR=$(u32 $((o + 8)))
TEXT_BITS=$(u32 $((o + 16)))
TEXT_PTR=$(u32 $((o + 20)))
break
fi
i=$((i + 1))
done
[ -n "$TEXT_ADDR" ] || fail "COFF has no .text section"
[ "$TEXT_BITS" -gt 0 ] 2>/dev/null || fail ".text is empty"
[ $((TEXT_BITS % 8)) -eq 0 ] || fail ".text size $TEXT_BITS bits is not whole bytes"
# The linked layout this check was written against.
TEXT_HEX=$(printf '%08X' "$TEXT_ADDR")
ENTRY=$(u32 $((20 + 16)))
ENTRY_HEX=$(printf '%08X' "$ENTRY")
TEXT_BYTES=$((TEXT_BITS / 8))
[ "$TEXT_HEX" = "018A0000" ] \
|| fail ".text is linked at $TEXT_HEX, want 018A0000"
[ "$ENTRY_HEX" = "018A0000" ] \
|| fail "COFF entry point is $ENTRY_HEX, want 018A0000"
[ "$TEXT_PTR" -gt 0 ] || fail ".text has no raw data (scnptr=0)"
echo " .text at $TEXT_HEX: $TEXT_BITS bits ($TEXT_BYTES bytes), scnptr=$TEXT_PTR"
echo " entry point $ENTRY_HEX"
dd if="$COFF" of="$TMP/text.bin" bs=1 skip="$TEXT_PTR" count="$TEXT_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/text.bin")" -eq "$TEXT_BYTES" ] \
|| fail "extracted $(wc -c < "$TMP/text.bin") bytes, want $TEXT_BYTES"
echo "== resolve the linked symbols from the COFF symbol table"
symptr=$(u32 8)
nsyms=$(u32 12)
[ "$symptr" -gt 0 ] 2>/dev/null || fail "COFF has no symbol table"
[ "$nsyms" -gt 0 ] 2>/dev/null || fail "COFF symbol table is empty"
sym_addr() {
_want=$1
_i=0
while [ "$_i" -lt "$nsyms" ]; do
_o=$((symptr + _i * 18))
_n=$(dd if="$COFF" bs=1 skip="$_o" count=8 2>/dev/null | tr -d '\000')
if [ "$_n" = "$_want" ]; then
u32 $((_o + 8))
return 0
fi
_aux=$(od -An -v -tu1 -j $((_o + 17)) -N 1 "$COFF" | awk '{ print $1 }')
_i=$((_i + 1 + _aux))
done
return 1
}
get_sym() {
_name=$1
_addr=$(sym_addr "$_name") || fail "COFF symbol table has no $_name"
[ -n "$_addr" ] || fail "COFF symbol table has no $_name"
printf '%s' "$_addr"
}
ADD=$(get_sym _add)
LOAD=$(get_sym _load)
LATE=$(get_sym _late)
SECOND=$(get_sym _second)
LOADB=$(get_sym _loadb)
STOREB=$(get_sym _storeb)
ADD_HEX=$(printf '%08X' "$ADD")
LOAD_HEX=$(printf '%08X' "$LOAD")
LATE_HEX=$(printf '%08X' "$LATE")
SECOND_HEX=$(printf '%08X' "$SECOND")
LOADB_HEX=$(printf '%08X' "$LOADB")
STOREB_HEX=$(printf '%08X' "$STOREB")
[ "$ADD_HEX" = "018A0240" ] || fail "_add linked at $ADD_HEX, want 018A0240"
[ "$LOAD_HEX" = "018A0270" ] || fail "_load linked at $LOAD_HEX, want 018A0270"
[ "$LATE_HEX" = "018A0290" ] || fail "_late linked at $LATE_HEX, want 018A0290"
[ "$SECOND_HEX" = "018A02C0" ] || fail "_second linked at $SECOND_HEX, want 018A02C0"
[ "$LOADB_HEX" = "018A0300" ] || fail "_loadb linked at $LOADB_HEX, want 018A0300"
[ "$STOREB_HEX" = "018A0320" ] || fail "_storeb linked at $STOREB_HEX, want 018A0320"
echo " _add=$ADD_HEX _load=$LOAD_HEX _late=$LATE_HEX _second=$SECOND_HEX"
echo " _loadb=$LOADB_HEX _storeb=$STOREB_HEX (appended after _second)"
echo "== disassemble the emitted .text with dis34"
"$DIS34" -b "$TEXT_HEX" -l -o "$TMP/text.bin" > "$TMP/dis34.txt" 2> "$TMP/dis34.err" \
|| { cat "$TMP/dis34.err" >&2; fail "dis34 failed"; }
[ -s "$TMP/dis34.txt" ] || fail "dis34 produced no output"
# match_at FILE DECIMAL_ADDR ERE
# dis34 -l prints "018a0240:\tadd a0, a1\t; 4001". The operand must be
# followed by optional whitespace and then the comment/end-of-line marker, so
# "rets 1" cannot satisfy a "rets" pattern.
match_at() {
_file=$1
_addr=$2
_pat=$3
_laddr=$(printf '%08x' "$_addr")
grep -Eiq "^${_laddr}:[[:space:]]+${_pat}([[:space:]]*(;|$))" "$_file"
}
# expect_at LABEL DECIMAL_ADDR EXPECTED_TEXT ERE
expect_at() {
_label=$1
_addr=$2
_want=$3
_pat=$4
_laddr=$(printf '%08x' "$_addr")
if match_at "$TMP/dis34.txt" "$_addr" "$_pat"; then
echo " ok $_label @ 0x$_laddr: $_want"
return 0
fi
{
echo "M1 dis34 round-trip: FAIL"
echo " $_label at bit 0x$_laddr: expected $_want"
echo " dis34 output near 0x$_laddr:"
awk -v a="$_laddr" '
{ low = tolower($0) }
low ~ ("^" a ":") { seen = 1 }
seen { print " " $0; n++ }
seen && n >= 3 { exit }
' "$TMP/dis34.txt"
if cp "$TMP/dis34.txt" "$FAIL_LOG" 2>/dev/null; then
echo " full disassembly preserved at: $FAIL_LOG"
else
echo " full disassembly: $TMP/dis34.txt (temporary; removed on exit)"
fi
} >&2
exit 1
}
expect_label() {
_addr=$1
# dis34 labels branch targets as L followed by %X (no zero padding).
_laddr=$(printf '%x' "$_addr")
grep -Eiq "^L${_laddr}:" "$TMP/dis34.txt" \
|| fail "dis34 did not label the branch target L$(printf '%X' "$_addr")"
echo " ok branch target L$(printf '%X' "$_addr") is labelled"
}
echo "== check the linked instructions"
expect_label "$ADD"
expect_at "_add" "$ADD" "ADD A0, A1" 'add[[:space:]]+a0,[[:space:]]*a1'
expect_at "_add+16" $((ADD + 16)) "MOVE A1, A0" 'move[[:space:]]+a1,[[:space:]]*a0'
expect_at "_add+32" $((ADD + 32)) "RETS 0" 'rets([[:space:]]+0)?'
expect_label "$LOAD"
expect_at "_load" "$LOAD" "MOVE *A0, A0, 1" 'move[[:space:]]+\*a0,[[:space:]]*a0,[[:space:]]*1'
expect_at "_load+16" $((LOAD + 16)) "RETS 0" 'rets([[:space:]]+0)?'
expect_at "_late" "$LATE" "ADDI 24, A0" 'addi[[:space:]]+(0x18|24),[[:space:]]*a0'
expect_at "_late+32" $((LATE + 32)) "RETS 0" 'rets([[:space:]]+0)?'
expect_label "$SECOND"
expect_at "_second" "$SECOND" "MOVI _arr+32, A0" 'movi[[:space:]]+(0x)?18a9020,[[:space:]]*a0'
expect_at "_second+48" $((SECOND + 48)) "RETS 0" 'rets([[:space:]]+0)?'
# Negative control for the RETS operand boundary: "rets 1" must not match.
printf '018a0260:\trets\t1\t; 0960\n' > "$TMP/rets-neg.txt"
if match_at "$TMP/rets-neg.txt" $((ADD + 32)) 'rets([[:space:]]+0)?'; then
fail "negative control: the RETS pattern accepted 'rets 1'"
fi
echo " ok negative control @ 0x$(printf '%08x' $((ADD + 32))): 'rets 1' rejected"
expect_label "$LOADB"
expect_at "_loadb" "$LOADB" "MOVB *A0, A0" 'movb[[:space:]]+\*a0,[[:space:]]*a0'
expect_at "_loadb+16" $((LOADB + 16)) "RETS 0" 'rets([[:space:]]+0)?'
expect_at "_storeb" "$STOREB" "MOVB A1, *A0" 'movb[[:space:]]+a1,[[:space:]]*\*a0'
expect_at "_storeb+16" $((STOREB + 16)) "RETS 0" 'rets([[:space:]]+0)?'
echo "M1 dis34 round-trip: PASS"
+44
View File
@@ -0,0 +1,44 @@
; entry.asm -- M1 smoke-test entry, linked at bit 018A0000.
;
; M1 has no stack frame, no calls and no TI ABI. The generated functions are
; leaf functions: i32/pointer arguments in A0-A3, result in A0.
;
; Marker words (bit addresses, 0x20 bits apart = 4 bytes):
; 018A8000 add(20, 22)
; 018A8020 load(018A8100)
; 018A8040 second() == &arr[1]
; 018A8060 loadb(018A8080) == 0xFFFFFF81 (sign-extended 0x81)
; 018A8080 storeb(018A8080, 0x81) leaves the byte 0x81
;
; _late is linked but not called: it is a compile-time check that a surviving
; GEP offset is 24 bits, not 192.
;
; The char helpers are exercised by _char_test (char-test.asm, appended after
; the compiled functions). Calling it here instead of calling _second keeps
; this entry's size -- and therefore every function's linked address -- the
; same; _char_test calls _second and returns its result in A0.
.text
.globl _start
_start:
setf 32, 0, 1 ; FS1 = 32 for 32-bit MOVE
setf 16, 1, 0 ; FS0 = 16, for any i16 code
movi 20, a0
movi 22, a1
calla _add
movi 018A8000h, a2
move a0, *a2, 1
movi 018A8100h, a2
movi 12345678h, a3
move a3, *a2, 1
move a2, a0
calla _load
movi 018A8020h, a2
move a0, *a2, 1
calla _char_test
movi 018A8040h, a2
move a0, *a2, 1
rets
+9
View File
@@ -0,0 +1,9 @@
/* Late-GEP check: p + 3 bytes must reach llc as ADDI 24 -- the address unit is
* a bit and tms-bitaddr has already scaled the offset -- not ADDI 192.
*
* The plan's source also compared p + 3 with another pointer. That form
* lowers to setcc/branches, which the M1 backend deliberately does not have;
* this form exercises the same late-GEP contract without it. See the M1
* implementation design, sections 7.3 and 7.5.
*/
int late(char *p) { return (int)(p + 3); }
+16
View File
@@ -0,0 +1,16 @@
-a
-o M1.OUT
-m M1.MAP
-e _start
M1.obj
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 018A9000h, length = 1000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+1
View File
@@ -0,0 +1 @@
int load(int *p) { return *p; }
+44
View File
@@ -0,0 +1,44 @@
-- m1-check.lua -- load the M1 COFF with dwt/loader/loader.lua and read the
-- marker words the generated code wrote.
--
-- M1_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- M1_EXPECT_LOAD expected load() result (default 0x12345678)
-- M1_EXPECT_SECOND expected &arr[1] in bits
-- M1_EXPECT_LOADB expected sign-extended byte load (default 0xFFFFFF81)
-- M1_EXPECT_STOREB expected byte store (default 0x81)
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M1_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local EXPECT_LOAD = tonumber(os.getenv("M1_EXPECT_LOAD") or "0x12345678")
local EXPECT_SECOND = tonumber(os.getenv("M1_EXPECT_SECOND") or "0x018A9020")
local EXPECT_LOADB = tonumber(os.getenv("M1_EXPECT_LOADB") or "0xFFFFFF81")
local EXPECT_STOREB = tonumber(os.getenv("M1_EXPECT_STOREB") or "0x81")
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 add = prog:read_u32(0x018A8000)
local load = prog:read_u32(0x018A8020)
local second = prog:read_u32(0x018A8040)
local loadb = prog:read_u32(0x018A8060)
local storeb = prog:read_u8(0x018A8080)
print(string.format(
"M1: add=%d load=0x%08X second=0x%08X loadb=0x%08X storeb=0x%02X",
add, load, second, loadb, storeb))
if add == 42 and load == EXPECT_LOAD and second == EXPECT_SECOND
and loadb == EXPECT_LOADB and storeb == EXPECT_STOREB then
print("M1 MAME: PASS")
else
print(string.format(
"M1 MAME: FAIL (want add=42 load=0x%08X second=0x%08X loadb=0x%08X storeb=0x%02X)",
EXPECT_LOAD, EXPECT_SECOND, EXPECT_LOADB, EXPECT_STOREB))
end
end
end, "m1-check")
+167
View File
@@ -0,0 +1,167 @@
#!/bin/sh
# M1 end-to-end smoke test.
#
# scripts/m1/run.sh
#
# Compiles six C functions with scripts/tms-clang + llc -O0, assembles and
# links them with the 1987 GSPA/GSPLNK 2.00 under DOSBox, then loads the COFF
# into MAME through dwt/loader/loader.lua and checks the marker words:
#
# add(20, 22) == 42
# load(&word) == 0x12345678
# second() == &arr[1] (arr + 32 bits)
# loadb(&byte) == 0xFFFFFF81 (sign-extended 0x81)
# storeb(&byte, 0x81) leaves the byte 0x81
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M1_WORK M1_COFF M1_SDK LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
DIR=$ROOT/scripts/m1
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
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}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${M1_WORK:-$ROOT/build/m1}
COFF=${M1_COFF:-$WORK/m1.coff}
SDK=${M1_SDK:-$ROOT/build/m1-sdk}
ASM=$WORK/asm
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
fail() {
echo "m1: $*" >&2
exit 1
}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
mkdir -p "$(dirname "$COFF")"
echo "== compile and select"
export TMS_CLANG TMS_OPT TMS_BITADDR
for name in add load late const_gep char; do
"$ROOT/scripts/tms-clang" -O2 -o "$ASM/$name.ll" "$DIR/$name.c"
"$TMS_LLC" -march=tms34010 -O0 -filetype=asm \
"$ASM/$name.ll" -o "$ASM/$name.s" \
|| fail "llc failed for $name.c"
echo " $name.s: $(grep -c . "$ASM/$name.s") lines"
done
echo "== check the bit-address constants"
grep -Eq '^[[:space:]]*ADDI[[:space:]]+24,[[:space:]]*A0' "$ASM/late.s" \
|| fail "late.s has no ADDI 24 (late GEP got scaled again?)"
grep -Eq 'ADDI[[:space:]]+192' "$ASM/late.s" \
&& fail "late.s contains ADDI 192: late GEP was scaled twice"
grep -Eq '^[[:space:]]*MOVI[[:space:]]+_arr\+32,[[:space:]]*A0' "$ASM/const_gep.s" \
|| fail "const_gep.s has no 'MOVI _arr+32': constant GEP addend is not in bits"
grep -Eq '_arr\+4[^0-9]' "$ASM/const_gep.s" \
&& fail "const_gep.s references _arr+4 (bytes) instead of _arr+32 (bits)"
echo " late.s: $(grep -E 'ADDI' "$ASM/late.s" | head -1 | sed 's/^[[:space:]]*//')"
echo " const_gep.s: $(grep -E 'MOVI' "$ASM/const_gep.s" | head -1 | sed 's/^[[:space:]]*//')"
echo "== extract the 1987 SDK"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE not extracted into $SDK"
echo "== assemble and link with GSPA/GSPLNK under DOSBox"
cat "$DIR/entry.asm" "$ASM/add.s" "$ASM/load.s" "$ASM/late.s" \
"$ASM/const_gep.s" "$ASM/char.s" "$DIR/char-test.asm" > "$SDK/M1.ASM"
# The linker command file must keep CRLF line endings.
sed 's/\r$//' "$DIR/link.cmd" | sed 's/$/\r/' > "$SDK/M1.CMD"
rm -f "$SDK/M1.OBJ" "$SDK/M1.OUT" "$SDK/M1.MAP" "$SDK/M1.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 M1 M1.obj M1.lst -l" \
-c "gsplnk M1.cmd" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$SDK/M1.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M1.LST" > "$WORK/m1.lst"
grep -q 'No Errors' "$WORK/m1.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/m1.lst" >&2 || true; fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/m1.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/m1.lst" >&2 || true; fail "GSPA reported warnings"; }
[ -f "$SDK/M1.OUT" ] || fail "GSPLNK produced no M1.OUT"
sed 's/\r$//' "$SDK/M1.MAP" > "$WORK/m1.map"
cp "$SDK/M1.OUT" "$COFF"
cp "$SDK/M1.ASM" "$WORK/m1.asm"
ENTRY=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m1.map")
[ "$ENTRY" = "018A0000" ] || fail "linker entry _start is '$ENTRY', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m1.map" \
|| fail "linker map has no _start entry point"
BSS_ORIGIN=$(awk '$1 == ".bss" && $2 == "0" { print $3; exit }' "$WORK/m1.map")
BSS_LENGTH=$(awk '$1 == ".bss" && $2 == "0" { print $4; exit }' "$WORK/m1.map")
[ -n "$BSS_ORIGIN" ] || fail "linker map has no .bss section"
[ "$BSS_LENGTH" = "00000080" ] \
|| fail ".bss is $BSS_LENGTH bits, expected 00000080 (only arr[4])"
# Pin the required layout independently of the map: &arr[1] is arr + 32 bits
# and arr is the first object in the .bss section that link.cmd puts at ram.
[ "$BSS_ORIGIN" = "018A9000" ] \
|| fail "linker .bss origin is $BSS_ORIGIN, want 018A9000 (link.cmd ram origin)"
EXPECT_SECOND=0x018A9020
DERIVED_SECOND=$(printf '0x%08X' "$((0x$BSS_ORIGIN + 32))")
[ "$DERIVED_SECOND" = "$EXPECT_SECOND" ] \
|| fail ".bss origin gives &arr[1] = $DERIVED_SECOND, want $EXPECT_SECOND"
echo " linked .text at 018A0000, .bss at $BSS_ORIGIN (128 bits)"
echo " expected &arr[1] = $EXPECT_SECOND"
echo "== run the COFF in MAME"
[ -x "$MAME" ] || fail "MAME binary not built: $MAME"
[ -f "$LOADER_LUA" ] || fail "COFF loader missing: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "COFF loader payload missing: $LOADER_BIN"
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$COFF" \
LOADER_OUT="$WORK/evidence" \
M1_LOADER_LUA="$LOADER_LUA" \
M1_EXPECT_LOAD=0x12345678 M1_EXPECT_SECOND="$EXPECT_SECOND" \
timeout "${MAME_TIMEOUT:-600}" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/m1-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M1: add=' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M1 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 '^M1 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
echo "M1 MAME: PASS"
+3
View File
@@ -0,0 +1,3 @@
__attribute__((noinline)) int add2(int a, int b) { return a + b; }
__attribute__((noinline)) int first(int a, int b) { return a; }
__attribute__((noinline)) int second(int a, int b) { return b; }
+2
View File
@@ -0,0 +1,2 @@
extern int add2(int, int);
int caller(void) { return add2(20, 22); }
+3
View File
@@ -0,0 +1,3 @@
/* First ROM call: strlen("0::0") must be 4. */
extern int strlen(const char *);
int check(void) { return strlen("0::0"); }
+334
View File
@@ -0,0 +1,334 @@
#!/bin/sh
# M2 dis34 round-trip.
#
# scripts/m2/dis-roundtrip.sh
#
# Extracts the linked .text/.data from build/m2/m2.coff (using the COFF
# section table, not hard-coded file offsets), disassembles the text with the
# VT1200 tree's dis34 at the linked bit address, and checks that GSPA encoded
# the TI-ABI code llc printed:
#
# _strlen JAUC 3FB458D0 (the ROM stub, ABI-preserving)
# _first MOVE A13,A? ; ADDI -32,A? ; RETS 2
# _second ADDI -64,A? ; RETS 2
# _keep old-STK push, argument pushes, CALLA, SETF, LOADSTK, RETS 2
# _locals nonzero frame ADDI, a frame access, RETS 0
#
# It also checks the old-STK operand against the number of pushes before
# SETFP, and the .data bytes contain the "0::0" string literal.
#
# Overridable: M2_COFF DIS34
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
COFF=${M2_COFF:-$ROOT/build/m2/m2.coff}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
fail() {
echo "M2 dis34 round-trip: FAIL: $*" >&2
exit 1
}
[ -f "$COFF" ] || fail "linked COFF not found: $COFF (run scripts/m2/run.sh)"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/m2-dis34.XXXXXX")
FAIL_LOG=${M2_DIS_FAIL_LOG:-${TMPDIR:-/tmp}/m2-dis34-failure.txt}
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
# Read little-endian fields out of the COFF. od keeps this dependency-free.
read_u8s() {
od -An -v -tu1 -j "$1" -N "$2" "$COFF"
}
u16() {
read_u8s "$1" 2 | awk '{ print $1 + 256 * $2 }'
}
u32() {
read_u8s "$1" 4 | awk '{ print $1 + 256 * $2 + 65536 * $3 + 16777216 * $4 }'
}
echo "== parse the COFF section table ($COFF)"
nscns=$(u16 2)
opthdr=$(u16 16)
[ "$nscns" -gt 0 ] 2>/dev/null || fail "COFF has no sections (nscns='$nscns')"
[ "$opthdr" -gt 0 ] 2>/dev/null || fail "COFF has no optional header (opthdr='$opthdr')"
TEXT_ADDR=
TEXT_BITS=
TEXT_PTR=
DATA_ADDR=
DATA_BITS=
DATA_PTR=
sh_base=$((20 + opthdr))
i=0
while [ "$i" -lt "$nscns" ]; do
o=$((sh_base + i * 40))
name=$(dd if="$COFF" bs=1 skip="$o" count=8 2>/dev/null | tr -d '\000')
if [ "$name" = ".text" ]; then
TEXT_ADDR=$(u32 $((o + 8)))
TEXT_BITS=$(u32 $((o + 16)))
TEXT_PTR=$(u32 $((o + 20)))
elif [ "$name" = ".data" ]; then
DATA_ADDR=$(u32 $((o + 8)))
DATA_BITS=$(u32 $((o + 16)))
DATA_PTR=$(u32 $((o + 20)))
fi
i=$((i + 1))
done
[ -n "$TEXT_ADDR" ] || fail "COFF has no .text section"
[ "$TEXT_BITS" -gt 0 ] 2>/dev/null || fail ".text is empty"
[ $((TEXT_BITS % 8)) -eq 0 ] || fail ".text size $TEXT_BITS bits is not whole bytes"
[ -n "$DATA_ADDR" ] || fail "COFF has no .data section"
[ "$DATA_BITS" -gt 0 ] 2>/dev/null || fail ".data is empty"
[ $((DATA_BITS % 8)) -eq 0 ] || fail ".data size $DATA_BITS bits is not whole bytes"
TEXT_HEX=$(printf '%08X' "$TEXT_ADDR")
ENTRY=$(u32 $((20 + 16)))
ENTRY_HEX=$(printf '%08X' "$ENTRY")
TEXT_BYTES=$((TEXT_BITS / 8))
DATA_BYTES=$((DATA_BITS / 8))
[ "$TEXT_HEX" = "018A0000" ] \
|| fail ".text is linked at $TEXT_HEX, want 018A0000"
[ "$ENTRY_HEX" = "018A0000" ] \
|| fail "COFF entry point is $ENTRY_HEX, want 018A0000"
[ "$TEXT_PTR" -gt 0 ] || fail ".text has no raw data (scnptr=0)"
[ "$DATA_PTR" -gt 0 ] || fail ".data has no raw data (scnptr=0)"
echo " .text at $TEXT_HEX: $TEXT_BITS bits ($TEXT_BYTES bytes), scnptr=$TEXT_PTR"
echo " .data at $(printf '%08X' "$DATA_ADDR"): $DATA_BITS bits ($DATA_BYTES bytes), scnptr=$DATA_PTR"
echo " entry point $ENTRY_HEX"
dd if="$COFF" of="$TMP/text.bin" bs=1 skip="$TEXT_PTR" count="$TEXT_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/text.bin")" -eq "$TEXT_BYTES" ] \
|| fail "extracted $(wc -c < "$TMP/text.bin") .text bytes, want $TEXT_BYTES"
dd if="$COFF" of="$TMP/data.bin" bs=1 skip="$DATA_PTR" count="$DATA_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/data.bin")" -eq "$DATA_BYTES" ] \
|| fail "extracted $(wc -c < "$TMP/data.bin") .data bytes, want $DATA_BYTES"
echo "== resolve the linked symbols from the COFF symbol table"
symptr=$(u32 8)
nsyms=$(u32 12)
[ "$symptr" -gt 0 ] 2>/dev/null || fail "COFF has no symbol table"
[ "$nsyms" -gt 0 ] 2>/dev/null || fail "COFF symbol table is empty"
sym_addr() {
_want=$1
_i=0
while [ "$_i" -lt "$nsyms" ]; do
_o=$((symptr + _i * 18))
_n=$(dd if="$COFF" bs=1 skip="$_o" count=8 2>/dev/null | tr -d '\000')
if [ "$_n" = "$_want" ]; then
u32 $((_o + 8))
return 0
fi
_aux=$(od -An -v -tu1 -j $((_o + 17)) -N 1 "$COFF" | awk '{ print $1 }')
_i=$((_i + 1 + _aux))
done
return 1
}
get_sym() {
_name=$1
_addr=$(sym_addr "$_name") || fail "COFF symbol table has no $_name"
[ -n "$_addr" ] || fail "COFF symbol table has no $_name"
printf '%s' "$_addr"
}
STRLEN=$(get_sym _strlen)
FIRST=$(get_sym _first)
SECOND=$(get_sym _second)
KEEP=$(get_sym _keep)
LOCALS=$(get_sym _locals)
ADD2=$(get_sym _add2)
STRLEN_HEX=$(printf '%08X' "$STRLEN")
FIRST_HEX=$(printf '%08X' "$FIRST")
SECOND_HEX=$(printf '%08X' "$SECOND")
KEEP_HEX=$(printf '%08X' "$KEEP")
LOCALS_HEX=$(printf '%08X' "$LOCALS")
ADD2_HEX=$(printf '%08X' "$ADD2")
echo " _strlen=$STRLEN_HEX _first=$FIRST_HEX _second=$SECOND_HEX"
echo " _add2=$ADD2_HEX _keep=$KEEP_HEX _locals=$LOCALS_HEX"
echo "== disassemble the emitted .text with dis34"
"$DIS34" -b "$TEXT_HEX" -l -o "$TMP/text.bin" > "$TMP/dis34.txt" 2> "$TMP/dis34.err" \
|| { cat "$TMP/dis34.err" >&2; fail "dis34 failed"; }
[ -s "$TMP/dis34.txt" ] || fail "dis34 produced no output"
# match_at FILE DECIMAL_ADDR ERE
# dis34 -l prints "018a05c0:\tmove a13, a0\t; 4da0". The operand must be
# followed by optional whitespace and then the comment/end-of-line marker, so
# "rets 1" cannot satisfy a "rets" pattern.
match_at() {
_file=$1
_addr=$2
_pat=$3
_laddr=$(printf '%08x' "$_addr")
grep -Eiq "^${_laddr}:[[:space:]]+${_pat}([[:space:]]*(;|$))" "$_file"
}
# expect_at LABEL DECIMAL_ADDR EXPECTED_TEXT ERE
expect_at() {
_label=$1
_addr=$2
_want=$3
_pat=$4
_laddr=$(printf '%08x' "$_addr")
if match_at "$TMP/dis34.txt" "$_addr" "$_pat"; then
echo " ok $_label @ 0x$_laddr: $_want"
return 0
fi
{
echo "M2 dis34 round-trip: FAIL"
echo " $_label at bit 0x$_laddr: expected $_want"
echo " dis34 output near 0x$_laddr:"
awk -v a="$_laddr" '
{ low = tolower($0) }
low ~ ("^" a ":") { seen = 1 }
seen { print " " $0; n++ }
seen && n >= 4 { exit }
' "$TMP/dis34.txt"
if cp "$TMP/dis34.txt" "$FAIL_LOG" 2>/dev/null; then
echo " full disassembly preserved at: $FAIL_LOG"
else
echo " full disassembly: $TMP/dis34.txt (temporary; removed on exit)"
fi
} >&2
exit 1
}
# func_body DECIMAL_ADDR > FILE: the function's instructions, through RETS.
func_body() {
_laddr=$(printf '%08x' "$1")
awk -v a="$_laddr" '
{ low = tolower($0) }
low ~ ("^" a ":") { on = 1 }
on { print }
on && low ~ /^[0-9a-f]+:[[:space:]]+rets([[:space:]]|;|$)/ { exit }
' "$TMP/dis34.txt"
}
# expect_in BODY EXPECTED_TEXT ERE
expect_in() {
_file=$1
_want=$2
_pat=$3
if grep -Eiq "$_pat" "$_file"; then
echo " ok $_want"
return 0
fi
echo "M2 dis34 round-trip: FAIL: missing $_want" >&2
sed 's/^/ /' "$_file" >&2
exit 1
}
# expect_seq BODY REGEX...: each pattern must occur, in order, after the last.
expect_seq() {
_file=$1
shift
_last=0
for _pat in "$@"; do
_line=$(awk -v start="$_last" -v pat="$_pat" '
NR > start && tolower($0) ~ pat { print NR; exit }
' "$_file")
[ -n "$_line" ] || {
echo "M2 dis34 round-trip: FAIL: call sequence missing /$_pat/" >&2
sed 's/^/ /' "$_file" >&2
exit 1
}
_last=$_line
done
echo " ok call sequence ($# instructions/operands, in order)"
}
echo "== check the linked instructions"
# ROM import stub: absolute unconditional jump, ABI-preserving.
expect_at "_strlen" "$STRLEN" "JAUC 3FB458D0" \
'jauc[[:space:]]+0x3fb458d0'
# _first must materialise its frame pointer and load argument 0 at FP(-32).
func_body "$FIRST" > "$TMP/first.txt"
expect_in "$TMP/first.txt" "_first MOVEFP (MOVE A13,A?)" \
'move[[:space:]]+a13,[[:space:]]*a[0-9]+'
expect_in "$TMP/first.txt" "_first ADDI -32" \
'addi[[:space:]]+(0xffe0|-0x20|-32),'
expect_in "$TMP/first.txt" "_first RETS 2" \
'rets[[:space:]]+2([[:space:]]*(;|$))'
# _second loads argument 1 at FP(-64).
func_body "$SECOND" > "$TMP/second.txt"
expect_in "$TMP/second.txt" "_second ADDI -64" \
'addi[[:space:]]+(0xffc0|-0x40|-64),'
expect_in "$TMP/second.txt" "_second RETS 2" \
'rets[[:space:]]+2([[:space:]]*(;|$))'
# _keep exercises the whole call/return path against _add2.
func_body "$KEEP" > "$TMP/keep.txt"
expect_seq "$TMP/keep.txt" \
'move[[:space:]]+a14,[[:space:]]*-\*sp,[[:space:]]*1' \
'move[[:space:]]+[^,]+,[[:space:]]*\*a14\+,[[:space:]]*1' \
'calla' \
'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:]]*(;|$))'
# _locals has a nonzero frame allocation, a frame access and RETS 0.
func_body "$LOCALS" > "$TMP/locals.txt"
expect_in "$TMP/locals.txt" "_locals frame ADDI" \
'addi[[:space:]]+0x0*[1-9a-f][0-9a-f]*,[[:space:]]*a14'
expect_in "$TMP/locals.txt" "_locals frame access" \
'move[[:space:]]+(a[0-9]+,[[:space:]]*\*a[0-9]+|\*a[0-9]+,[[:space:]]*a[0-9]+)'
expect_in "$TMP/locals.txt" "_locals RETS 0" \
'rets([[:space:]]+0)?([[:space:]]*(;|$))'
# Old-STK offset: the LOADSTK operand must count every callee-saved push
# before SETFP, plus the caller's pushed old STK. This is the check the M2
# lit tests deliberately leave to dis34.
echo "== check the old-STK restore offsets"
check_stk() {
_label=$1
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
{ 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 \
| sed 's/.*0x//; s/).*//')
[ -n "$_operand" ] || fail "$_label has no LOADSTK (*SP(n),A14)"
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| 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"
check_stk "_second" "$SECOND"
check_stk "_keep" "$KEEP"
# Negative control for the RETS operand boundary: "rets 1" must not match.
printf '%08x:\trets\t1\t; 0961\n' "$ADD2" > "$TMP/rets-neg.txt"
if match_at "$TMP/rets-neg.txt" "$ADD2" 'rets([[:space:]]+0)?'; then
fail "negative control: the RETS pattern accepted 'rets 1'"
fi
echo " ok negative control @ 0x$(printf '%08x' "$ADD2"): 'rets 1' rejected"
echo "== check the copied .data bytes"
# The check.c string literal "0::0\0" must survive llc -> GSPA -> COFF.
DATA_HEX=$(od -An -v -tx1 "$TMP/data.bin" | tr -d ' \n')
case "$DATA_HEX" in
*303a3a3000*) echo " ok .data contains 30 3A 3A 30 00 (\"0::0\")" ;;
*) fail ".data does not contain 30 3A 3A 30 00 (got $DATA_HEX)" ;;
esac
echo "M2 dis34 round-trip: PASS"
+59
View File
@@ -0,0 +1,59 @@
; entry.asm -- M2 TI ABI smoke-test entry, linked at bit 018A0000.
;
; Markers (0x20 bits apart):
; 018A8000 check() strlen("0::0") == 4
; 018A8020 first(20,22) == 20
; 018A8040 second(20,22) == 22
; 018A8060 caller() add2(20,22) == 42
; 018A8080 locals() == 7
; 018A80A0 keep(10) == 16 (g == 5 before the call, + 11)
.text
.globl _start
_start:
setf 32, 0, 1
setf 16, 1, 0
movi _cstack, a14
move a14, a13
calla _check
movi 018A8000h, a2
move a8, *a2, 1
; first(20, 22): last argument first, on the program stack
move a14, -*sp, 1
movi 22, a0
move a0, *a14+, 1
movi 20, a0
move a0, *a14+, 1
calla _first
movi 018A8020h, a2
move a8, *a2, 1
; second(20, 22)
move a14, -*sp, 1
movi 22, a0
move a0, *a14+, 1
movi 20, a0
move a0, *a14+, 1
calla _second
movi 018A8040h, a2
move a8, *a2, 1
calla _caller
movi 018A8060h, a2
move a8, *a2, 1
calla _locals
movi 018A8080h, a2
move a8, *a2, 1
move a14, -*sp, 1
movi 10, a0
move a0, *a14+, 1
calla _keep
movi 018A80A0h, a2
move a8, *a2, 1
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Generate absolute-jump stubs for the ROM entry points in a per-ROM symbol file.
# Usage: gen-rom-imports.sh symbols/vt1200-v22.syms OUT.asm
set -eu
SYMS=${1:?symbol file}
OUT=${2:?output file}
printf '\t.text\n' > "$OUT"
awk '
/^[[:space:]]*#/ || NF < 2 { next }
{
name = $1
addr = $2
sub(/^0x/, "", addr)
printf "\t.globl _%s\n_%s:\n\tjauc %sh\n", name, name, addr
}
' "$SYMS" >> "$OUT"
+3
View File
@@ -0,0 +1,3 @@
extern int add2(int, int);
int g = 5; /* initialized .data: also tests the loader copy */
int keep(int a) { int x = g; int y = add2(a, 1); return x + y; }
+16
View File
@@ -0,0 +1,16 @@
-a
-o M2.OUT
-m M2.MAP
-e _start
M2.obj
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 018A9000h, length = 40000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+1
View File
@@ -0,0 +1 @@
int locals(void) { volatile int x = 7; return x; }
+51
View File
@@ -0,0 +1,51 @@
-- m2-check.lua -- load the M2 COFF with dwt/loader/loader.lua and read the
-- marker words the compiled TI-ABI code wrote.
--
-- M2_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- M2_EXPECT_CHECK 4 (strlen("0::0"))
-- M2_EXPECT_FIRST 20 (first(20,22))
-- M2_EXPECT_SECOND 22 (second(20,22))
-- M2_EXPECT_CALLER 42 (add2(20,22))
-- M2_EXPECT_LOCALS 7
-- M2_EXPECT_KEEP 16 (g == 5, + keep(10))
--
-- 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 "2700")
local EXPECT_CHECK = tonumber(os.getenv("M2_EXPECT_CHECK") or "4")
local EXPECT_FIRST = tonumber(os.getenv("M2_EXPECT_FIRST") or "20")
local EXPECT_SECOND = tonumber(os.getenv("M2_EXPECT_SECOND") or "22")
local EXPECT_CALLER = tonumber(os.getenv("M2_EXPECT_CALLER") or "42")
local EXPECT_LOCALS = tonumber(os.getenv("M2_EXPECT_LOCALS") or "7")
local EXPECT_KEEP = tonumber(os.getenv("M2_EXPECT_KEEP") or "16")
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 check = prog:read_u32(0x018A8000)
local first = prog:read_u32(0x018A8020)
local second = prog:read_u32(0x018A8040)
local caller = prog:read_u32(0x018A8060)
local locals = prog:read_u32(0x018A8080)
local keep = prog:read_u32(0x018A80A0)
print(string.format(
"M2: check=%d first=%d second=%d caller=%d locals=%d keep=%d",
check, first, second, caller, locals, keep))
if check == EXPECT_CHECK and first == EXPECT_FIRST
and second == EXPECT_SECOND and caller == EXPECT_CALLER
and locals == EXPECT_LOCALS and keep == EXPECT_KEEP then
print("M2 MAME: PASS")
else
print(string.format(
"M2 MAME: FAIL (want check=%d first=%d second=%d caller=%d locals=%d keep=%d)",
EXPECT_CHECK, EXPECT_FIRST, EXPECT_SECOND, EXPECT_CALLER,
EXPECT_LOCALS, EXPECT_KEEP))
end
end
end, "m2-check")
+171
View File
@@ -0,0 +1,171 @@
#!/bin/sh
# M2 end-to-end smoke test: TI ABI + a real ROM strlen call.
#
# scripts/m2/run.sh
#
# Compiles five C translation units with scripts/tms-clang + llc -O0, assembles
# and links them with the 1987 GSPA/GSPLNK 2.00 under DOSBox, then loads the
# COFF into MAME through dwt/loader/loader.lua and checks the marker words:
#
# check() strlen("0::0") == 4
# first(20,22) == 20
# second(20,22) == 22
# caller() add2(20,22) == 42
# locals() == 7
# keep(10) == 16
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M2_WORK M2_COFF M2_SDK LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
DIR=$ROOT/scripts/m2
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
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}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${M2_WORK:-$ROOT/build/m2}
COFF=${M2_COFF:-$WORK/m2.coff}
SDK=${M2_SDK:-$ROOT/build/m2-sdk}
ASM=$WORK/asm
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
SYMS=${M2_SYMS:-$ROOT/symbols/vt1200-v22.syms}
fail() {
echo "m2: $*" >&2
exit 1
}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
mkdir -p "$(dirname "$COFF")"
echo "== compile and select"
export TMS_CLANG TMS_OPT TMS_BITADDR
for name in check args caller locals keep; do
"$ROOT/scripts/tms-clang" -O2 -o "$ASM/$name.ll" "$DIR/$name.c"
"$TMS_LLC" -march=tms34010 -O0 -filetype=asm \
"$ASM/$name.ll" -o "$ASM/$name.s" \
|| fail "llc failed for $name.c"
echo " $name.s: $(grep -c . "$ASM/$name.s") lines"
done
# strlen("0::0") must be a real ROM call, not a folded 4.
grep -q 'CALLA _strlen' "$ASM/check.s" \
|| fail "check.s has no 'CALLA _strlen' (strlen was folded or not called)"
echo " check.s: $(grep -E 'CALLA _strlen' "$ASM/check.s" | head -1 | sed 's/^[[:space:]]*//')"
echo "== generate the per-ROM import stubs"
"$DIR/gen-rom-imports.sh" "$SYMS" "$WORK/rom-imports.asm"
grep -q '^_strlen:' "$WORK/rom-imports.asm" \
|| fail "rom-imports.asm has no _strlen stub"
grep -A1 '^_strlen:' "$WORK/rom-imports.asm" | grep -qi 'jauc 3FB458D0h' \
|| fail "rom-imports.asm _strlen stub does not jump to 3FB458D0h"
echo " _strlen: $(grep -A1 '^_strlen:' "$WORK/rom-imports.asm" | tail -1 | sed 's/^[[:space:]]*//')"
echo "== extract the 1987 SDK"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE not extracted into $SDK"
echo "== assemble and link with GSPA/GSPLNK under DOSBox"
cat "$DIR/entry.asm" "$ASM/check.s" "$ASM/args.s" "$ASM/caller.s" \
"$ASM/locals.s" "$ASM/keep.s" "$WORK/rom-imports.asm" > "$SDK/M2.ASM"
# The linker command file must keep CRLF line endings.
sed 's/\r$//' "$DIR/link.cmd" | sed 's/$/\r/' > "$SDK/M2.CMD"
rm -f "$SDK/M2.OBJ" "$SDK/M2.OUT" "$SDK/M2.MAP" "$SDK/M2.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 M2 M2.obj M2.lst -l" \
-c "gsplnk M2.cmd" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$SDK/M2.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M2.LST" > "$WORK/m2.lst"
grep -q 'No Errors' "$WORK/m2.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/m2.lst" >&2 || true; fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/m2.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/m2.lst" >&2 || true; fail "GSPA reported warnings"; }
[ -f "$SDK/M2.OUT" ] || fail "GSPLNK produced no M2.OUT"
sed 's/\r$//' "$SDK/M2.MAP" > "$WORK/m2.map"
cp "$SDK/M2.OUT" "$COFF"
cp "$SDK/M2.ASM" "$WORK/m2.asm"
ENTRY=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m2.map")
[ "$ENTRY" = "018A0000" ] || fail "linker entry _start is '$ENTRY', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m2.map" \
|| fail "linker map has no _start entry point"
BSS_ORIGIN=$(awk '$1 == ".bss" && $2 == "0" { print $3; exit }' "$WORK/m2.map")
BSS_LENGTH=$(awk '$1 == ".bss" && $2 == "0" { print $4; exit }' "$WORK/m2.map")
[ -n "$BSS_ORIGIN" ] || fail "linker map has no .bss section"
[ "$BSS_ORIGIN" = "018A9000" ] \
|| fail "linker .bss origin is $BSS_ORIGIN, want 018A9000 (link.cmd ram origin)"
[ "$BSS_LENGTH" = "00008000" ] \
|| fail ".bss is $BSS_LENGTH bits, expected 00008000 (_cstack)"
DATA_ORIGIN=$(awk '$1 == ".data" && $2 == "0" { print $3; exit }' "$WORK/m2.map")
DATA_LENGTH=$(awk '$1 == ".data" && $2 == "0" { print $4; exit }' "$WORK/m2.map")
[ -n "$DATA_LENGTH" ] || fail "linker map has no .data section"
[ "$DATA_LENGTH" != "00000000" ] || fail ".data is empty (no initialized globals)"
echo " linked .text at 018A0000, .data at $DATA_ORIGIN ($DATA_LENGTH bits), .bss at $BSS_ORIGIN ($BSS_LENGTH bits)"
echo "== run the COFF in MAME"
[ -x "$MAME" ] || fail "MAME binary not built: $MAME"
[ -f "$LOADER_LUA" ] || fail "COFF loader missing: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "COFF loader payload missing: $LOADER_BIN"
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$COFF" \
LOADER_OUT="$WORK/evidence" \
M2_LOADER_LUA="$LOADER_LUA" \
M2_EXPECT_CHECK=4 M2_EXPECT_FIRST=20 M2_EXPECT_SECOND=22 \
M2_EXPECT_CALLER=42 M2_EXPECT_LOCALS=7 M2_EXPECT_KEEP=16 \
timeout "${MAME_TIMEOUT:-600}" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/m2-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M2: check=' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M2 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 'placed \.data .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .data bytes"
grep -q '^M2 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
echo "M2 MAME: PASS"
+23
View File
@@ -0,0 +1,23 @@
#include "vt1200_xlib.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
int sumto(int n) {
int s = 0;
int i;
for (i = 1; i <= n; i++)
s += i;
return s;
}
int max2(int a, int b) { return a > b ? a : b; }
int lt(int a, int b) { return a < b; }
int branch_test(void) {
MARK(4) = (unsigned int)sumto(10);
MARK(5) = (unsigned int)max2(20, 22);
MARK(6) = (unsigned int)lt(5, 7);
MARK(7) = (unsigned int)layout_screens();
MARK(8) = (unsigned int)layout_root();
return 0;
}
+478
View File
@@ -0,0 +1,478 @@
#!/bin/sh
# M3 dis34 round-trip.
#
# scripts/m3/dis-roundtrip.sh
#
# Parses build/m3/m3.coff, disassembles its linked .text at 018A0000 with the
# VT1200 tree's dis34, and checks that GSPA encoded the compiler output:
#
# _XOpenDisplay/_XCreateSimpleWindow/_XMapWindow/_XSync JAUC <ROM bit addr>
# (XMapWindow is 3FD64F60, MapWindow opcode 8; 3FD645B0 is XRaiseWindow)
# _xhello: 1 push -> CALLA _XOpenDisplay, 9 pushes -> CALLA
# _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 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
#
# Overridable: M3_COFF M3_ASM DIS34
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
WORK=${M3_WORK:-$ROOT/build/m3}
COFF=${M3_COFF:-$WORK/m3.coff}
ASM=${M3_ASM:-$WORK/m3.asm}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
fail() {
echo "M3 dis34 round-trip: FAIL: $*" >&2
exit 1
}
[ -f "$COFF" ] || fail "linked COFF not found: $COFF (run scripts/m3/run.sh)"
[ -f "$ASM" ] || fail "linked assembly not found: $ASM (run scripts/m3/run.sh)"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/m3-dis34.XXXXXX")
FAIL_LOG=${M3_DIS_FAIL_LOG:-${TMPDIR:-/tmp}/m3-dis34-failure.txt}
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
# Read little-endian fields out of the COFF. od keeps this dependency-free.
read_u8s() {
od -An -v -tu1 -j "$1" -N "$2" "$COFF"
}
u16() {
read_u8s "$1" 2 | awk '{ print $1 + 256 * $2 }'
}
u32() {
read_u8s "$1" 4 | awk '{ print $1 + 256 * $2 + 65536 * $3 + 16777216 * $4 }'
}
echo "== parse the COFF section table ($COFF)"
nscns=$(u16 2)
opthdr=$(u16 16)
[ "$nscns" -gt 0 ] 2>/dev/null || fail "COFF has no sections (nscns='$nscns')"
[ "$opthdr" -gt 0 ] 2>/dev/null || fail "COFF has no optional header (opthdr='$opthdr')"
TEXT_ADDR=
TEXT_BITS=
TEXT_PTR=
DATA_ADDR=
DATA_BITS=
DATA_PTR=
sh_base=$((20 + opthdr))
i=0
while [ "$i" -lt "$nscns" ]; do
o=$((sh_base + i * 40))
name=$(dd if="$COFF" bs=1 skip="$o" count=8 2>/dev/null | tr -d '\000')
if [ "$name" = ".text" ]; then
TEXT_ADDR=$(u32 $((o + 8)))
TEXT_BITS=$(u32 $((o + 16)))
TEXT_PTR=$(u32 $((o + 20)))
elif [ "$name" = ".data" ]; then
DATA_ADDR=$(u32 $((o + 8)))
DATA_BITS=$(u32 $((o + 16)))
DATA_PTR=$(u32 $((o + 20)))
fi
i=$((i + 1))
done
[ -n "$TEXT_ADDR" ] || fail "COFF has no .text section"
[ "$TEXT_BITS" -gt 0 ] 2>/dev/null || fail ".text is empty"
[ $((TEXT_BITS % 8)) -eq 0 ] || fail ".text size $TEXT_BITS bits is not whole bytes"
[ -n "$DATA_ADDR" ] || fail "COFF has no .data section"
[ "$DATA_BITS" -gt 0 ] 2>/dev/null || fail ".data is empty"
[ $((DATA_BITS % 8)) -eq 0 ] || fail ".data size $DATA_BITS bits is not whole bytes"
TEXT_HEX=$(printf '%08X' "$TEXT_ADDR")
ENTRY=$(u32 $((20 + 16)))
ENTRY_HEX=$(printf '%08X' "$ENTRY")
TEXT_BYTES=$((TEXT_BITS / 8))
DATA_BYTES=$((DATA_BITS / 8))
[ "$TEXT_HEX" = "018A0000" ] \
|| fail ".text is linked at $TEXT_HEX, want 018A0000"
[ "$ENTRY_HEX" = "018A0000" ] \
|| fail "COFF entry point is $ENTRY_HEX, want 018A0000"
[ "$TEXT_PTR" -gt 0 ] || fail ".text has no raw data (scnptr=0)"
[ "$DATA_PTR" -gt 0 ] || fail ".data has no raw data (scnptr=0)"
echo " .text at $TEXT_HEX: $TEXT_BITS bits ($TEXT_BYTES bytes), scnptr=$TEXT_PTR"
echo " .data at $(printf '%08X' "$DATA_ADDR"): $DATA_BITS bits ($DATA_BYTES bytes), scnptr=$DATA_PTR"
echo " entry point $ENTRY_HEX"
dd if="$COFF" of="$TMP/text.bin" bs=1 skip="$TEXT_PTR" count="$TEXT_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/text.bin")" -eq "$TEXT_BYTES" ] \
|| fail "extracted $(wc -c < "$TMP/text.bin") .text bytes, want $TEXT_BYTES"
dd if="$COFF" of="$TMP/data.bin" bs=1 skip="$DATA_PTR" count="$DATA_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/data.bin")" -eq "$DATA_BYTES" ] \
|| fail "extracted $(wc -c < "$TMP/data.bin") .data bytes, want $DATA_BYTES"
echo "== resolve the linked symbols from the COFF symbol table"
symptr=$(u32 8)
nsyms=$(u32 12)
[ "$symptr" -gt 0 ] 2>/dev/null || fail "COFF has no symbol table"
[ "$nsyms" -gt 0 ] 2>/dev/null || fail "COFF symbol table is empty"
sym_addr() {
_want=$1
_strtab=$((symptr + nsyms * 18))
_i=0
while [ "$_i" -lt "$nsyms" ]; do
_o=$((symptr + _i * 18))
# COFF inline names are 8 bytes; longer names are 0,0,0,0 + a
# string-table offset (the table starts with its own 4-byte size).
if [ "$(u32 "$_o")" -eq 0 ]; then
_soff=$(u32 $((_o + 4)))
_n=$(dd if="$COFF" bs=1 skip=$((_strtab + _soff)) count=64 2>/dev/null |
tr '\000' '\n' | head -1)
else
_n=$(dd if="$COFF" bs=1 skip="$_o" count=8 2>/dev/null | tr -d '\000')
fi
if [ "$_n" = "$_want" ]; then
u32 $((_o + 8))
return 0
fi
_aux=$(od -An -v -tu1 -j $((_o + 17)) -N 1 "$COFF" | awk '{ print $1 }')
_i=$((_i + 1 + _aux))
done
return 1
}
get_sym() {
_name=$1
_addr=$(sym_addr "$_name") || fail "COFF symbol table has no $_name"
[ -n "$_addr" ] || fail "COFF symbol table has no $_name"
printf '%s' "$_addr"
}
XOPEN=$(get_sym _XOpenDisplay)
XCREATE=$(get_sym _XCreateSimpleWindow)
XMAP=$(get_sym _XMapWindow)
XSYNC=$(get_sym _XSync)
XHELLO=$(get_sym _xhello)
SUMTO=$(get_sym _sumto)
MAX2=$(get_sym _max2)
LT=$(get_sym _lt)
BRANCH=$(get_sym _branch_test)
ROOTPROBE=$(get_sym _root_probe)
XOPEN_HEX=$(printf '%08X' "$XOPEN")
XCREATE_HEX=$(printf '%08X' "$XCREATE")
XMAP_HEX=$(printf '%08X' "$XMAP")
XSYNC_HEX=$(printf '%08X' "$XSYNC")
XHELLO_HEX=$(printf '%08X' "$XHELLO")
XOPEN_L=$(printf '%x' "$XOPEN")
XCREATE_L=$(printf '%x' "$XCREATE")
XMAP_L=$(printf '%x' "$XMAP")
XSYNC_L=$(printf '%x' "$XSYNC")
echo " _XOpenDisplay=$XOPEN_HEX _XCreateSimpleWindow=$XCREATE_HEX"
echo " _XMapWindow=$XMAP_HEX _XSync=$XSYNC_HEX"
echo " _xhello=$XHELLO_HEX _sumto=$(printf '%08X' "$SUMTO") _max2=$(printf '%08X' "$MAX2") _lt=$(printf '%08X' "$LT")"
echo " _branch_test=$(printf '%08X' "$BRANCH") _root_probe=$(printf '%08X' "$ROOTPROBE")"
echo "== disassemble the emitted .text with dis34"
"$DIS34" -b "$TEXT_HEX" -l -o "$TMP/text.bin" > "$TMP/dis34.txt" 2> "$TMP/dis34.err" \
|| { cat "$TMP/dis34.err" >&2; fail "dis34 failed"; }
[ -s "$TMP/dis34.txt" ] || fail "dis34 produced no output"
# match_at FILE DECIMAL_ADDR ERE
match_at() {
_file=$1
_addr=$2
_pat=$3
_laddr=$(printf '%08x' "$_addr")
grep -Eiq "^${_laddr}:[[:space:]]+${_pat}([[:space:]]*(;|$))" "$_file"
}
expect_at() {
_label=$1
_addr=$2
_want=$3
_pat=$4
_laddr=$(printf '%08x' "$_addr")
if match_at "$TMP/dis34.txt" "$_addr" "$_pat"; then
echo " ok $_label @ 0x$_laddr: $_want"
return 0
fi
{
echo "M3 dis34 round-trip: FAIL"
echo " $_label at bit 0x$_laddr: expected $_want"
echo " dis34 output near 0x$_laddr:"
awk -v a="$_laddr" '
{ low = tolower($0) }
low ~ ("^" a ":") { seen = 1 }
seen { print " " $0; n++ }
seen && n >= 4 { exit }
' "$TMP/dis34.txt"
if cp "$TMP/dis34.txt" "$FAIL_LOG" 2>/dev/null; then
echo " full disassembly preserved at: $FAIL_LOG"
else
echo " full disassembly: $TMP/dis34.txt (temporary; removed on exit)"
fi
} >&2
exit 1
}
func_body() {
_laddr=$(printf '%08x' "$1")
awk -v a="$_laddr" '
{ low = tolower($0) }
low ~ ("^" a ":") { on = 1 }
on { print }
on && low ~ /^[0-9a-f]+:[[:space:]]+rets([[:space:]]|;|$)/ { exit }
' "$TMP/dis34.txt"
}
expect_in() {
_file=$1
_want=$2
_pat=$3
if grep -Eiq "$_pat" "$_file"; then
echo " ok $_want"
return 0
fi
echo "M3 dis34 round-trip: FAIL: missing $_want" >&2
sed 's/^/ /' "$_file" >&2
exit 1
}
# count_between FILE START_RE END_RE PUSH_RE: count push encodings after the
# START_RE line up to (not including) the END_RE line.
count_between() {
_file=$1
_start=$2
_end=$3
_push=$4
awk -v s="$_start" -v e="$_end" -v p="$_push" '
{ low = tolower($0) }
on && low ~ e { exit }
on && low ~ p { n++ }
low ~ s { on = 1 }
END { print n + 0 }
' "$_file"
}
echo "== check the ROM import stubs"
expect_at "_XOpenDisplay" "$XOPEN" "JAUC 3F9C2570" \
'jauc[[:space:]]+0x3f9c2570'
expect_at "_XCreateSimpleWindow" "$XCREATE" "JAUC 3FD41B90" \
'jauc[[:space:]]+0x3fd41b90'
expect_at "_XMapWindow" "$XMAP" "JAUC 3FD64F60" \
'jauc[[:space:]]+0x3fd64f60'
expect_at "_XSync" "$XSYNC" "JAUC 3FD9F6B0" \
'jauc[[:space:]]+0x3fd9f6b0'
echo "== check the compiled Xlib call sequence"
func_body "$XHELLO" > "$TMP/xhello.txt"
expect_in "$TMP/xhello.txt" "CALLA _XOpenDisplay ($XOPEN_HEX)" \
"calla[[:space:]]+l${XOPEN_L}"
expect_in "$TMP/xhello.txt" "CALLA _XCreateSimpleWindow ($XCREATE_HEX)" \
"calla[[:space:]]+l${XCREATE_L}"
expect_in "$TMP/xhello.txt" "CALLA _XMapWindow ($XMAP_HEX)" \
"calla[[:space:]]+l${XMAP_L}"
expect_in "$TMP/xhello.txt" "CALLA _XSync ($XSYNC_HEX)" \
"calla[[:space:]]+l${XSYNC_L}"
# The arguments are pushed last-first onto the program stack; the first
# argument (background=1 for XCreateSimpleWindow) is pushed last.
P1=$(count_between "$TMP/xhello.txt" '^[0-9a-f]+:[[:space:]]+setf[[:space:]]+16' \
"calla[[:space:]]+l${XOPEN_L}" 'move[[:space:]]+[^,]+, *\*a14\+, *1')
P2=$(count_between "$TMP/xhello.txt" "calla[[:space:]]+l${XOPEN_L}" \
"calla[[:space:]]+l${XCREATE_L}" 'move[[:space:]]+[^,]+, *\*a14\+, *1')
P3=$(count_between "$TMP/xhello.txt" "calla[[:space:]]+l${XCREATE_L}" \
"calla[[:space:]]+l${XMAP_L}" 'move[[:space:]]+[^,]+, *\*a14\+, *1')
P4=$(count_between "$TMP/xhello.txt" "calla[[:space:]]+l${XMAP_L}" \
"calla[[:space:]]+l${XSYNC_L}" 'move[[:space:]]+[^,]+, *\*a14\+, *1')
[ "$P1" -eq 1 ] || fail "XOpenDisplay has $P1 argument pushes, want 1"
[ "$P2" -eq 9 ] || fail "XCreateSimpleWindow has $P2 argument pushes, want 9"
[ "$P3" -eq 2 ] || fail "XMapWindow has $P3 argument pushes, want 2"
[ "$P4" -eq 2 ] || fail "XSync has $P4 argument pushes, want 2"
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. 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 '
/^[[:space:]]*CALLA[[:space:]]+_XOpenDisplay/ { on = 1; next }
/^[[:space:]]*CALLA[[:space:]]+_XCreateSimpleWindow/ { exit }
!on { next }
/^[[:space:]]*MOVI[[:space:]]/ {
line = $0
sub(/.*MOVI[[:space:]]+/, "", line)
sub(/[[:space:]]*;.*/, "", line)
split(line, p, /,[[:space:]]*/)
gsub(/[[:space:]]/, "", p[1])
gsub(/[[:space:]]/, "", p[2])
val[p[2]] = p[1]
next
}
/^[[:space:]]*MOVE[[:space:]]+A[0-9]+,[[:space:]]*\*A14\+,/ {
line = $0
sub(/.*MOVE[[:space:]]+/, "", line)
sub(/,.*/, "", line)
v = val[line]
if (line == "A2") v = "root"
if (line == "A0") v = "display"
print v
}
' "$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.vals"
} >&2
exit 1
fi
echo " ok XCreateSimpleWindow argument order: 1,0,2,200,400,100,100,root,display (display pushed last)"
# Xlib clobbers SETF; the compiler must re-establish 16/FS0 and 32/FS1 after
# every call. Check in the linked assembly, where CALLA symbols survive.
awk '
/^_xhello:/ { on = 1; next }
on && /-- End function/ { exit }
on && /^[[:space:]]*CALLA/ { pending = 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
}
END { print n + 0 }
' "$ASM" > "$TMP/setf_count"
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,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.
func_body "$XHELLO" > "$TMP/xhello.txt"
expect_in "$TMP/xhello.txt" "_xhello RETS 0" 'rets([[:space:]]+0)?([[:space:]]*(;|$))'
for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
addr=${pair%%:*}
label=${pair##*:}
func_body "$addr" > "$TMP/fn.txt"
expect_in "$TMP/fn.txt" "$label RETS 2" 'rets[[:space:]]+2([[:space:]]*(;|$))'
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##*:}
func_body "$addr" > "$TMP/fn.txt"
if ! grep -Eiq 'cmp' "$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no CMP"
fi
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 branch"
fi
echo " ok $label: CMP + branch"
done
for pair in "$XHELLO:_xhello"; do
addr=${pair%%:*}
label=${pair##*:}
func_body "$addr" > "$TMP/fn.txt"
if ! grep -Eiq '\bjauc\b' "$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no JAUC"
fi
echo " ok $label: JAUC"
done
func_body "$BRANCH" > "$TMP/branch.txt"
for callee in _sumto _max2 _lt _layout_screens _layout_root; do
grep -Eiq "calla[[:space:]]+L$(get_sym "$callee" | xargs printf '%X')" "$TMP/branch.txt" \
|| fail "_branch_test does not call $callee"
done
echo " ok _branch_test calls sumto, max2, lt, layout_screens, layout_root"
# 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"
if grep -q '\.LBB' "$ASM"; then
fail "linked assembly contains dotted .LBB labels (GSPA rejects them)"
fi
echo " ok LBB… block labels (no dot)"
echo "== check the old-STK restore offsets"
check_stk() {
_label=$1
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
{ 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 \
| sed 's/.*0x//; s/).*//')
[ -n "$_operand" ] || fail "$_label has no LOADSTK (*SP(n),A14)"
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| 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"
check_stk "_lt" "$LT"
check_stk "_root_probe" "$ROOTPROBE"
# Negative control for the RETS operand boundary: "rets 1" must not match.
printf '%08x:\trets\t1\t; 0961\n' "$SUMTO" > "$TMP/rets-neg.txt"
if match_at "$TMP/rets-neg.txt" "$SUMTO" 'rets([[:space:]]+0)?'; then
fail "negative control: the RETS pattern accepted 'rets 1'"
fi
echo " ok negative control @ 0x$(printf '%08x' "$SUMTO"): 'rets 1' rejected"
echo "== check the copied .data bytes"
DATA_HEX=$(od -An -v -tx1 "$TMP/data.bin" | tr -d ' \n')
case "$DATA_HEX" in
*303a3a3000*) echo " ok .data contains 30 3A 3A 30 00 (\"0::0\")" ;;
*) fail ".data does not contain 30 3A 3A 30 00 (got $DATA_HEX)" ;;
esac
echo "M3 dis34 round-trip: PASS"
+25
View File
@@ -0,0 +1,25 @@
; entry.asm -- M3 entry, linked at bit 018A0000.
;
; Calls the compiled branch/loop tests and then the first compiled C Xlib
; client. Markers (0x20 bits apart):
; 018A8000 Display pointer (xhello)
; 018A8020 root window (xhello)
; 018A8040 window id (xhello)
; 018A8060 XSync diagnostic (xhello)
; 018A8080 sumto(10) == 55 (branch_test)
; 018A80A0 max2(20,22) == 22 (branch_test)
; 018A80C0 lt(5,7) == 1 (branch_test)
; 018A80E0 layout_screens() == 0x480
; 018A8100 layout_root() == 0x40
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _branch_test
calla _xhello
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+7
View File
@@ -0,0 +1,7 @@
struct display { char pad[0x90]; void *screens; };
struct screen { char pad[0x8]; unsigned int root; };
/* The 1987 compiler's &-of-member is a bit address, so these return the
ROM's bit offsets 0x480/0x40 directly. */
int layout_screens() { return (int)&((struct display *)0)->screens; }
int layout_root() { return (int)&((struct screen *)0)->root; }
+29
View File
@@ -0,0 +1,29 @@
*******************************************************
* GSP C COMPILER, Version 2.01, 87.300 *
*******************************************************
FP .set A13
STK .set A14
.globl _layout_screens
.file "LAYOUT.c"
******************************************************
* FUNCTION DEF : _layout_screens
******************************************************
_layout_screens:
MOVE A7,-*SP,1
MOVI 1152,A7
MOVE A7,A8
EPI0_1:
MOVE *SP+,A7,1
RETS 0
.globl _layout_root
******************************************************
* FUNCTION DEF : _layout_root
******************************************************
_layout_root:
MOVE A7,-*SP,1
MOVI 64,A7
MOVE A7,A8
EPI0_2:
MOVE *SP+,A7,1
RETS 0
.end
+21
View File
@@ -0,0 +1,21 @@
#include "vt1200_xlib.h"
/* The ROM's indirect displacements are bit offsets (xhello.asm):
Display.screens at bit 0x480, Screen.root at bit 0x40. C struct offsets
are bytes, so assert the byte offsets and return the ROM's bit offsets. */
_Static_assert(__builtin_offsetof(Display, screens) == 0x90,
"Display.screens must be at byte 0x90 (bit 0x480)");
_Static_assert(__builtin_offsetof(Screen, root) == 0x8,
"Screen.root must be at byte 0x8 (bit 0x40)");
int layout_screens(void) {
return (int)__builtin_offsetof(Display, screens) * 8;
}
int layout_root(void) {
return (int)__builtin_offsetof(Screen, root) * 8;
}
/* Exercise the real access path: vt1200_root() follows Display.screens (bit
0x480) and reads Screen.root (bit 0x40). The align-1 loads this generates
must select MOVE directly (see m3-unaligned.ll). */
unsigned int root_probe(Display *d) { return vt1200_root(d); }
+16
View File
@@ -0,0 +1,16 @@
-a
-o M3.OUT
-m M3.MAP
-e _start
M3.obj
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 018A9000h, length = 40000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+79
View File
@@ -0,0 +1,79 @@
-- m3-check.lua -- load the M3 COFF with dwt/loader/loader.lua, read the
-- compiled branch/Xlib marker words, and prove a window was mapped by reading
-- the white background pixel in VRAM.
--
-- M3_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
-- XSync is diagnostic only; the pass requires the visible white pixel.
--
-- The DWT root window is a fine monochrome weave, so one set bit at (150,150)
-- cannot distinguish the mapped client window from the root. Require the
-- whole 32-bit VRAM word containing (150,150) to be 0xFFFFFFFF, and check a
-- second interior word at (250,200) so the client area is proven solid, not
-- just a lucky white stripe.
dofile(os.getenv("M3_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
-- Window: XCreateSimpleWindow(display, root, 100, 100, 400, 200, 2, 0, 1).
-- The client area starts at (102,102); sample well inside it.
local VRAM_BASE = 0x04000000
local VRAM_PITCH = 2048 -- VR319: 2048 bits per row
local WHITE_WORD = 0xFFFFFFFF
local PX, PY = 150, 150
local PX2, PY2 = 250, 200
local frames = 0
local checked = false
local function vram_word(prog, x, y)
local bit = VRAM_BASE + y * VRAM_PITCH + x
local word = bit - (bit % 32)
return prog:read_u32(word), word, 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 display = prog:read_u32(0x018A8000)
local root = prog:read_u32(0x018A8020)
local window = prog:read_u32(0x018A8040)
local sync = prog:read_u32(0x018A8060)
local sum = prog:read_u32(0x018A8080)
local maxv = prog:read_u32(0x018A80A0)
local ltv = prog:read_u32(0x018A80C0)
local screens = prog:read_u32(0x018A80E0)
local rootoff = prog:read_u32(0x018A8100)
-- The full words containing each sample pixel.
local pix, word, bit = vram_word(prog, PX, PY)
local pix2, word2, bit2 = vram_word(prog, PX2, PY2)
local solid = pix == WHITE_WORD
local solid2 = pix2 == WHITE_WORD
print(string.format(
"M3: display=%u root=%u window=%u sync=%d sum=%d max=%d lt=%d screens=0x%x root_off=0x%x",
display, root, window, sync, sum, maxv, ltv, screens, rootoff))
print(string.format(
"M3: pixel(%d,%d) bit=0x%08X word=0x%08X value=0x%08X %s",
PX, PY, bit, word, pix, solid and "SOLID-WHITE" or "not-solid-white"))
print(string.format(
"M3: pixel(%d,%d) bit=0x%08X word=0x%08X value=0x%08X %s",
PX2, PY2, bit2, word2, pix2, solid2 and "SOLID-WHITE" or "not-solid-white"))
local ok = display ~= 0 and root ~= 0 and window ~= 0
and sum == 55 and maxv == 22 and ltv == 1
and screens == 0x480 and rootoff == 0x40
and solid and solid2
if ok then
print("M3 MAME: PASS")
else
print("M3 MAME: FAIL")
end
end
end, "m3-check")
+226
View File
@@ -0,0 +1,226 @@
#!/bin/sh
# M3 end-to-end test: compiled branches/loops plus the first compiled C Xlib
# client, linked with the 1987 GSPA/GSPLNK toolchain and run in MAME.
#
# scripts/m3/run.sh
#
# Compiles xhello.c, branch.c and layout.c with scripts/tms-clang -O2 and
# llc -O0, assembles/links them with the SDK under DOSBox, loads the COFF
# through dwt/loader/loader.lua, and checks:
#
# 018A8000 Display pointer (nonzero)
# 018A8020 root window id (nonzero)
# 018A8040 window id (nonzero)
# 018A8060 XSync result (diagnostic only)
# 018A8080 sumto(10) == 55
# 018A80A0 max2(20,22)== 22
# 018A80C0 lt(5,7) == 1
# 018A80E0 layout_screens() == 0x480
# 018A8100 layout_root() == 0x40
#
# XMapWindow is the true MapWindow entry 3FD64F60 (request opcode 8);
# 3FD645B0 is XRaiseWindow (ConfigureWindow opcode 12), not a mapping call.
#
# and, decisively, the full all-white VRAM word at (150,150) and another at
# (250,200) inside the mapped window. A markers-only or root-window bit is a
# failure.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M3_WORK M3_COFF M3_SDK LOADER_AT LOADER_END
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
DIR=$ROOT/scripts/m3
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
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}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${M3_WORK:-$ROOT/build/m3}
COFF=${M3_COFF:-$WORK/m3.coff}
SDK=${M3_SDK:-$ROOT/build/m3-sdk}
ASM=$WORK/asm
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-3400}
SYMS=${M3_SYMS:-$ROOT/symbols/vt1200-v22.syms}
fail() {
echo "m3: $*" >&2
exit 1
}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
mkdir -p "$ASM" "$WORK/evidence" "$WORK/run/nvram" "$WORK/run/cfg"
mkdir -p "$(dirname "$COFF")"
# IndVarSimplify's exit-value replacement turns sumto's loop into an i33
# multiply (n*(n+1)/2), and this target has no multiply or i64 support: llc
# then dies selecting umul_lohi. Keep the loop (which is the point of the M3
# branch test) by disabling only that rewrite, and only for branch.c; xhello
# and layout use the normal optimizer pipeline. branch.c itself is unchanged.
OPT_NOREPLEXIT=$WORK/opt-keep-loops
printf '#!/bin/sh\nexec "%s" -replexitval=never "$@"\n' "$TMS_OPT" > "$OPT_NOREPLEXIT"
chmod +x "$OPT_NOREPLEXIT"
echo "== compile and select"
export TMS_CLANG TMS_BITADDR
for name in xhello branch layout; do
opt=$TMS_OPT
[ "$name" = branch ] && opt=$OPT_NOREPLEXIT
TMS_OPT=$opt "$ROOT/scripts/tms-clang" -O2 -I "$DIR" -o "$ASM/$name.ll" "$DIR/$name.c"
"$TMS_LLC" -march=tms34010 -O0 -filetype=asm \
"$ASM/$name.ll" -o "$ASM/$name.s" \
|| fail "llc failed for $name.c"
echo " $name.s: $(grep -c . "$ASM/$name.s") lines"
done
# The Xlib calls must be real ROM imports, and the window must use background
# pixel 1 (white).
grep -q 'CALLA _XOpenDisplay' "$ASM/xhello.s" \
|| fail "xhello.s has no 'CALLA _XOpenDisplay'"
grep -q 'CALLA _XCreateSimpleWindow' "$ASM/xhello.s" \
|| fail "xhello.s has no 'CALLA _XCreateSimpleWindow'"
grep -q 'CALLA _XMapWindow' "$ASM/xhello.s" \
|| fail "xhello.s has no 'CALLA _XMapWindow'"
grep -q 'CALLA _XSync' "$ASM/xhello.s" \
|| fail "xhello.s has no 'CALLA _XSync'"
# 9 arguments: background=1, border=0, width=2, height=200, width=400, y=100,
# x=100, root, display. The first argument (background) is the last pushed,
# i.e. the first MOVI before the nine '*A14+' stores.
PUSHES=$(awk '
/MOVE .*, *\*A14\+, *1/ { n++ }
/CALLA/ { if ($0 ~ /_XCreateSimpleWindow/) print n; n = 0 }
' "$ASM/xhello.s")
[ "$PUSHES" = "9" ] || fail "XCreateSimpleWindow has $PUSHES pushes, want 9"
grep -q 'MOVI 1, ' "$ASM/xhello.s" \
|| fail "xhello.s has no background pixel 1 (white)"
echo " XCreateSimpleWindow: 9 argument pushes, background pixel 1"
echo "== generate the per-ROM import stubs"
"$ROOT/scripts/m2/gen-rom-imports.sh" "$SYMS" "$WORK/rom-imports.asm"
for sym in XOpenDisplay XCreateSimpleWindow XMapWindow XSync; do
grep -q "^_$sym:" "$WORK/rom-imports.asm" \
|| fail "rom-imports.asm has no _$sym stub"
done
grep -A1 '^_XOpenDisplay:' "$WORK/rom-imports.asm" | grep -qi 'jauc 3F9C2570h' \
|| fail "rom-imports.asm _XOpenDisplay stub does not jump to 3F9C2570h"
echo " _XOpenDisplay: $(grep -A1 '^_XOpenDisplay:' "$WORK/rom-imports.asm" | tail -1 | sed 's/^[[:space:]]*//')"
echo "== extract the 1987 SDK"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE not extracted into $SDK"
echo "== assemble and link with GSPA/GSPLNK under DOSBox"
# GSPA 2.00 has one flat symbol table per assembly, and llc names basic blocks
# LBB0_1, LBB1_2, ... restarting in every translation unit. Concatenating the
# three TUs would therefore collide (DUPLICATE DEFINITION). Give each TU its
# own LBB prefix; the labels stay LBB… (GSPA rejects dotted .L labels).
for pair in branch:B layout:L xhello:X; do
src=${pair%%:*}
tag=${pair##*:}
sed "s/LBB\([0-9][0-9]*_[0-9][0-9]*\)/LBB$tag\1/g" \
"$ASM/$src.s" > "$ASM/$src.unique.s"
done
cat "$DIR/entry.asm" "$ASM/branch.unique.s" "$ASM/layout.unique.s" \
"$ASM/xhello.unique.s" "$WORK/rom-imports.asm" > "$SDK/M3.ASM"
# The linker command file must keep CRLF line endings.
sed 's/\r$//' "$DIR/link.cmd" | sed 's/$/\r/' > "$SDK/M3.CMD"
rm -f "$SDK/M3.OBJ" "$SDK/M3.OUT" "$SDK/M3.MAP" "$SDK/M3.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 M3 M3.obj M3.lst -l" \
-c "gsplnk M3.cmd" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -20 "$WORK/dosbox.log" >&2; fail "DOSBox failed"; }
[ -f "$SDK/M3.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/M3.LST" > "$WORK/m3.lst"
grep -q 'No Errors' "$WORK/m3.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/m3.lst" >&2 || true; fail "GSPA reported errors"; }
grep -q 'No Warnings' "$WORK/m3.lst" \
|| { grep -i -B2 -A2 'warning' "$WORK/m3.lst" >&2 || true; fail "GSPA reported warnings"; }
[ -f "$SDK/M3.OUT" ] || fail "GSPLNK produced no M3.OUT"
sed 's/\r$//' "$SDK/M3.MAP" > "$WORK/m3.map"
cp "$SDK/M3.OUT" "$COFF"
cp "$SDK/M3.ASM" "$WORK/m3.asm"
ENTRY=$(awk '$2 == "_start" { print $1; exit }' "$WORK/m3.map")
[ "$ENTRY" = "018A0000" ] || fail "linker entry _start is '$ENTRY', want 018A0000"
grep -q 'ENTRY POINT SYMBOL: "_start"' "$WORK/m3.map" \
|| fail "linker map has no _start entry point"
BSS_ORIGIN=$(awk '$1 == ".bss" && $2 == "0" { print $3; exit }' "$WORK/m3.map")
BSS_LENGTH=$(awk '$1 == ".bss" && $2 == "0" { print $4; exit }' "$WORK/m3.map")
[ -n "$BSS_ORIGIN" ] || fail "linker map has no .bss section"
[ "$BSS_ORIGIN" = "018A9000" ] \
|| fail "linker .bss origin is $BSS_ORIGIN, want 018A9000 (link.cmd ram origin)"
[ "$BSS_LENGTH" = "00008000" ] \
|| fail ".bss is $BSS_LENGTH bits, expected 00008000 (_cstack)"
DATA_ORIGIN=$(awk '$1 == ".data" && $2 == "0" { print $3; exit }' "$WORK/m3.map")
DATA_LENGTH=$(awk '$1 == ".data" && $2 == "0" { print $4; exit }' "$WORK/m3.map")
[ -n "$DATA_LENGTH" ] || fail "linker map has no .data section"
[ "$DATA_LENGTH" != "00000000" ] || fail ".data is empty (no \"0::0\" literal)"
echo " linked .text at 018A0000, .data at $DATA_ORIGIN ($DATA_LENGTH bits), .bss at $BSS_ORIGIN ($BSS_LENGTH bits)"
echo "== run the COFF in MAME"
[ -x "$MAME" ] || fail "MAME binary not built: $MAME"
[ -f "$LOADER_LUA" ] || fail "COFF loader missing: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "COFF loader payload missing: $LOADER_BIN"
# Start from empty NVRAM and pin the monitor: the pixel check assumes the real
# VR319 2048-bit row pitch, and stale NVRAM must not change the boot state.
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$COFF" \
LOADER_OUT="$WORK/evidence" \
M3_LOADER_LUA="$LOADER_LUA" \
timeout "${MAME_TIMEOUT:-900}" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/m3-check.lua" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
MARKERS=$(grep -E '^M3: display=' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M3 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 'placed \.data .* 0 differing' "$WORK/mame.log" \
|| fail "COFF loader could not verify the placed .data bytes"
grep -q '^M3 MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "M3 marker/window check failed"; }
echo "M3 MAME: PASS"
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# M3 ROM symbol validation: the four Xlib entry points used by the compiled
# client must exist in the v2.2 table, sit in the ROM's bit range, be 16-bit
# aligned, and disassemble to a plausible function prologue.
#
# This is a regression check, not a re-extraction: dwt/gui/xhello.asm and the
# termtris xlib.h are the evidence that these entries work. XMapWindow is the
# true map entry (MapWindow request opcode 8); 0x3FD645B0 is XRaiseWindow
# (ConfigureWindow opcode 12), never a mapping call. M4 extends the table for
# XImage/XEvent and validates every entry independently in
# scripts/m4/validate-syms.sh.
#
# scripts/m3/validate-syms.sh [symbols/vt1200-v22.syms]
#
# Overridable: M3_SYMS DIS34 ROM
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
SYMS=${1:-${M3_SYMS:-$ROOT/symbols/vt1200-v22.syms}}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
ROM=${ROM:-$ROOT/vendor/vt1200/vt1200_v22.bin}
ROM_LO=$((0x3F200000))
ROM_HI=$((0x3FFFFFFF))
fail() {
echo "m3 validate-syms: FAIL: $*" >&2
exit 1
}
[ -f "$SYMS" ] || fail "symbol file not found: $SYMS"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
[ -f "$ROM" ] || fail "ROM image not found: $ROM"
check_sym() { # check_sym NAME EXPECTED_HEX
name=$1
expected=$2
got=$(awk -v n="$name" '$1 == n { print $2; exit }' "$SYMS")
[ -n "$got" ] || fail "$SYMS has no $name entry"
[ "$got" = "$expected" ] \
|| fail "$name is $got, expected $expected (the xhello.asm-proven entry)"
addr=$((got))
[ "$addr" -ge "$ROM_LO" ] && [ "$addr" -le "$ROM_HI" ] \
|| fail "$name $got is outside the ROM bit range 3F200000h..3FFFFFFFh"
[ $((addr % 16)) -eq 0 ] \
|| fail "$name $got is not 16-bit aligned"
off=$(( (addr - ROM_LO) / 8 ))
first=$("$DIS34" -b "$got" -s "$off" "$ROM" 2>/dev/null |
awk 'NF && $1 !~ /^L[0-9A-Fa-f]+:$/ { print tolower($1); exit }')
[ -n "$first" ] || fail "$name $got disassembled to nothing"
case " move mmtm setf cmp addi " in
*" $first "*) ;;
*) fail "$name $got starts with '$first', not a plausible function prologue" ;;
esac
echo " ok $name $got: $first ..."
}
check_sym XOpenDisplay 0x3F9C2570
check_sym XCreateSimpleWindow 0x3FD41B90
check_sym XMapWindow 0x3FD64F60
check_sym XSync 0x3FD9F6B0
echo "m3 validate-syms: PASS (four v2.2 Xlib entries in ROM, aligned, prologues valid)"
+43
View File
@@ -0,0 +1,43 @@
#ifndef VT1200_XLIB_H
#define VT1200_XLIB_H
typedef unsigned int XID;
typedef unsigned int Window;
/* ROM v2.2 layout (xhello.asm). TMS34010 indirect displacements are *bit*
offsets: xhello's `*a11(0480h)` / `*a10(040h)` are bit offsets 0x480/0x40,
which are byte offsets 0x90/0x8. Cross-checks: the classic 32-bit
Screen.root is at byte 8, and the Terminal Manager scales its screen index
by 0x280 = sizeof(Screen) (0x50 bytes) * 8. */
typedef struct {
unsigned char pad[0x90];
void *screens;
} Display;
typedef struct {
unsigned char pad[0x8];
unsigned int root;
} Screen;
extern Display *XOpenDisplay(const char *name);
extern Window XCreateSimpleWindow(Display *display, Window parent,
int x, int y, unsigned width,
unsigned height, unsigned border_width,
unsigned long border,
unsigned long background);
extern int XMapWindow(Display *display, Window window);
extern int XSync(Display *display, int discard);
/* clang is invoked at -O0 (the optimizer runs separately), which marks every
definition noinline. Keep this helper always-inline so layout.c and the
Xlib client do not each emit a local _vt1200_root for GSPA/GSPLNK to
collide on. */
static inline __attribute__((always_inline)) unsigned int
vt1200_root(Display *d) {
return ((Screen *)((Display *)d)->screens)->root;
}
int layout_screens(void);
int layout_root(void);
#endif
+23
View File
@@ -0,0 +1,23 @@
#include "vt1200_xlib.h"
/*
* XMapWindow maps with the true MapWindow entry (0x3FD64F60, request opcode
* 8), not 0x3FD645B0: that address is XRaiseWindow (ConfigureWindow opcode
* 12, CWStackMode=Above).
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
int xhello(void) {
Display *d = XOpenDisplay("0::0");
MARK(0) = (unsigned int)d;
if (!d)
return -1;
unsigned int root = vt1200_root(d);
MARK(1) = root;
Window w = XCreateSimpleWindow(d, root, 100, 100, 400, 200, 2, 0, 1);
MARK(2) = (unsigned int)w;
XMapWindow(d, w);
int s = XSync(d, 0);
MARK(3) = (unsigned int)s;
return (int)w;
}
+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())
+312
View File
@@ -0,0 +1,312 @@
#!/bin/sh
# M4 dis34 round-trip for the image/event client.
#
# scripts/m4/dis-roundtrip.sh
#
# Parses build/m4-xshow/m4.coff, disassembles its linked .text at 018A0000
# with dis34, and checks that GSPA encoded:
#
# - every ROM Xlib import as JAUC <bit address> (the v2.2 table);
# - the image client's direct calls: XOpenDisplay, XCreateSimpleWindow,
# XSelectInput, XCreateGC, XSetForeground, XCreatePixmap, XCreateImage,
# XSetErrorHandler, XMapWindow, XRaiseWindow, XSetInputFocus, XPutImage,
# XCopyArea, XFillRectangle, XSync, XPending, XNextEvent, XLookupString,
# XFlush, XGetInputFocus;
# - the ROM sleep through a function pointer (CALL Rs, encoded 0x0920), the
# Task 3 indirect-call contract;
# - the nine-argument XCreateSimpleWindow order 0,0,0,480,640,20,20,root,
# display (display pushed last);
# - the XSetErrorHandler callback pointer (MOVI _on_error);
# - SETF 16/32 after every call and the RETS/old-STK rules;
# - the 480x80-byte checker .bss and its word-fill loop.
#
# Overridable: M4_COFF M4_ASM DIS34
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
WORK=${M4_WORK:-$ROOT/build/m4-xshow}
COFF=${M4_COFF:-$WORK/m4.coff}
ASM=${M4_ASM:-$WORK/m4.asm}
LST=${M4_LST:-$WORK/m4.lst}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
fail() {
echo "M4 dis34 round-trip: FAIL: $*" >&2
exit 1
}
[ -f "$COFF" ] || fail "linked COFF not found: $COFF (run scripts/m4/run.sh)"
[ -f "$ASM" ] || fail "linked assembly not found: $ASM"
[ -f "$LST" ] || fail "GSPA listing not found: $LST"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/m4-dis34.XXXXXX")
FAIL_LOG=${M4_DIS_FAIL_LOG:-${TMPDIR:-/tmp}/m4-dis34-failure.txt}
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
read_u8s() { od -An -v -tu1 -j "$1" -N "$2" "$COFF"; }
u16() { read_u8s "$1" 2 | awk '{ print $1 + 256 * $2 }'; }
u32() { read_u8s "$1" 4 | awk '{ print $1 + 256 * $2 + 65536 * $3 + 16777216 * $4 }'; }
echo "== parse the COFF section table ($COFF)"
nscns=$(u16 2)
opthdr=$(u16 16)
[ "$nscns" -gt 0 ] 2>/dev/null || fail "COFF has no sections"
[ "$opthdr" -gt 0 ] 2>/dev/null || fail "COFF has no optional header"
TEXT_ADDR=; TEXT_BITS=; TEXT_PTR=
DATA_ADDR=; DATA_BITS=; DATA_PTR=
BSS_ADDR=; BSS_BITS=
sh_base=$((20 + opthdr))
i=0
while [ "$i" -lt "$nscns" ]; do
o=$((sh_base + i * 40))
name=$(dd if="$COFF" bs=1 skip="$o" count=8 2>/dev/null | tr -d '\000')
case "$name" in
.text) TEXT_ADDR=$(u32 $((o + 8))); TEXT_BITS=$(u32 $((o + 16))); TEXT_PTR=$(u32 $((o + 20))) ;;
.data) DATA_ADDR=$(u32 $((o + 8))); DATA_BITS=$(u32 $((o + 16))); DATA_PTR=$(u32 $((o + 20))) ;;
.bss) BSS_ADDR=$(u32 $((o + 8))); BSS_BITS=$(u32 $((o + 16))) ;;
esac
i=$((i + 1))
done
[ -n "$TEXT_ADDR" ] || fail "COFF has no .text section"
[ "$TEXT_BITS" -gt 0 ] 2>/dev/null || fail ".text is empty"
[ $((TEXT_BITS % 8)) -eq 0 ] || fail ".text size $TEXT_BITS bits is not whole bytes"
[ -n "$DATA_ADDR" ] || fail "COFF has no .data section"
[ -n "$BSS_ADDR" ] || fail "COFF has no .bss section"
[ "$BSS_BITS" -ge $((0x4B000)) ] 2>/dev/null \
|| fail ".bss is $BSS_BITS bits, too small for the 640x480 image (0x4B000 bits)"
TEXT_HEX=$(printf '%08X' "$TEXT_ADDR")
ENTRY=$(u32 $((20 + 16)))
ENTRY_HEX=$(printf '%08X' "$ENTRY")
TEXT_BYTES=$((TEXT_BITS / 8))
[ "$TEXT_HEX" = "018A0000" ] || fail ".text is linked at $TEXT_HEX, want 018A0000"
[ "$ENTRY_HEX" = "018A0000" ] || fail "COFF entry point is $ENTRY_HEX, want 018A0000"
BSS_HEX=$(printf '%08X' "$BSS_ADDR")
[ "$BSS_HEX" = "01A00000" ] || fail ".bss is at $BSS_HEX, want 01A00000"
echo " .text at $TEXT_HEX: $TEXT_BITS bits ($TEXT_BYTES bytes)"
echo " .data at $(printf '%08X' "$DATA_ADDR"): $DATA_BITS bits"
echo " .bss at $BSS_HEX: $BSS_BITS bits"
echo " entry point $ENTRY_HEX"
dd if="$COFF" of="$TMP/text.bin" bs=1 skip="$TEXT_PTR" count="$TEXT_BYTES" 2>/dev/null
[ "$(wc -c < "$TMP/text.bin")" -eq "$TEXT_BYTES" ] || fail "could not extract .text"
echo "== resolve linked symbols"
symptr=$(u32 8)
nsyms=$(u32 12)
[ "$nsyms" -gt 0 ] 2>/dev/null || fail "COFF has no symbol table"
sym_addr() {
_want=$1
_strtab=$((symptr + nsyms * 18))
_i=0
while [ "$_i" -lt "$nsyms" ]; do
_o=$((symptr + _i * 18))
if [ "$(u32 "$_o")" -eq 0 ]; then
_soff=$(u32 $((_o + 4)))
_n=$(dd if="$COFF" bs=1 skip=$((_strtab + _soff)) count=64 2>/dev/null |
tr '\000' '\n' | head -1)
else
_n=$(dd if="$COFF" bs=1 skip="$_o" count=8 2>/dev/null | tr -d '\000')
fi
if [ "$_n" = "$_want" ]; then
u32 $((_o + 8))
return 0
fi
_aux=$(od -An -v -tu1 -j $((_o + 17)) -N 1 "$COFF" | awk '{ print $1 }')
_i=$((_i + 1 + _aux))
done
return 1
}
get_sym() {
_a=$(sym_addr "$1") || fail "COFF symbol table has no $1"
printf '%s' "$_a"
}
XOPEN=$(get_sym _XOpenDisplay)
XCREATE=$(get_sym _XCreateSimpleWindow)
XSELECT=$(get_sym _XSelectInput)
XGC=$(get_sym _XCreateGC)
XSETFG=$(get_sym _XSetForeground)
XCPM=$(get_sym _XCreatePixmap)
XCI=$(get_sym _XCreateImage)
XERR=$(get_sym _XSetErrorHandler)
XMAP=$(get_sym _XMapWindow)
XRAISE=$(get_sym _XRaiseWindow)
XSETFOCUS=$(get_sym _XSetInputFocus)
XPUT=$(get_sym _XPutImage)
XCOPY=$(get_sym _XCopyArea)
XFILL=$(get_sym _XFillRectangle)
XSYNC=$(get_sym _XSync)
XPEND=$(get_sym _XPending)
XNEXT=$(get_sym _XNextEvent)
XLOOKUP=$(get_sym _XLookupString)
XFLUSH=$(get_sym _XFlush)
XGETFOCUS=$(get_sym _XGetInputFocus)
XSLEEP=$(get_sym _sleep)
XBLIT=$(get_sym _blit_copy)
XSHOW=$(get_sym _xshow)
echo "== disassemble the emitted .text with dis34"
"$DIS34" -b "$TEXT_HEX" -l -o "$TMP/text.bin" > "$TMP/dis34.txt" 2> "$TMP/dis34.err" \
|| { cat "$TMP/dis34.err" >&2; fail "dis34 failed"; }
[ -s "$TMP/dis34.txt" ] || fail "dis34 produced no output"
match_at() {
_file=$1; _addr=$2; _pat=$3
_laddr=$(printf '%08x' "$_addr")
grep -Eiq "^${_laddr}:[[:space:]]+${_pat}([[:space:]]*(;|$))" "$_file"
}
expect_at() {
_label=$1; _addr=$2; _want=$3; _pat=$4
_laddr=$(printf '%08x' "$_addr")
if match_at "$TMP/dis34.txt" "$_addr" "$_pat"; then
echo " ok $_label @ 0x$_laddr: $_want"
return 0
fi
{
echo "M4 dis34 round-trip: FAIL"
echo " $_label at bit 0x$_laddr: expected $_want"
awk -v a="$_laddr" '{ low=tolower($0) } low ~ ("^" a ":") { seen=1 } seen { print " " $0; n++ } seen && n>=4 { exit }' "$TMP/dis34.txt"
cp "$TMP/dis34.txt" "$FAIL_LOG" 2>/dev/null || true
} >&2
exit 1
}
echo "== check the ROM import stubs"
expect_at _XOpenDisplay "$XOPEN" "JAUC 3F9C2570" 'jauc[[:space:]]+0x3f9c2570'
expect_at _XCreateSimpleWindow "$XCREATE" "JAUC 3FD41B90" 'jauc[[:space:]]+0x3fd41b90'
expect_at _XSelectInput "$XSELECT" "JAUC 3FD97D50" 'jauc[[:space:]]+0x3fd97d50'
expect_at _XCreateGC "$XGC" "JAUC 3F997000" 'jauc[[:space:]]+0x3f997000'
expect_at _XSetForeground "$XSETFG" "JAUC 3FD99A60" 'jauc[[:space:]]+0x3fd99a60'
expect_at _XCreatePixmap "$XCPM" "JAUC 3FD416E0" 'jauc[[:space:]]+0x3fd416e0'
expect_at _XCreateImage "$XCI" "JAUC 3F9A0490" 'jauc[[:space:]]+0x3f9a0490'
expect_at _XSetErrorHandler "$XERR" "JAUC 3FD45700" 'jauc[[:space:]]+0x3fd45700'
expect_at _XMapWindow "$XMAP" "JAUC 3FD64F60" 'jauc[[:space:]]+0x3fd64f60'
expect_at _XRaiseWindow "$XRAISE" "JAUC 3FD645B0" 'jauc[[:space:]]+0x3fd645b0'
expect_at _XSetInputFocus "$XSETFOCUS" "JAUC 3FD536B0" 'jauc[[:space:]]+0x3fd536b0'
expect_at _XPutImage "$XPUT" "JAUC 3F9CEC70" 'jauc[[:space:]]+0x3f9cec70'
expect_at _XCopyArea "$XCOPY" "JAUC 3FD3E220" 'jauc[[:space:]]+0x3fd3e220'
expect_at _XFillRectangle "$XFILL" "JAUC 3F99E8F0" 'jauc[[:space:]]+0x3f99e8f0'
expect_at _XSync "$XSYNC" "JAUC 3FD9F6B0" 'jauc[[:space:]]+0x3fd9f6b0'
expect_at _XPending "$XPEND" "JAUC 3FD67620" 'jauc[[:space:]]+0x3fd67620'
expect_at _XNextEvent "$XNEXT" "JAUC 3F9C1CF0" 'jauc[[:space:]]+0x3f9c1cf0'
expect_at _XLookupString "$XLOOKUP" "JAUC 3F9A9C30" 'jauc[[:space:]]+0x3f9a9c30'
expect_at _XFlush "$XFLUSH" "JAUC 3F9B1030" 'jauc[[:space:]]+0x3f9b1030'
expect_at _XGetInputFocus "$XGETFOCUS" "JAUC 3FD55210" 'jauc[[:space:]]+0x3fd55210'
expect_at _sleep "$XSLEEP" "JAUC 3FB33A20" 'jauc[[:space:]]+0x3fb33a20'
expect_at _blit_copy "$XBLIT" "JAUC 3FB44400" 'jauc[[:space:]]+0x3fb44400'
echo "== check the compiled client calls (linked assembly keeps the names)"
for sym in XOpenDisplay XCreateSimpleWindow XSelectInput XCreateGC XSetForeground \
XCreatePixmap XCreateImage XSetErrorHandler XMapWindow XRaiseWindow \
XSetInputFocus XPutImage XCopyArea XFillRectangle XSync XPending \
XNextEvent XLookupString XFlush XGetInputFocus; do
grep -q "CALLA _${sym}" "$ASM" || fail "linked assembly has no CALLA _$sym"
done
echo " ok direct CALLA imports: 20 Xlib entries"
grep -Eq '^[[:space:]]*MOVI _on_error_[A-Za-z0-9_]+, A[0-9]+' "$ASM" \
|| fail "no MOVI _on_error before XSetErrorHandler"
echo " ok XSetErrorHandler callback pointer: MOVI _on_error…"
grep -Eq '^[[:space:]]*CALL A[0-9]+' "$ASM" \
|| fail "no indirect CALL (Task 3 CALL Rs) in the client"
echo " ok indirect sleep call: CALL A?"
grep -q 'CALLA _blit_copy' "$ASM" \
|| fail "linked assembly has no CALLA _blit_copy (ROM copy entry)"
echo " ok ROM blit_copy entry: CALLA _blit_copy (JAUC 3FB44400)"
# XCreateSimpleWindow argument order: push 0,0,0,480,640,20,20,root,display.
LN=$(grep -n 'CALLA _XCreateSimpleWindow' "$ASM" | head -1 | cut -d: -f1)
[ -n "$LN" ] || fail "linked assembly has no CALLA _XCreateSimpleWindow"
sed -n "$((LN - 24)),$((LN))p" "$ASM" > "$TMP/create.block"
awk '
/^[[:space:]]*MOVI[[:space:]]/ {
line=$0; sub(/.*MOVI[[:space:]]+/, "", line); sub(/[[:space:]]*;.*/, "", line);
split(line, p, /,[[:space:]]*/); gsub(/[[:space:]]/, "", p[1]); gsub(/[[:space:]]/, "", p[2]);
val[p[2]] = p[1]; next
}
/^[[:space:]]*MOVE[[:space:]]+A[0-9]+,[[:space:]]*\*A14\+,/ {
line=$0; sub(/.*MOVE[[:space:]]+/, "", line); sub(/,.*/, "", line);
v = val[line]; if (line == "A1") v = "root"; if (line == "A0") v = "display";
print v
}
' "$TMP/create.block" > "$TMP/create.vals"
printf '%s\n' 0 0 0 480 640 20 20 root display > "$TMP/create.want"
if ! cmp -s "$TMP/create.want" "$TMP/create.vals"; then
{
echo "M4 dis34 round-trip: FAIL: XCreateSimpleWindow argument order"
echo " expected (background,border,border_width,height,width,y,x,root,display):"
sed 's/^/ /' "$TMP/create.want"
echo " got:"
sed 's/^/ /' "$TMP/create.vals"
} >&2
exit 1
fi
echo " ok XCreateSimpleWindow order: 0,0,0,480,640,20,20,root,display (display last)"
# Every call must be followed by the SETF 16/32 pair. The hand-written
# _start trampoline (`calla _xshow` + rets) is not a compiler call and is
# checked separately; the scan starts at _xshow: so lower-case call spellings
# inside the compiler output are still matched.
grep -Eq '^[[:space:]]*calla[[:space:]]+_xshow' "$ASM" \
|| fail "entry.asm does not call _xshow"
awk '
{ low = tolower($0) }
/^_xshow:/ { on = 1 }
low ~ /^[[:space:]]*;/ { next }
!on { next }
expect == 1 {
if ($0 ~ /SETF 16, 1, 0/) { expect = 2 }
else { bad++; expect = 0 }
next
}
expect == 2 {
if ($0 ~ /SETF 32, 0, 1/) { ok++; expect = 0 }
else { bad++; expect = 0 }
next
}
low ~ /^[[:space:]]*(calla|call)[[:space:]]/ { calls++; expect = 1 }
END { printf "%d %d %d\n", calls + 0, ok + 0, bad + 0 }
' "$ASM" > "$TMP/setf.count"
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,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.
awk '/^_on_error_/ { on=1 } on { print } on && /rets[[:space:]]+2/ { exit }' "$ASM" > "$TMP/onerr.s"
grep -Eq 'MOVE \*SP\((0x80|128)\), A14, 1' "$TMP/onerr.s" \
|| { sed 's/^/ /' "$TMP/onerr.s" >&2; fail "on_error does not restore A14 from *SP(0x80/128)"; }
grep -Eq '^[[:space:]]*RETS 2' "$TMP/onerr.s" || fail "on_error has no RETS 2"
echo " ok on_error: 3 pushes -> *SP(0x80),A14 and RETS 2"
# Task 3 CALL encoding in the GSPA listing.
grep -Eq '^[[:space:]]*[0-9]+[[:space:]]+[0-9A-F]+[[:space:]]+0920[[:space:]]+CALL[[:space:]]+A[0-9]+' "$LST" \
|| fail "GSPA listing has no 0x0920 CALL A?"
echo " ok GSPA encoded the indirect call as 0x0920"
# dis34 must decode the indirect call as `call aN`.
grep -Eq '^[0-9a-f]+:[[:space:]]+call[[:space:]]+a[0-9]+' "$TMP/dis34.txt" \
|| fail "dis34 did not decode any CALL Rs as 'call aN'"
echo " ok dis34 decodes CALL Rs as 'call aN'"
# The checker data lives in .bss: 480*80 bytes, built as 32-bit words.
grep -Eq '\.bss[[:space:]]+_data_[A-Za-z0-9_]+,307200,32' "$ASM" \
|| fail "linked assembly has no .bss _data…,307200,32 (480*80 bytes)"
grep -Eq '^[[:space:]]*MOVI -1, A[0-9]+' "$ASM" \
|| fail "checker fill loop has no MOVI -1 (all-ones cell)"
grep -Eq '^[[:space:]]*NOT A[0-9]+' "$ASM" \
|| fail "checker fill loop has no NOT (all-zero cell)"
echo " ok checker .bss: 480*80 bytes, MOVI -1 / NOT cell fill"
# The client must actually set the XImage byte/bit order to LSBFirst. The
# layout gate pins data=16 (0x80), byte_order=20 (0xA0) and
# bitmap_bit_order=28 (0xE0); here the linked code stores zero at 0xA0/0xE0.
grep -Eq 'ADDI 160, A[0-9]+' "$ASM" || fail "no XImage.byte_order (bit 0xA0) store"
grep -Eq 'ADDI 224, A[0-9]+' "$ASM" || fail "no XImage.bitmap_bit_order (bit 0xE0) store"
echo " ok XImage byte_order/bitmap_bit_order stores (LSBFirst at 0xA0/0xE0)"
echo "M4 dis34 round-trip: PASS"
+17
View File
@@ -0,0 +1,17 @@
; entry.asm -- M4 entry, linked at bit 018A0000.
;
; Calls the compiled unsigned runtime test. Markers (0x20 bits apart):
; 018A8000 le(5,7) == 1
; 018A8020 ule(7,5) == 0 (unsigned <=)
; 018A8040 sum_le(10) == 55
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _unsigned_test
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+43
View File
@@ -0,0 +1,43 @@
-- fnptr-check.lua -- M4 function-pointer/indirect-call markers.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- Markers (0x20 bits apart):
-- 018A8000 apply(inc, 41) == 42
-- 018A8020 apply(vf, 41) == 42 (volatile local function pointer)
-- 018A8040 apply(g_fn, 43) == 42 (global function pointer = dec)
-- 018A8060 fnptr_test() == 42 (return value, stored by the entry)
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, 3 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format("M4: fnptr=%d fnptr_volatile=%d fnptr_global=%d fnptr_ret=%d",
m[0], m[1], m[2], m[3]))
local want = {42, 42, 42, 42}
local ok = true
for i = 0, 3 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M4 MAME: PASS")
else
print("M4 MAME: FAIL (want fnptr=42 fnptr_volatile=42 fnptr_global=42 fnptr_ret=42)")
end
end
end, "fnptr-check")
+17
View File
@@ -0,0 +1,17 @@
; fnptr-entry.asm -- M4 function-pointer/indirect-call test entry.
;
; Calls the function-pointer translation unit and stores its return value in
; marker 3. Markers live at 0x018A8000 + n*0x20 (bit addresses).
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _fnptr_test
movi 018A8060h, a0
move a8, *a0, 1
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+29
View File
@@ -0,0 +1,29 @@
/* fnptr.c -- M4 function-pointer/indirect-call runtime test.
*
* Markers live at 0x018A8000 + n*0x20 (bit addresses):
* 0 apply(inc, 41) == 42 direct symbol passed as a pointer
* 1 apply(vf, 41) == 42 volatile local function pointer
* 2 apply(g_fn, 43) == 42 global function pointer holding dec
* 3 fnptr_test() == 42 return value, stored by fnptr-entry.asm
*
* apply/inc/dec are noinline so -O2 cannot inline the helper and devirtualise
* the callback into a direct call; the call inside apply is a real `call i32
* %f` and lowers to CALL Rs.
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
typedef int (*fn)(int);
__attribute__((noinline)) int inc(int x) { return x + 1; }
__attribute__((noinline)) int dec(int x) { return x - 1; }
__attribute__((noinline)) int apply(fn f, int x) { return f(x); }
static fn volatile g_fn = dec;
int fnptr_test(void) {
volatile fn vf = inc;
MARK(0) = (unsigned)apply(inc, 41);
MARK(1) = (unsigned)apply(vf, 41);
MARK(2) = (unsigned)apply(g_fn, 43);
return apply(vf, 41);
}
+102
View File
@@ -0,0 +1,102 @@
/*
* Offset-only equivalent of scripts/m4/x11m4.h for the 1987 TI GSP C
* compiler (GSPCC/GSPCG 2.01). The VT1200 C ABI packs struct members, so
* these structs have the same byte layout as the target's x11m4.h. The
* XImage function table is modelled as six 32-bit void* slots: only its
* size and the offset of f are needed here, and that is layout-equivalent
* to the target's six function pointers.
*
* The 1987 compiler's &-of-member is a bit address, so these functions
* return the ROM's bit displacements directly.
*/
struct display {
char pad[0x90];
void *screens;
};
struct screen {
char pad[0x8];
unsigned int root;
};
struct ximage_funcs {
void *create_image;
void *destroy_image;
void *get_pixel;
void *put_pixel;
void *sub_image;
void *add_pixel;
};
struct ximage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask, green_mask, blue_mask;
void *obdata;
struct ximage_funcs f;
};
struct xerror {
int type;
void *display;
unsigned long resourceid;
unsigned long serial;
unsigned char error_code;
unsigned char request_code;
unsigned char minor_code;
unsigned char abi_pad;
};
struct xkey {
int type;
unsigned long serial;
int send_event;
void *display;
unsigned long window;
unsigned long root;
unsigned long subwindow;
unsigned long time;
int x, y;
int x_root, y_root;
unsigned int state;
unsigned int keycode;
int same_screen;
};
struct xexpose {
int type;
unsigned long serial;
int send_event;
void *display;
unsigned long window;
int x, y;
int width, height;
int count;
};
union xevent {
int type;
struct xkey xkey;
struct xexpose xexpose;
long pad[24];
};
int layout_display_screens() { return (int)&((struct display *)0)->screens; }
int layout_screen_root() { return (int)&((struct screen *)0)->root; }
int layout_image_data() { return (int)&((struct ximage *)0)->data; }
int layout_image_byte_order() { return (int)&((struct ximage *)0)->byte_order; }
int layout_image_bytes_per_line() { return (int)&((struct ximage *)0)->bytes_per_line; }
int layout_image_bits_per_pixel() { return (int)&((struct ximage *)0)->bits_per_pixel; }
int layout_image_f() { return (int)&((struct ximage *)0)->f; }
int layout_error_error_code() { return (int)&((struct xerror *)0)->error_code; }
int layout_event_xkey_keycode() { return (int)&((struct xevent *)0)->xkey.keycode; }
int layout_event_size() { return (int)sizeof(union xevent); }
+114
View File
@@ -0,0 +1,114 @@
*******************************************************
* GSP C COMPILER, Version 2.01, 87.300 *
*******************************************************
FP .set A13
STK .set A14
.globl _layout_display_screens
.file "LAYOUT.c"
******************************************************
* FUNCTION DEF : _layout_display_screens
******************************************************
_layout_display_screens:
MOVE A7,-*SP,1
MOVI 1152,A7
MOVE A7,A8
EPI0_1:
MOVE *SP+,A7,1
RETS 0
.globl _layout_screen_root
******************************************************
* FUNCTION DEF : _layout_screen_root
******************************************************
_layout_screen_root:
MOVE A7,-*SP,1
MOVI 64,A7
MOVE A7,A8
EPI0_2:
MOVE *SP+,A7,1
RETS 0
.globl _layout_image_data
******************************************************
* FUNCTION DEF : _layout_image_data
******************************************************
_layout_image_data:
MOVE A7,-*SP,1
MOVI 128,A7
MOVE A7,A8
EPI0_3:
MOVE *SP+,A7,1
RETS 0
.globl _layout_image_byte_order
******************************************************
* FUNCTION DEF : _layout_image_byte_order
******************************************************
_layout_image_byte_order:
MOVE A7,-*SP,1
MOVI 160,A7
MOVE A7,A8
EPI0_4:
MOVE *SP+,A7,1
RETS 0
.globl _layout_image_bytes_per_line
******************************************************
* FUNCTION DEF : _layout_image_bytes_per_line
******************************************************
_layout_image_bytes_per_line:
MOVE A7,-*SP,1
MOVI 320,A7
MOVE A7,A8
EPI0_5:
MOVE *SP+,A7,1
RETS 0
.globl _layout_image_bits_per_pixel
******************************************************
* FUNCTION DEF : _layout_image_bits_per_pixel
******************************************************
_layout_image_bits_per_pixel:
MOVE A7,-*SP,1
MOVI 352,A7
MOVE A7,A8
EPI0_6:
MOVE *SP+,A7,1
RETS 0
.globl _layout_image_f
******************************************************
* FUNCTION DEF : _layout_image_f
******************************************************
_layout_image_f:
MOVE A7,-*SP,1
MOVI 512,A7
MOVE A7,A8
EPI0_7:
MOVE *SP+,A7,1
RETS 0
.globl _layout_error_error_code
******************************************************
* FUNCTION DEF : _layout_error_error_code
******************************************************
_layout_error_error_code:
MOVE A7,-*SP,1
MOVI 128,A7
MOVE A7,A8
EPI0_8:
MOVE *SP+,A7,1
RETS 0
.globl _layout_event_xkey_keycode
******************************************************
* FUNCTION DEF : _layout_event_xkey_keycode
******************************************************
_layout_event_xkey_keycode:
MOVE A7,-*SP,1
MOVI 416,A7
MOVE A7,A8
EPI0_9:
MOVE *SP+,A7,1
RETS 0
.globl _layout_event_size
******************************************************
* FUNCTION DEF : _layout_event_size
******************************************************
_layout_event_size:
MOVI 96,A8
EPI0_10:
RETS 0
.end
+120
View File
@@ -0,0 +1,120 @@
#include "x11m4.h"
/*
* Byte offsets are C offsets; the TMS34010 ROM's indirect displacements are
* bit offsets, so every layout_* function below returns offset * 8. The one
* exception is layout_event_size(), which reports sizeof(XEvent) in bytes
* because the termtris buffer is sized in bytes (vt_u32 evbuf[24]).
*/
_Static_assert(sizeof(void *) == 4, "the VT1200 X11 ABI is 32-bit");
_Static_assert(sizeof(long) == 4, "the VT1200 X11 ABI is 32-bit");
_Static_assert(sizeof(XID) == 4, "XID must be 32-bit");
_Static_assert(sizeof(Time) == 4, "Time must be 32-bit");
_Static_assert(__builtin_offsetof(Display, screens) == 0x90,
"Display.screens must be at byte 0x90 (bit 0x480)");
_Static_assert(__builtin_offsetof(Screen, root) == 0x8,
"Screen.root must be at byte 0x8 (bit 0x40)");
/* 32-bit X11R4 XImage: data 16, byte_order 20, bytes_per_line 40. */
_Static_assert(__builtin_offsetof(XImage, width) == 0, "XImage.width");
_Static_assert(__builtin_offsetof(XImage, height) == 4, "XImage.height");
_Static_assert(__builtin_offsetof(XImage, xoffset) == 8, "XImage.xoffset");
_Static_assert(__builtin_offsetof(XImage, format) == 12, "XImage.format");
_Static_assert(__builtin_offsetof(XImage, data) == 16,
"XImage.data must be at byte 16 (bit 0x80)");
_Static_assert(__builtin_offsetof(XImage, byte_order) == 20,
"XImage.byte_order must be at byte 20 (bit 0xA0)");
_Static_assert(__builtin_offsetof(XImage, bitmap_unit) == 24, "XImage.bitmap_unit");
_Static_assert(__builtin_offsetof(XImage, bitmap_bit_order) == 28,
"XImage.bitmap_bit_order");
_Static_assert(__builtin_offsetof(XImage, bitmap_pad) == 32, "XImage.bitmap_pad");
_Static_assert(__builtin_offsetof(XImage, depth) == 36, "XImage.depth");
_Static_assert(__builtin_offsetof(XImage, bytes_per_line) == 40,
"XImage.bytes_per_line must be at byte 40 (bit 0x140)");
_Static_assert(__builtin_offsetof(XImage, bits_per_pixel) == 44,
"XImage.bits_per_pixel must be at byte 44 (bit 0x160)");
_Static_assert(__builtin_offsetof(XImage, red_mask) == 48, "XImage.red_mask");
_Static_assert(__builtin_offsetof(XImage, green_mask) == 52, "XImage.green_mask");
_Static_assert(__builtin_offsetof(XImage, blue_mask) == 56, "XImage.blue_mask");
_Static_assert(__builtin_offsetof(XImage, obdata) == 60, "XImage.obdata");
_Static_assert(__builtin_offsetof(XImage, f) == 64,
"XImage.f must be at byte 64 (bit 0x200)");
_Static_assert(__builtin_offsetof(struct funcs, destroy_image) == 4,
"XImage.f.destroy_image must be 4 bytes into the inline funcs");
_Static_assert(__builtin_offsetof(XImage, f.destroy_image) == 68,
"XImage.f.destroy_image must be at byte 68 (bit 0x220)");
_Static_assert(sizeof(struct funcs) == 24, "the X11R4 funcs tail is six pointers");
_Static_assert(sizeof(XImage) == 88,
"sizeof(XImage) must cover the ROM's full inline-funcs object");
/* 32-bit X11R4 XErrorEvent: error_code 16, request_code 17, minor_code 18. */
_Static_assert(__builtin_offsetof(XErrorEvent, type) == 0, "XErrorEvent.type");
_Static_assert(__builtin_offsetof(XErrorEvent, display) == 4, "XErrorEvent.display");
_Static_assert(__builtin_offsetof(XErrorEvent, resourceid) == 8,
"XErrorEvent.resourceid");
_Static_assert(__builtin_offsetof(XErrorEvent, serial) == 12, "XErrorEvent.serial");
_Static_assert(__builtin_offsetof(XErrorEvent, error_code) == 16,
"XErrorEvent.error_code must be at byte 16 (bit 0x80)");
_Static_assert(__builtin_offsetof(XErrorEvent, request_code) == 17,
"XErrorEvent.request_code");
_Static_assert(__builtin_offsetof(XErrorEvent, minor_code) == 18,
"XErrorEvent.minor_code");
/* The packed object would be 19 bytes; one X11R4 object-size compatibility
* pad byte keeps the 32-bit object at 20. The client reads only the
* handler-passed fields. */
_Static_assert(sizeof(XErrorEvent) == 20, "sizeof(XErrorEvent) must be 20");
/* XEvent: type 0, xkey.window 16, xkey.keycode 52, xexpose.window 16, x 20. */
_Static_assert(__builtin_offsetof(XEvent, type) == 0, "XEvent.type");
_Static_assert(__builtin_offsetof(XEvent, xkey.window) == 16, "XEvent.xkey.window");
_Static_assert(__builtin_offsetof(XEvent, xkey.keycode) == 52,
"XEvent.xkey.keycode must be at byte 52 (bit 0x1A0)");
_Static_assert(__builtin_offsetof(XEvent, xexpose.window) == 16,
"XEvent.xexpose.window");
_Static_assert(__builtin_offsetof(XEvent, xexpose.x) == 20, "XEvent.xexpose.x");
_Static_assert(__builtin_offsetof(XEvent, xfocus.window) == 16,
"XEvent.xfocus.window");
_Static_assert(__builtin_offsetof(XEvent, xbutton.window) == 16,
"XEvent.xbutton.window");
_Static_assert(__builtin_offsetof(XEvent, xconfigure.window) == 20,
"XEvent.xconfigure.window");
_Static_assert(__builtin_offsetof(XEvent, xclient.window) == 16,
"XEvent.xclient.window");
_Static_assert(sizeof(XEvent) >= 96,
"XEvent must cover the termtris 96-byte vt_u32 evbuf[24]");
_Static_assert(sizeof(XEvent) == 96, "the X11R4 XEvent union is 96 bytes");
int layout_display_screens(void) {
return (int)__builtin_offsetof(Display, screens) * 8;
}
int layout_screen_root(void) {
return (int)__builtin_offsetof(Screen, root) * 8;
}
int layout_image_data(void) {
return (int)__builtin_offsetof(XImage, data) * 8;
}
int layout_image_byte_order(void) {
return (int)__builtin_offsetof(XImage, byte_order) * 8;
}
int layout_image_bytes_per_line(void) {
return (int)__builtin_offsetof(XImage, bytes_per_line) * 8;
}
int layout_image_bits_per_pixel(void) {
return (int)__builtin_offsetof(XImage, bits_per_pixel) * 8;
}
int layout_image_f(void) {
return (int)__builtin_offsetof(XImage, f) * 8;
}
int layout_error_error_code(void) {
return (int)__builtin_offsetof(XErrorEvent, error_code) * 8;
}
int layout_event_xkey_keycode(void) {
return (int)__builtin_offsetof(XEvent, xkey.keycode) * 8;
}
int layout_event_size(void) {
return (int)sizeof(XEvent);
}
/* Exercise the real access path: follows Display.screens and reads Screen.root. */
unsigned int root_probe(Display *d) { return vt_root(d); }
+16
View File
@@ -0,0 +1,16 @@
-a
-o M4.OUT
-m M4.MAP
-e _start
M4.obj
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+30
View File
@@ -0,0 +1,30 @@
/* m4 loop.c -- an ordinary -O2 loop test. The driver wrapper disables
* IndVarSimplify's exit-value replacement (-replexitval=never): this target has
* no i64, and the closed form of sumto turns into an i33 multiply that llc
* cannot select. The loops themselves must survive and run.
*
* Markers (0x20 bits apart, written by loop_test):
* 018A8100 sumto(10) == 55
* 018A8120 squares(5) == 30
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n)*0x20u))
int sumto(int n) {
int s = 0, i;
for (i = 1; i <= n; i++)
s += i;
return s;
}
int squares(int n) {
int s = 0, i;
for (i = 0; i < n; i++)
s += i * i;
return s;
}
int loop_test(void) {
MARK(8) = (unsigned)sumto(10);
MARK(9) = (unsigned)squares(5);
return 0;
}
+52
View File
@@ -0,0 +1,52 @@
-- m4-check.lua -- load the M4 COFF with dwt/loader/loader.lua and read the
-- marker words written by unsigned.c.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
-- Markers (0x20 bits apart):
-- 018A8000 le(5,7) == 1
-- 018A8020 ule(7,5) == 0 (unsigned <=)
-- 018A8040 sum_le(10) == 55
-- 018A8060 ge(7,5) == 1 (signed >=)
-- 018A8080 uge(5,7) == 0 (unsigned >=)
-- 018A80A0 gt(5,7) == 0 (signed >)
-- 018A80C0 ugt(7,5) == 1 (unsigned >)
-- 018A80E0 ne(7,5) == 1
-- 018A8100 lt(7,5) == 0 (signed <)
-- 018A8120 ult(5,7) == 1 (unsigned <)
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, 9 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M4: le=%d ule=%d sum_le=%d ge=%d uge=%d gt=%d ugt=%d ne=%d lt=%d ult=%d",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9]))
local want = {1, 0, 55, 1, 0, 0, 1, 1, 0, 1}
local ok = true
for i = 0, 9 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M4 MAME: PASS")
else
print("M4 MAME: FAIL (want le=1 ule=0 sum_le=55 ge=1 uge=0 gt=0 ugt=1 ne=1 lt=0 ult=1)")
end
end
end, "m4-check")
+54
View File
@@ -0,0 +1,54 @@
-- mul-check.lua -- M4 multiply/divide and -O2 loop markers.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- Markers (0x20 bits apart):
-- 018A8000 mul(6,7) == 42
-- 018A8020 umul16(0xffff,0xffff) == 0xfffe0001
-- 018A8040 sdiv(100,7) == 14
-- 018A8060 udiv(0xfffffffe,7) == 613566756
-- 018A8080 srem(100,7) == 2
-- 018A80A0 urem(100,7) == 2
-- 018A80C0 sdiv(-100,7) == -14
-- 018A80E0 srem(-100,7) == -2
-- 018A8100 sumto(10) == 55
-- 018A8120 squares(5) == 30
-- 018A8140 mul(0x12345678,0x9abcdef0) == 0x242d2080
-- 018A8160 urem(0xfffffffe,7) == 2
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, 11 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M4: mul=%d umul16=%d sdiv=%d udiv=%d srem=%d urem=%d sdivneg=%d sremneg=%d sumto=%d squares=%d widemul=%d widerem=%d",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
m[10], m[11]))
local want = {42, 0xfffe0001, 14, 613566756, 2, 2,
0xfffffff2, 0xfffffffe, 55, 30, 0x242d2080, 2}
local ok = true
for i = 0, 11 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M4 MAME: PASS")
else
print("M4 MAME: FAIL (want mul=42 umul16=4294836225 sdiv=14 udiv=613566756 srem=2 urem=2 sdivneg=-14 sremneg=-2 sumto=55 squares=30 widemul=606937216 widerem=2)")
end
end
end, "mul-check")
+16
View File
@@ -0,0 +1,16 @@
; mul-entry.asm -- M4 multiply/divide and -O2 loop test entry.
;
; Calls the multiply/divide and loop translation units. Markers written by
; mul.c and loop.c live at 0x018A8000 + n*0x20.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _mul_test
calla _loop_test
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+49
View File
@@ -0,0 +1,49 @@
/* m4 mul.c -- 32-bit multiply/divide marker test.
*
* Markers (0x20 bits apart, written by mul_test):
* 018A8000 mul(6,7) == 42
* 018A8020 umul16(0xffff,0xffff) == 0xfffe0001 (16x16 MPYU path)
* 018A8040 sdiv(100,7) == 14
* 018A8060 udiv(0xfffffffe,7) == 613566756
* 018A8080 srem(100,7) == 2
* 018A80A0 urem(100,7) == 2
* 018A80C0 sdiv(-100,7) == -14
* 018A80E0 srem(-100,7) == -2
* 018A8140 mulu(0x12345678,0x9ABCDEF0) == 0x242D2080 (wide 32x32 product)
* 018A8160 urem(0xfffffffe,7) == 2 (wide quotient in the remainder)
*/
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n)*0x20u))
int mul(int a, int b) { return a * b; }
/* A full-width unsigned product. The 32x32 low bits are identical for signed
* and unsigned values, so the target selects the same MPYS; using unsigned
* operands keeps a wide marker from being signed-overflow UB. */
unsigned mulu(unsigned a, unsigned b) { return a * b; }
/* A 16x16 unsigned product: both operands are masked to 16 bits, which is the
* form the target selects to MPYU. The product must be computed in unsigned
* arithmetic: 0xffff * 0xffff does not fit in signed int, so `int * int` would
* be signed overflow and the optimizer could narrow or rename the result. */
int umul16(int a, int b) {
return (int)((unsigned)(a & 0xffff) * (unsigned)(b & 0xffff));
}
int sdiv(int a, int b) { return a / b; }
unsigned udiv(unsigned a, unsigned b) { return a / b; }
int srem(int a, int b) { return a % b; }
unsigned urem(unsigned a, unsigned b) { return a % b; }
int mul_test(void) {
MARK(0) = (unsigned)mul(6, 7);
MARK(1) = (unsigned)umul16(0xffff, 0xffff);
MARK(2) = (unsigned)sdiv(100, 7);
MARK(3) = udiv(0xfffffffeu, 7u);
MARK(4) = (unsigned)srem(100, 7);
MARK(5) = urem(100u, 7u);
MARK(6) = (unsigned)sdiv(-100, 7);
MARK(7) = (unsigned)srem(-100, 7);
MARK(10) = mulu(0x12345678u, 0x9ABCDEF0u);
MARK(11) = urem(0xfffffffeu, 7u);
return 0;
}
+1
View File
@@ -0,0 +1 @@
char *a(void) { return "same"; }
+1
View File
@@ -0,0 +1 @@
char *b(void) { return "same"; }
+16
View File
@@ -0,0 +1,16 @@
; private-entry.asm -- M4 two-TU private-symbol link test entry.
;
; Calls both translation units so the linker keeps their functions and the
; string literals that those functions reference.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _a
calla _b
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+454
View File
@@ -0,0 +1,454 @@
#!/bin/sh
# M4 end-to-end runner: compile translation units, assemble/link with the 1987
# GSPA/GSPLNK toolchain under DOSBox, load the COFF in MAME, and evaluate the
# marker Lua script.
#
# scripts/m4/run.sh
#
# The default is unsigned.c at -O0, linked with entry.asm and checked by
# m4-check.lua. Other M4 tasks can reuse this runner:
#
# M4_SOURCES="foo bar" C basenames under scripts/m4 (default: unsigned)
# M4_ENTRY=/path/entry.asm assembly entry file (default: scripts/m4/entry.asm)
# M4_CHECK_LUA=/path.lua MAME marker script (default: scripts/m4/m4-check.lua)
# M4_CLANG_OPT=-O2 tms-clang optimization level (default: -O0)
# 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 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)
DIR=$ROOT/scripts/m4
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
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}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${M4_WORK:-$ROOT/build/m4}
COFF=${M4_COFF:-$WORK/m4.coff}
SDK=${M4_SDK:-$ROOT/build/m4-sdk}
ASM=$WORK/asm
LOADER_LUA=$ROOT/vendor/vt1200/dwt/loader/loader.lua
LOADER_BIN=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
LOADER_AT=${LOADER_AT:-2500}
LOADER_END=${LOADER_END:-2700}
SYMS=${M4_SYMS:-$ROOT/symbols/vt1200-v22.syms}
SOURCES=${M4_SOURCES:-unsigned}
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
exit 1
}
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"
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
case $name in
*/*) src=$name ;;
*) src=$DIR/$name.c ;;
esac
base=$(basename "$src" .c)
[ -f "$src" ] || fail "missing source: $src"
# 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"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE not extracted into $SDK"
# .bss is placed at 0x01A00000 (link.cmd). The 640x480 1-bit image is
# 38400 bytes; with the 4 KiB C stack and 1 KiB XG block it cannot fit the old
# 32 KiB region at 0x018A9000. 0x01A00000 is the region the termtris loader
# uses for its 125984-bit .bss (termtris.map 0x01A00000..0x01A1EC20), while the
# X server's request buffer lives in low RAM (0x00988FD0..0x0098CFD0).
echo "== assemble and link with GSPA/GSPLNK under DOSBox"
# GSPA 2.00 has one flat symbol table per assembly, and llc names basic blocks
# 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.
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"
EXTRAS="$EXTRAS $extra"
done
fi
if [ -n "${M4_ROM_SYMBOLS:-}" ]; then
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
rm -f "$SDK/M4.OBJ" "$SDK/M4.OUT" "$SDK/M4.MAP" "$SDK/M4.LST"
rm -f "$SDK/M4EXT.OBJ" "$SDK/M4EXT.LST"
run_dosbox() {
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf "$@" > "$WORK/dosbox.log" 2>&1
}
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
echo "M4 LINK: PASS"
exit 0
fi
echo "== run the COFF in MAME"
[ -x "$MAME" ] || fail "MAME binary not built: $MAME"
[ -f "$LOADER_LUA" ] || fail "COFF loader missing: $LOADER_LUA"
[ -f "$LOADER_BIN" ] || fail "COFF loader payload missing: $LOADER_BIN"
[ -f "$CHECK_LUA" ] || fail "marker Lua missing: $CHECK_LUA"
rm -rf "$WORK/run/nvram"
mkdir -p "$WORK/run/nvram"
VT1200_MONITOR=VR319 \
VT1200_SKIP_LEVEL1=1 \
LOADER_AT="$LOADER_AT" LOADER_END="$LOADER_END" \
LOADER_BIN="$LOADER_BIN" LOADER_COFF="$COFF" \
LOADER_OUT="$WORK/evidence" \
M4_LOADER_LUA="$LOADER_LUA" \
timeout "${MAME_TIMEOUT:-900}" "$MAME" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$CHECK_LUA" -autoboot_delay 0 \
> "$WORK/mame.log" 2>&1 \
|| { tail -30 "$WORK/mame.log" >&2; fail "MAME run failed"; }
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 -qE '^M[47] MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
case "$MARKERS" in
M7:*) echo "M7 MAME: PASS" ;;
*) echo "M4 MAME: PASS" ;;
esac
+37
View File
@@ -0,0 +1,37 @@
/*
* switch.c -- a dense char switch, used by tests/m4/termtris.sh to pin the
* driver's late-GEP policy.
*
* The optimizer's switch-to-lookup-table transform creates a new i8 GEP after
* 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)
{
switch(c) {
case '#': return 2;
case '.': return 1;
case '{': return 11;
case '}': return 12;
case '[': return 13;
case ']': return 14;
case '>': return 15;
case '<': return 16;
case '-': return 17;
case '(': return 18;
case ')': return 19;
default: return 0;
}
}
int sw_sum(const char *s)
{
int r = 0;
while(*s) {
r += sw_tile(*s++);
}
return r;
}
+226
View File
@@ -0,0 +1,226 @@
#!/bin/sh
# build.sh -- build the pinned termtris COFF with this compiler (tms-clang +
# llc), then assemble/link with the TI GSPA/GSPLNK toolchain.
#
# scripts/m4/termtris/build.sh
#
# Inputs: the test-only pinned checkout vendor/vt1200-termtris (branch
# `termtris`, commit be5b323...). Output: build/m4-termtris/termtris.coff and
# termtris.map, plus the generated TERMTRIS.ASM/LST for the dis34-style checks.
#
# Overridable: VT1200_TERMTRIS TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC
# TERMTRIS_WORK TERMTRIS_SDK DOSBOX DOSBOX_CONF SDK_IMG
# TERMTRIS_CC_OPT TERMTRIS_LLC_OPT
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m4/termtris
VENDOR=${VT1200_TERMTRIS:-$ROOT/vendor/vt1200-termtris}
SRC=$VENDOR/apps/termtris/src
ENTRY_SRC=$SRC/vt1200
LLVM_BIN=${LLVM_BIN:-$ROOT/build/llvm-clean-build/bin}
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}
MAME=${MAME:-$ROOT/build/mame-src/vt1200}
DOSBOX=${DOSBOX:-dosbox}
DOSBOX_CONF=${DOSBOX_CONF:-$ROOT/vendor/vt1200/harness/sdk-scratch/dosbox-bench.conf}
SDK_IMG=${SDK_IMG:-$ROOT/vendor/vt1200/tools/tms34010-sdk/1987-05 TMS34010 SDK/1987-11-06 TMS34010 Simulator-C Tools-ASM Tools.img}
WORK=${TERMTRIS_WORK:-$ROOT/build/m4-termtris}
SDK=${TERMTRIS_SDK:-$ROOT/build/m4-termtris-sdk}
ASM=$WORK/asm
CC_OPT=${TERMTRIS_CC_OPT:--O2}
LLC_OPT=${TERMTRIS_LLC_OPT:--O0}
SOURCES="main game scoredb x11 compat xgfix"
fail() {
echo "termtris build: $*" >&2
exit 1
}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
[ -d "$SRC" ] || fail "missing pinned termtris source: $SRC"
# The pinned commit matters: a newer branch may have moved the DIAG markers or
# changed the game loop. Fail loudly rather than silently test another tree.
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 the pinned be5b323f5d2cc4f7a7d25e7143c67bd9828ccbdf"
fi
mkdir -p "$ASM" "$WORK"
echo "== compile the pinned sources with this compiler ($CC_OPT) and llc ($LLC_OPT)"
export TMS_CLANG TMS_OPT TMS_BITADDR
# -I order: quoted game headers, then the vt1200 shims (stdio.h/inttypes.h),
# then the small local shims for stdlib/string/time. tms-clang passes
# -nostdinc, so every angle-bracket header must resolve here.
INCLUDES="-I $SRC -I $SRC/vt1200 -I $DIR/include"
for name in $SOURCES; do
case $name in
game) src=$SRC/game.c ;;
main|x11|compat|xgfix) src=$SRC/vt1200/$name.c ;;
scoredb) src=$SRC/vt1200/scoredb.c ;;
*) fail "unknown source $name" ;;
esac
[ -f "$src" ] || fail "missing source: $src"
# shellcheck disable=SC2086
"$ROOT/scripts/tms-clang" "$CC_OPT" $INCLUDES -o "$ASM/$name.ll" "$src" \
|| fail "tms-clang failed for $src"
"$TMS_LLC" -march=tms34010 "$LLC_OPT" -filetype=asm \
"$ASM/$name.ll" -o "$ASM/$name.s" \
|| fail "llc failed for $src"
echo " $name.s: $(grep -c . "$ASM/$name.s") lines"
done
echo "== extract the TI 1987 SDK"
if [ ! -f "$SDK/GSPA.EXE" ]; then
command -v mcopy >/dev/null 2>&1 || fail "mtools (mcopy) is required"
[ -f "$SDK_IMG" ] || fail "SDK image not found: $SDK_IMG"
mkdir -p "$SDK"
mcopy -s -n -i "$SDK_IMG" "::/A2/*" "$SDK/"
mcopy -s -n -i "$SDK_IMG" "::/C2/*" "$SDK/"
fi
[ -f "$SDK/GSPA.EXE" ] || fail "GSPA.EXE not extracted into $SDK"
[ -f "$SDK/RTS.LIB" ] || fail "RTS.LIB not extracted into $SDK"
# GSPA has one flat symbol table per assembly, and llc restarts LBB0_1 in every
# translation unit. Give each TU its own LBB prefix (the M4 run.sh pattern).
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
# The body (entry, code, libc) without the .cinit member: the linker takes the
# empty CINIT.asm first, and the caller relinks with CINITZ.asm when the map
# says .cinit is empty.
# The vendored entry/cinit files end with `.end`, which stops GSPA at that
# point when the pieces are concatenated into one assembly (the vendored
# build assembles each file separately). Drop the terminator; GSPA's own
# `.end` is appended by the cinit member.
strip_end() {
sed '/^[[:space:]]*\.end[[:space:]]*$/d' "$1"
}
: > "$WORK/code.asm"
strip_end "$ENTRY_SRC/entry.asm" >> "$WORK/code.asm"
for name in $SOURCES; do
cat "$ASM/$name.unique.s" >> "$WORK/code.asm"
done
# GSPA needs an explicit `.globl` declaration for a symbol the linker will
# resolve from another object (rts.lib); llc prints the call/reference but no
# declaration. Collect the CALLA/MOVI references and declare the ones this
# assembly does not define itself.
sed -n \
-e 's/.*CALLA[[:space:]]*\(_[A-Za-z0-9_][A-Za-z0-9_]*\).*/\1/p' \
-e 's/.*MOVI[[:space:]]*\(_[A-Za-z0-9_][A-Za-z0-9_]*\).*/\1/p' \
"$WORK/code.asm" | sort -u > "$WORK/refs.txt"
sed -n 's/^\(_[A-Za-z0-9_][A-Za-z0-9_]*\):.*/\1/p' "$WORK/code.asm" \
| sort -u > "$WORK/defs.txt"
: > "$WORK/externs.asm"
while read -r sym; do
[ -n "$sym" ] || continue
grep -qxF "$sym" "$WORK/defs.txt" || printf '\t.globl\t%s\n' "$sym" >> "$WORK/externs.asm"
done < "$WORK/refs.txt"
: > "$WORK/body.asm"
cat "$WORK/externs.asm" "$WORK/code.asm" > "$WORK/body.asm"
strip_end "$ENTRY_SRC/cinit.asm" > "$WORK/cinit.asm"
strip_end "$ENTRY_SRC/cinitz.asm" > "$WORK/cinitz.asm"
# The link command file must keep CRLF line endings for the DOS tool.
write_cmd() {
{
printf '%s\n' '-a'
printf '%s\n' '-o TERMTRIS.OUT'
printf '%s\n' '-m TERMTRIS.MAP'
printf '%s\n' '-e _start'
printf '%s\n' 'TERMTRIS.obj'
printf '%s\n' '-l rts.lib'
printf '%s\n' 'MEMORY'
printf '%s\n' '{'
# The vintage r5.01 build's text+data is 10.6+0.6 KiB and fits the
# 20000h-bit program region. This compiler's -O2/llc -O0 output is
# about twice as large (see the report), so the program region is
# widened to 40000h bits (32 KiB). It ends at 018E0000, below the
# loader's COFF buffer at 01900000 and the .bss region at 01A00000.
printf '%s\n' ' prog: origin = 018A0000h, length = 40000h'
printf '%s\n' ' ram: origin = 01A00000h, length = 40000h'
printf '%s\n' '}'
printf '%s\n' 'SECTIONS'
printf '%s\n' '{'
printf '%s\n' ' .text: {} > prog'
printf '%s\n' ' .data: {} > prog'
printf '%s\n' ' .cinit: {} > prog'
printf '%s\n' ' .bss: {} > ram'
printf '%s\n' '}'
} > "$WORK/termtris.cmd"
sed 's/$/\r/' "$WORK/termtris.cmd" > "$SDK/TERMTRIS.CMD"
}
assemble_link() {
cinit=$1
cat "$WORK/body.asm" "$WORK/$cinit" > "$SDK/TERMTRIS.ASM"
rm -f "$SDK/TERMTRIS.OBJ" "$SDK/TERMTRIS.LST" \
"$SDK/TERMTRIS.OUT" "$SDK/TERMTRIS.MAP"
write_cmd
SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
timeout "${DOSBOX_TIMEOUT:-300}" "$DOSBOX" -conf "$DOSBOX_CONF" \
-noprimaryconf -nolocalconf \
-c "mount c $SDK" -c "c:" \
-c "gspa TERMTRIS TERMTRIS.obj TERMTRIS.lst -l" \
-c "gsplnk TERMTRIS.cmd" \
-c "exit" -exit > "$WORK/dosbox.log" 2>&1 \
|| { tail -30 "$WORK/dosbox.log" >&2; fail "DOSBox failed ($cinit)"; }
[ -f "$SDK/TERMTRIS.LST" ] || fail "GSPA produced no listing (see $WORK/dosbox.log)"
sed 's/\r$//' "$SDK/TERMTRIS.LST" > "$WORK/termtris.lst"
grep -q 'No Errors' "$WORK/termtris.lst" \
|| { grep -i -B2 -A2 'error' "$WORK/termtris.lst" >&2 || true; \
fail "GSPA reported an error"; }
# GSPA's symbol table caps names at 31 characters. llc's path-hashed
# static/switch-table names can exceed that; the truncation is consistent
# between definition and reference and the map below is checked for
# duplicates. Any other warning is fatal.
nwarn=$(grep -c 'WARNING' "$WORK/termtris.lst" || true)
ntrunc=$(grep -c 'WARNING - SYMBOL TRUNCATED' "$WORK/termtris.lst" || true)
if [ "$nwarn" -ne "$ntrunc" ]; then
grep -i -B2 -A2 'warning' "$WORK/termtris.lst" >&2 || true
fail "GSPA reported a non-truncation warning"
fi
[ "$nwarn" -eq 0 ] || echo " GSPA: $nwarn long symbol name(s) truncated to 31 chars"
[ -f "$SDK/TERMTRIS.OUT" ] || fail "GSPLNK produced no TERMTRIS.OUT"
sed 's/\r$//' "$SDK/TERMTRIS.MAP" > "$WORK/termtris.map"
}
echo "== assemble and link with GSPA/GSPLNK under DOSBox"
assemble_link cinit.asm
CSIZE=$(awk '$1 == ".cinit" {print $4; exit}' "$WORK/termtris.map")
if [ "$CSIZE" = "00000000" ]; then
# An empty .cinit makes the linker point `cinit` at .text; the entry's
# walker would read an instruction as a record count. Relink with the
# one-word terminator, exactly as the vendored build.sh does.
echo " .cinit is empty; relinking with the CINITZ terminator"
assemble_link cinitz.asm
fi
ENTRY_ADDR=$(awk '$2 == "_start" { print $1; exit }' "$WORK/termtris.map")
[ -n "$ENTRY_ADDR" ] || fail "link map has no _start"
[ "$ENTRY_ADDR" = "018a0000" ] || [ "$ENTRY_ADDR" = "018A0000" ] \
|| fail "linker _start is '$ENTRY_ADDR', want 018a0000"
cp "$SDK/TERMTRIS.OUT" "$WORK/termtris.coff"
cp "$SDK/TERMTRIS.ASM" "$WORK/termtris.asm"
echo " linked .text at $ENTRY_ADDR, TERMTRIS.OUT -> $WORK/termtris.coff"
awk '/^\.text|^\.data|^\.cinit|^\.bss/ || /_dbg_loops|_dbg_events|_dbg_last|_dbg_focus|_dbg_rev|_quit|_tick_interval/ {print}' \
"$WORK/termtris.map" | sed -n '1,40p'
+12
View File
@@ -0,0 +1,12 @@
/*
* stdlib.h -- the subset of <stdlib.h> termtris' game.c uses, for the
* freestanding tms-clang build. The implementations come from the TI 1987
* RTS.LIB (rand/srand); there is no heap allocator in the game.
*/
#ifndef VT_TERMTRIS_STDLIB_H_
#define VT_TERMTRIS_STDLIB_H_
int rand(void);
void srand(unsigned seed);
#endif
+15
View File
@@ -0,0 +1,15 @@
/*
* string.h -- the subset of <string.h> termtris uses, for the freestanding
* tms-clang build. The implementations come from the TI 1987 RTS.LIB.
*/
#ifndef VT_TERMTRIS_STRING_H_
#define VT_TERMTRIS_STRING_H_
void *memcpy(void *dst, const void *src, unsigned n);
void *memset(void *dst, int c, unsigned n);
unsigned strlen(const char *s);
char *strcpy(char *dst, const char *src);
char *strncpy(char *dst, const char *src, unsigned n);
int strcmp(const char *a, const char *b);
#endif
+8
View File
@@ -0,0 +1,8 @@
/*
* time.h -- game.c includes <time.h>, but the VT1200 port replaces time(0)
* with the ROM's free-running tick (vt_rand_seed); no time function is used.
*/
#ifndef VT_TERMTRIS_TIME_H_
#define VT_TERMTRIS_TIME_H_
#endif
+393
View File
@@ -0,0 +1,393 @@
-- play_keys.lua -- M4 termtris acceptance harness (adapted from the pinned
-- apps/termtris/tests/play_keys.lua).
--
-- Boots the firmware with VT1200_SKIP_LEVEL1=1 (the documented divergence) to
-- the OS, then at frame LOADER_AT pokes:
-- * the loader payload at bit 0x01880000 (raw dwt/loader/build/loader.bin)
-- * a GSPLNK COFF image at LOADER_BUF (default bit 0x01900000)
-- * the loader descriptor at 0x01882C00
-- and sets PC = 0x01880000. It does not use the network, the rdebug service
-- or any firmware transport: this is the debugger-assisted milestone.
--
-- The loader itself copies the COFF sections to their linked bit addresses and
-- calls create_process(entry, "LOADER", 0x6000, 1, 0). This script only pokes
-- the input and reads the result; it never writes the app's code or markers.
--
-- Env:
-- LOADER_BIN loader payload (default dwt/loader/build/loader.bin)
-- LOADER_COFF app COFF (default dwt/loader/build/marker.coff)
-- LOADER_BUF COFF buffer bit address (default 0x01900000)
-- LOADER_AT injection frame (default 2500)
-- LOADER_END inspection/exit frame (default 2700)
-- LOADER_OUT evidence directory (default dwt/loader/evidence)
-- LOADER_SNAP 1 = write a PNG at LOADER_END (default 0)
-- LOADER_VERBOSE 1 = print the result block every 25 frames
local function hex(v, w) return string.format("%0" .. (w or 8) .. "X", v) end
local machine = manager.machine
local PLAY_MODE = os.getenv("PLAY_MODE") or "move"
print("PLAYKEYS: mode="..PLAY_MODE)
local DL = tonumber(os.getenv("DIAG_LOOPS") or "0")
local DE = tonumber(os.getenv("DIAG_EVENTS") or "0")
local DT = tonumber(os.getenv("DIAG_LAST") or "0")
local DF = tonumber(os.getenv("DIAG_FOCUS") or "0")
local DR = tonumber(os.getenv("DIAG_REV") or "0")
local DQ = tonumber(os.getenv("DIAG_QUIT") or "0")
local DTICK = tonumber(os.getenv("DIAG_TICK") or "0")
local DW = tonumber(os.getenv("DIAG_WIN") or "0")
local ports = machine.ioport.ports
local key_a = ports[":lk401:K26"].fields["A"]
local key_d = ports[":lk401:K28"].fields["D"]
local key_s = ports[":lk401:K27"].fields["S"]
local key_w = ports[":lk401:K14"].fields["W"]
local key_0 = ports[":lk401:K10"].fields["0 )"]
local key_p = ports[":lk401:K22"].fields["P"]
local key_r = ports[":lk401:K16"].fields["R"]
local key_h = ports[":lk401:K31"].fields["H"]
local key_q = ports[":lk401:K13"].fields["Q"]
local tabx = ports[":tablet:TABLET_X"].fields["Tablet X"]
local taby = ports[":tablet:TABLET_Y"].fields["Tablet Y"]
local tabb = ports[":tablet:TABLET_BTN"].fields["P1 Button 1"]
local cpu = machine.devices[':maincpu']
local dbg = machine.debugger
local prog = cpu.spaces['program']
if not dbg then
print("LOADER: debugger not enabled; pass -debug")
machine:exit()
return
end
local AT = tonumber(os.getenv("LOADER_AT") or "2500")
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local BIN = os.getenv("LOADER_BIN") or "dwt/loader/build/loader.bin"
local COFF = os.getenv("LOADER_COFF") or "dwt/loader/build/marker.coff"
local BUF = tonumber(os.getenv("LOADER_BUF") or "0x01900000")
local OUT = os.getenv("LOADER_OUT") or "dwt/loader/evidence"
local SNAP = os.getenv("LOADER_SNAP") == "1"
local MODE = tonumber(os.getenv("LOADER_MODE") or "0")
local A8DESC = os.getenv("LOADER_A8_DESC") == "1"
local VERBOSE = os.getenv("LOADER_VERBOSE") == "1"
local LOADER_BASE = 0x01880000
local DESC = 0x01882C00
local RESULT = 0x01882D00
local RETURN_STUB = 0x01883100
local RETURN_SP = 0x01883110
local function rd(p) return io.open(p, "rb") end
local function slurp(p)
local f, err = rd(p)
if not f then error("cannot open " .. p .. ": " .. tostring(err)) end
local s = f:read("*a")
f:close()
return s
end
local function u16(s, o)
return s:byte(o + 1) + s:byte(o + 2) * 256
end
local function u32(s, o)
return s:byte(o + 1) + s:byte(o + 2) * 256
+ s:byte(o + 3) * 65536 + s:byte(o + 4) * 16777216
end
local function parse_coff(d)
local c = { data = d }
c.magic = u16(d, 0)
c.nscns = u16(d, 2)
c.opthdr = u16(d, 16)
c.sections = {}
if c.opthdr > 0 then
c.optmagic = u16(d, 20)
c.entry = u32(d, 20 + 16)
c.textstart = u32(d, 20 + 20)
c.datastart = u32(d, 20 + 24)
end
local base = 20 + c.opthdr
for i = 0, c.nscns - 1 do
local o = base + i * 40
local name = d:sub(o + 1, o + 8):gsub("%z", "")
c.sections[#c.sections + 1] = {
name = name,
paddr = u32(d, o + 8),
size = u32(d, o + 16), -- bits
scnptr = u32(d, o + 20),
flags = u32(d, o + 36),
}
end
return c
end
local function poke_bytes(bitaddr, data)
local n = math.floor((#data + 1) / 2)
for i = 0, n - 1 do
local lo = data:byte(i * 2 + 1) or 0
local hi = data:byte(i * 2 + 2) or 0
prog:write_u16(bitaddr + i * 16, lo + hi * 256)
end
return n
end
local function verify_bytes(bitaddr, data)
local n = math.floor((#data + 1) / 2)
local bad = 0
for i = 0, n - 1 do
local lo = data:byte(i * 2 + 1) or 0
local hi = data:byte(i * 2 + 2) or 0
if prog:read_u16(bitaddr + i * 16) ~= lo + hi * 256 then
bad = bad + 1
end
end
return n, bad
end
local function w32(a, v) prog:write_u32(a, v) end
local function r32(a)
local ok, v = pcall(function() return prog:read_u32(a) end)
if ok then return v end
return 0xDEADBEEF
end
local loader = slurp(BIN)
local coff = slurp(COFF)
local app = parse_coff(coff)
print(string.format("LOADER: payload %s (%d B) -> bit %s", BIN, #loader, hex(LOADER_BASE)))
print(string.format("LOADER: COFF %s (%d B) -> bit %s", COFF, #coff, hex(BUF)))
print(string.format("LOADER: file magic=%04X nscns=%d opthdr=%d optmagic=%s entry=%s textstart=%s",
app.magic, app.nscns, app.opthdr,
app.optmagic and string.format("%04X", app.optmagic) or "none",
hex(app.entry or 0), hex(app.textstart or 0)))
for _, s in ipairs(app.sections) do
print(string.format("LOADER: sec %-8s paddr=%s size=%d bits (%d B) scnptr=%#x flags=%#x",
s.name, hex(s.paddr), s.size, math.floor(s.size / 8), s.scnptr, s.flags))
end
local TRACE = os.getenv("LOADER_TRACE") == "1"
local frames = 0
local injected = false
local done = false
local last_count = -1
local function status_name(v)
local t = {
[0] = "OK",
[1] = "bad descriptor",
[2] = "truncated COFF / section headers",
[3] = "bad COFF magic",
[4] = "section size not whole words",
[5] = "target outside RAM",
[6] = "target overlaps loader page or COFF buffer",
[7] = "relocation records present (unsupported)",
[8] = "target not in a free-list block",
[9] = "no entry point",
}
return t[v] or ("error " .. tostring(v))
end
local function result_dump()
local st = r32(RESULT + 0x000)
print(string.format(
"LOADER: result status=%d (%s) entry=%s text=%s/%d bits data=%s/%d bits bss=%s/%d bits relocs=%d pcb=%s nscns=%d len=%d",
st, status_name(st), hex(r32(RESULT + 0x020)),
hex(r32(RESULT + 0x040)), r32(RESULT + 0x060),
hex(r32(RESULT + 0x080)), r32(RESULT + 0x0A0),
hex(r32(RESULT + 0x0C0)), r32(RESULT + 0x0E0),
r32(RESULT + 0x100), hex(r32(RESULT + 0x120)),
r32(RESULT + 0x140), r32(RESULT + 0x160)))
end
local function inject()
-- 1. loader itself
local n, bad = 0, 0
poke_bytes(LOADER_BASE, loader)
n, bad = verify_bytes(LOADER_BASE, loader)
print(string.format("LOADER: loader poked %d words, readback %d bad at %s",
n, bad, hex(LOADER_BASE)))
-- 2. COFF image
poke_bytes(BUF, coff)
n, bad = verify_bytes(BUF, coff)
print(string.format("LOADER: COFF poked %d words, readback %d bad at %s",
n, bad, hex(BUF)))
-- 3. pre-fill every .bss section with A5A5, so a loaded zero is meaningful
for _, s in ipairs(app.sections) do
if s.flags & 0x80 ~= 0 then
for i = 0, math.floor(s.size / 16) - 1 do
prog:write_u16(s.paddr + i * 16, 0xA5A5)
end
print(string.format("LOADER: pre-filled .bss %s..%s with A5A5",
hex(s.paddr), hex(s.paddr + s.size)))
end
end
-- 4. descriptor: magic "LD" "R1", buf, len, mode=0 (spin)
w32(DESC + 0x00, 0)
prog:write_u16(DESC + 0x00, 0x4C44)
prog:write_u16(DESC + 0x10, 0x5231)
w32(DESC + 0x20, BUF)
w32(DESC + 0x40, #coff)
w32(DESC + 0x60, MODE)
print(string.format("LOADER: descriptor @%s magic=%04X/%04X buf=%s len=%d mode=%d",
hex(DESC), prog:read_u16(DESC + 0x00), prog:read_u16(DESC + 0x10),
hex(r32(DESC + 0x20)), r32(DESC + 0x40), r32(DESC + 0x60)))
-- 5. return stub. mode 0 ignores it (the loader jumps to ORIG_PC
-- itself); mode 1 returns here, and the stub resumes the interrupted
-- PC so the caller yields and the scheduler can run the child.
local orig_pc = cpu.state['PC'].value
if MODE == 1 then
prog:write_u16(RETURN_STUB, 0xC080) -- jauc <orig_pc>
prog:write_u16(RETURN_STUB + 0x10, orig_pc & 0xFFFF)
prog:write_u16(RETURN_STUB + 0x20, math.floor(orig_pc / 0x10000) & 0xFFFF)
else
prog:write_u16(RETURN_STUB, 0xC0FF) -- jruc self
end
-- 6. enter the loader. A8=0 selects the fixed descriptor; SP points at
-- the return slot so mode=1 would return to the spin stub.
-- Leave SP alone for mode 0: the loader pushes onto the current
-- process stack, then restores it and resumes at ORIG_PC. (mode 1
-- would use the return stub.)
w32(0x01882A20, orig_pc) -- LD_ORIG_PC
print(string.format("LOADER: will resume at %s after create_process", hex(orig_pc)))
cpu.state['A8'].value = A8DESC and DESC or 0
if MODE == 1 then
-- Simulate a CALLA from the current process: push the return
-- address on the *firmware* stack (a real transport would do this).
local sp = cpu.state['SP'].value - 0x20
w32(sp, RETURN_STUB)
cpu.state['SP'].value = sp
end
cpu.state['PC'].value = LOADER_BASE
injected = true
print(string.format("LOADER: frame %d: entered loader at %s (caller SP=%s)",
frames, hex(LOADER_BASE), hex(cpu.state['SP'].value)))
end
local function inspect()
result_dump()
-- Verify the placement from RAM: .text/.data must equal the file bytes.
for _, s in ipairs(app.sections) do
if s.scnptr ~= 0 and s.size > 0 then
local nb = math.floor(s.size / 8)
local bytes = coff:sub(s.scnptr + 1, s.scnptr + nb)
local _, bad = verify_bytes(s.paddr, bytes)
print(string.format("LOADER: placed %s at %s: %d bytes, %d differing",
s.name, hex(s.paddr), nb, bad))
end
end
local base = COFF:match("([^/]+)$") or COFF
if base:find("marker") then
print(string.format("LOADER: marker app: start=%s data=%s data2=%s bss=%s count=%d",
hex(r32(0x018E0000)), hex(r32(0x018E0020)), hex(r32(0x018E0040)),
hex(r32(0x018E0060)), r32(0x018E0080)))
elseif base:find("xhello") then
print(string.format("LOADER: xhello: stage=%d strlen=%d display=%s root=%s window=%s sync=%s",
r32(0x01890140), r32(0x01890160), hex(r32(0x01890100)),
hex(r32(0x01890110)), hex(r32(0x01890120)), hex(r32(0x01890130))))
end
if DL ~= 0 then
print(string.format("DIAG: loops=%d events=%d last=%d focus=%08X rev=%d quit=%d window=%08X", r32(DL), r32(DE), r32(DT), DF ~= 0 and r32(DF) or 0, DR ~= 0 and r32(DR) or 0, DQ ~= 0 and r32(DQ) or 0, DW ~= 0 and r32(DW) or 0))
if DTICK ~= 0 then
print(string.format("DIAG: tick=%d", r32(DTICK)))
end
end
print(string.format("LOADER: PC at inspection = %s", hex(cpu.state['PC'].value)))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == 2900 then tabx:set_value(700); taby:set_value(500); print("PLAYKEYS: move") end
if frames == 3000 then tabb:set_value(1); print("PLAYKEYS: click down") end
if frames == 3020 then tabb:set_value(0); print("PLAYKEYS: click up") end
if PLAY_MODE == "move" then
if frames == 3100 then key_a:set_value(1) end
if frames == 3110 then key_a:set_value(0) end
if frames == 3120 then key_d:set_value(1) end
if frames == 3130 then key_d:set_value(0) end
if frames == 3140 then key_s:set_value(1) end
if frames == 3150 then key_s:set_value(0) end
if frames == 3160 then key_w:set_value(1) end
if frames == 3170 then key_w:set_value(0) end
if frames == 3180 then key_0:set_value(1) end
if frames == 3190 then key_0:set_value(0) end
elseif PLAY_MODE == "panels" then
if frames == 3100 then key_h:set_value(1) end
if frames == 3110 then key_h:set_value(0) end
if frames == 3120 then key_r:set_value(1) end
if frames == 3130 then key_r:set_value(0) end
elseif PLAY_MODE == "quit" then
if frames == 3095 then print("PLAYKEYS: quit arm") end
if frames == 3100 then print("PLAYKEYS: Q down"); key_q:set_value(1) end
if frames == 3110 then print("PLAYKEYS: Q up"); key_q:set_value(0) end
end
if frames == AT and not injected then
inject()
if TRACE then dbg:command("trace /tmp/opencode/ld1.tr") end
end
if injected and TRACE and frames == AT + 1 then
dbg:command("trace off")
print("LOADER: trace written to /tmp/opencode/ld.tr")
end
if injected and not done then
if TRACE and frames <= AT + 40 then
print(string.format("LOADER: trace f=%d PC=%s SP=%s A14=%s status=%s entry=%s",
frames, hex(cpu.state['PC'].value), hex(cpu.state['SP'].value),
hex(cpu.state['A14'].value), hex(r32(RESULT + 0x000)),
hex(r32(RESULT + 0x020))))
end
local st = r32(RESULT + 0x000)
-- status 0 means OK; nonzero is final too once parsing has begun
if st ~= 0xFFFFFFFF and not done then
-- The loader writes 0 on success. A nonzero status is final
-- only after it has been written once (it is 0 from power-on,
-- so require the loader to have run: PC no longer at entry or
-- the app counter moved).
end
if VERBOSE and frames % 25 == 0 then
result_dump()
end
if base_contains_marker then
local c = r32(0x018E0080)
if c ~= last_count then
if last_count ~= -1 then
print(string.format("LOADER: marker counter %d -> %d (child running)",
last_count, c))
end
last_count = c
end
end
end
if frames >= ENDF then
if injected then
done = true
inspect()
if SNAP then
local screen = nil
for _, s in pairs(machine.screens) do screen = s break end
if screen then
local out = OUT .. "/loader_frame" .. frames .. ".png"
local ok, err = pcall(function() return screen:snapshot(out) end)
print(string.format("LOADER: snapshot %s ok=%s %s",
out, tostring(ok), tostring(err or "")))
end
end
end
machine:exit()
end
end, "vt1200-loader")
-- (Lua has no forward use of a name defined later; set a small flag here.)
base_contains_marker = (COFF:match("([^/]+)$") or ""):find("marker") ~= nil
dbg.visible_cpu = cpu
dbg.execution_state = 'run'
+104
View File
@@ -0,0 +1,104 @@
#!/bin/sh
# play_keys.sh -- run the M4-built termtris COFF in MAME through the proven
# play_keys paths (board, move, panels, quit), capture a snapshot per mode,
# and print the DIAG line. Threshold enforcement lives in
# scripts/tests/m4/termtris.sh.
#
# scripts/m4/termtris/play_keys.sh
#
# Env: MODES (default "board move panels quit"), TERMTRIS_NOBUILD=1,
# MAME, TERMTRIS_WORK, LOADER_AT/LOADER_END.
set -eu
ROOT=$(cd "$(dirname "$0")/../../.." && pwd)
DIR=$ROOT/scripts/m4/termtris
VENDOR=${VT1200_TERMTRIS:-$ROOT/vendor/vt1200-termtris}
WORK=${TERMTRIS_WORK:-$ROOT/build/m4-termtris}
M=${MAME:-$ROOT/build/mame-src/vt1200}
COFF=$WORK/termtris.coff
MAP=$WORK/termtris.map
EV=$WORK/evidence
LOADER=$ROOT/vendor/vt1200/dwt/loader/build/loader.bin
fail() {
echo "termtris play_keys: $*" >&2
exit 1
}
if [ "${TERMTRIS_NOBUILD:-}" != 1 ]; then
"$DIR/build.sh" > "$WORK/build.log" 2>&1 \
|| { tail -40 "$WORK/build.log" >&2; fail "build failed"; }
fi
[ -f "$COFF" ] || fail "missing COFF: $COFF"
[ -f "$MAP" ] || fail "missing link map: $MAP"
[ -x "$M" ] || fail "MAME binary not built: $M"
[ -f "$LOADER" ] || fail "COFF loader missing: $LOADER"
mkdir -p "$EV" "$WORK/run/nvram" "$WORK/run/cfg"
# The link map prints two address/name pairs per line, so the symbol address
# is the field before the name (the vendored play_keys.sh does the same).
addr() {
awk -v sym="$1" '{for (i = 2; i <= NF; i++) if ($i == sym) print $(i - 1)}' \
"$MAP" | head -1
}
DIAG_LOOPS=$(addr _dbg_loops)
DIAG_EVENTS=$(addr _dbg_events)
DIAG_LAST=$(addr _dbg_last)
DIAG_FOCUS=$(addr _dbg_focus)
DIAG_REV=$(addr _dbg_rev)
DIAG_QUIT=$(addr _quit)
DIAG_TICK=$(addr _tick_interval)
DIAG_WIN=$(addr _vt_win)
for sym in "$DIAG_LOOPS" "$DIAG_EVENTS" "$DIAG_LAST" "$DIAG_FOCUS" \
"$DIAG_REV" "$DIAG_QUIT" "$DIAG_TICK" "$DIAG_WIN"; do
[ -n "$sym" ] || fail "a termtris DIAG symbol is missing from $MAP"
done
echo "== termtris markers: loops=$DIAG_LOOPS events=$DIAG_EVENTS last=$DIAG_LAST"
echo " focus=$DIAG_FOCUS rev=$DIAG_REV quit=$DIAG_QUIT tick=$DIAG_TICK win=$DIAG_WIN"
for mode in ${MODES:-board move panels quit}; do
LOG=$WORK/play_$mode.log
rm -f "$EV/loader_frame3200.png" "$EV/loader_frame"*.png
echo "== play_keys: $mode"
VT1200_SKIP_LEVEL1=1 \
VT1200_MONITOR=VR319 \
LOADER_SNAP=1 \
PLAY_MODE=$mode \
DIAG_LOOPS="0x$DIAG_LOOPS" \
DIAG_EVENTS="0x$DIAG_EVENTS" \
DIAG_LAST="0x$DIAG_LAST" \
DIAG_FOCUS="0x$DIAG_FOCUS" \
DIAG_REV="0x$DIAG_REV" \
DIAG_QUIT="0x$DIAG_QUIT" \
DIAG_TICK="0x$DIAG_TICK" \
DIAG_WIN="0x$DIAG_WIN" \
LOADER_AT="${LOADER_AT:-2500}" \
LOADER_END="${LOADER_END:-3200}" \
LOADER_BIN="$LOADER" \
LOADER_COFF="$COFF" \
LOADER_OUT="$EV" \
timeout "${MAME_TIMEOUT:-900}" "$M" vt1200 \
-rompath "$ROOT/vendor/vt1200/harness/mame/roms" \
-video none -sound none -nothrottle -skip_gameinfo \
-nvram_directory "$WORK/run/nvram" \
-cfg_directory "$WORK/run/cfg" \
-debug -debugger none \
-autoboot_script "$DIR/play_keys.lua" -autoboot_delay 0 \
> "$LOG" 2>&1 \
|| { tail -40 "$LOG" >&2; fail "MAME run failed for $mode"; }
grep -E 'PLAYKEYS:|LOADER: result|LOADER: snapshot' "$LOG" | tail -5 \
|| true
DIAG=$(grep -a 'DIAG: loops' "$LOG" | tail -1 || true)
[ -n "$DIAG" ] || { tail -40 "$LOG" >&2; \
fail "no DIAG line for $mode (see $LOG)"; }
echo " $DIAG"
echo "$DIAG" > "$WORK/diag_$mode.txt"
[ -s "$EV/loader_frame${LOADER_END:-3200}.png" ] \
|| fail "no $mode snapshot in $EV"
cp "$EV/loader_frame${LOADER_END:-3200}.png" \
"$EV/termtris_${mode}_${LOADER_END:-3200}.png"
echo " $EV/termtris_${mode}_${LOADER_END:-3200}.png"
done
+24
View File
@@ -0,0 +1,24 @@
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n)*0x20u))
int le(int a, int b) { return a <= b; }
unsigned ule(unsigned a, unsigned b) { return a <= b; }
int sum_le(int n) { int s = 0, i; for (i = 0; i <= n; i++) s += i; return s; }
int ge(int a, int b) { return a >= b; }
unsigned uge(unsigned a, unsigned b) { return a >= b; }
int gt(int a, int b) { return a > b; }
unsigned ugt(unsigned a, unsigned b) { return a > b; }
int ne(int a, int b) { return a != b; }
int lt(int a, int b) { return a < b; }
unsigned ult(unsigned a, unsigned b) { return a < b; }
int unsigned_test(void) {
MARK(0) = (unsigned)le(5, 7);
MARK(1) = (unsigned)ule(7u, 5u);
MARK(2) = (unsigned)sum_le(10);
MARK(3) = (unsigned)ge(7, 5);
MARK(4) = (unsigned)uge(5u, 7u);
MARK(5) = (unsigned)gt(5, 7);
MARK(6) = (unsigned)ugt(7u, 5u);
MARK(7) = (unsigned)ne(7, 5);
MARK(8) = (unsigned)lt(7, 5);
MARK(9) = (unsigned)ult(5u, 7u);
return 0;
}
+384
View File
@@ -0,0 +1,384 @@
#!/bin/sh
# M4 ROM symbol validation.
#
# Every entry in the v2.2 table must:
# - sit in the ROM bit range 3F200000h..3FFFFFFFh,
# - be 16-bit aligned (TMS34010 instructions are 16-bit words), and
# - start with a plausible function prologue (MMTM/MOVE/SETF/CMP/ADDI).
#
# The correction-sensitive entries are also checked semantically with dis34:
# - XMapWindow must be 0x3FD64F60 and build MapWindow request opcode 8;
# - XRaiseWindow must be 0x3FD645B0 and build ConfigureWindow opcode 12 with
# CWStackMode=Above (value mask 0x40, value 0);
# - XPutImage builds request opcode 0x48 and XGetImage opcode 0x49;
# - XLoadFont builds OpenFont opcode 45 (0x2d) and XCopyArea CopyArea
# opcode 62 (0x3e) — both from the ROM request builders, not termtris;
# - XCreatePixmap builds CreatePixmap opcode 0x35 and XSetInputFocus builds
# SetInputFocus opcode 0x2a;
# - XCreateImage allocates 0x58 bytes (sizeof(XImage) == 88);
# - XSetErrorHandler / XSetIOErrorHandler install the ROM defaults into the
# per-process XG block at +0x60 / +0x40.
#
# This is a separate gate from scripts/m3/validate-syms.sh: M3 is a four-entry
# regression, M4 walks the whole table. Both use the same range/alignment/
# prologue rules and the same corrected XMapWindow address.
#
# scripts/m4/validate-syms.sh [symbols/vt1200-v22.syms]
#
# Overridable: M4_SYMS DIS34 ROM
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
SYMS=${1:-${M4_SYMS:-$ROOT/symbols/vt1200-v22.syms}}
DIS34=${DIS34:-$ROOT/vendor/vt1200/tools/smart34010/dis34}
ROM=${ROM:-$ROOT/vendor/vt1200/vt1200_v22.bin}
ROM_LO=$((0x3F200000))
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
}
[ -f "$SYMS" ] || fail "symbol file not found: $SYMS"
[ -x "$DIS34" ] || fail "dis34 not found or not executable: $DIS34"
[ -f "$ROM" ] || fail "ROM image not found: $ROM"
TMP=$(mktemp -d "${TMPDIR:-/tmp}/m4-syms.XXXXXX")
trap 'rm -rf "$TMP"' EXIT HUP INT TERM
sym_addr() { # sym_addr NAME
awk -v n="$1" '$1 == n { print $2; exit }' "$SYMS"
}
dis_at() { # dis_at BIT_ADDR BYTE_COUNT OUT
_daddr=$1
_dcount=$2
_dout=$3
_doff=$(( (_daddr - ROM_LO) / 8 ))
dd if="$ROM" of="$_dout.bin" bs=1 skip="$_doff" count="$_dcount" 2>/dev/null
# dis34 reports "unexpected end of input" when the last instruction is
# truncated; the leading instructions are still valid, so ignore its exit
# status and parse the output.
"$DIS34" -b "$(printf '%08X' "$_daddr")" -o "$_dout.bin" \
> "$_dout" 2>/dev/null || true
}
first_insn() { # first_insn DIS_TEXT
awk 'NF && $1 !~ /^L[0-9A-Fa-f]+:$/ { print tolower($1); exit }' "$1"
}
require_match() { # require_match DIS_TEXT ERE WHAT
grep -Eiq "$2" "$1" || {
sed 's/^/ /' "$1" >&2
fail "$3"
}
}
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
case "$_addr" in
0x* | 0X*) ;;
*) fail "$_name has malformed address '$_addr' (want 0x...)" ;;
esac
_dec=$((_addr))
[ "$_dec" -ge "$ROM_LO" ] && [ "$_dec" -le "$ROM_HI" ] \
|| fail "$_name $_addr is outside the ROM bit range 3F200000h..3FFFFFFFh"
[ $((_dec % 16)) -eq 0 ] \
|| fail "$_name $_addr is not 16-bit aligned"
dis_at "$_dec" 64 "$TMP/insn"
_first=$(first_insn "$TMP/insn")
[ -n "$_first" ] || fail "$_name $_addr disassembled to nothing"
case " move mmtm setf cmp addi " in
*" $_first "*) ;;
*) fail "$_name $_addr starts with '$_first', not a plausible function prologue" ;;
esac
echo " ok $_name $_addr: $_first ..."
}
# XMapWindow must be the MapWindow entry, not the ConfigureWindow entry.
check_mapwindow() {
_addr=$(sym_addr XMapWindow)
[ -n "$_addr" ] || fail "table has no XMapWindow entry"
_dec=$((_addr))
if [ "$_dec" -eq "$RAISEWINDOW" ]; then
fail "XMapWindow is $_addr, which is XRaiseWindow (ConfigureWindow opcode 12), not the MapWindow entry (0x3FD64F60): wrong address"
fi
[ "$_dec" -eq "$MAPWINDOW" ] \
|| fail "XMapWindow is $_addr, expected 0x3FD64F60 (MapWindow request opcode 8); wrong address"
dis_at "$_dec" 512 "$TMP/mapwindow"
require_match "$TMP/mapwindow" 'movk[[:space:]]+8,[[:space:]]+a11' \
"XMapWindow does not build MapWindow request opcode 8"
require_match "$TMP/mapwindow" 'movb[[:space:]]+a11,[[:space:]]+\*a10' \
"XMapWindow does not write the request opcode to the display buffer"
echo " ok XMapWindow builds MapWindow opcode 8 (XRaiseWindow is 0x3FD645B0)"
}
# XRaiseWindow must be the ConfigureWindow/Above entry.
check_raisewindow() {
_addr=$(sym_addr XRaiseWindow)
[ -n "$_addr" ] || fail "table has no XRaiseWindow entry"
_dec=$((_addr))
if [ "$_dec" -eq "$MAPWINDOW" ]; then
fail "XRaiseWindow is $_addr, which is XMapWindow (MapWindow opcode 8), not ConfigureWindow: wrong address"
fi
[ "$_dec" -eq "$RAISEWINDOW" ] \
|| fail "XRaiseWindow is $_addr, expected 0x3FD645B0 (ConfigureWindow opcode 12)"
dis_at "$_dec" 512 "$TMP/raisewindow"
require_match "$TMP/raisewindow" 'movk[[:space:]]+12,[[:space:]]+a[0-9]+' \
"XRaiseWindow does not build ConfigureWindow request opcode 12"
require_match "$TMP/raisewindow" 'movi[[:space:]]+0x40,[[:space:]]+a[0-9]+' \
"XRaiseWindow does not set the CWStackMode value mask 0x40"
require_match "$TMP/raisewindow" '\*a10\(0x40\)' \
"XRaiseWindow does not write the CWStackMode value-mask field"
require_match "$TMP/raisewindow" '\*a10\(0x60\)' \
"XRaiseWindow does not write the CWStackMode=Above value"
echo " ok XRaiseWindow builds ConfigureWindow opcode 12, CWStackMode=Above"
}
# XPutImage/XGetImage request opcodes, per the ROM strings they reference.
check_image_requests() {
_addr=$(sym_addr XPutImage)
[ -n "$_addr" ] || fail "table has no XPutImage entry"
dis_at "$((_addr))" 544 "$TMP/putimage"
require_match "$TMP/putimage" 'movi[[:space:]]+0x48,[[:space:]]+a[0-9]+' \
"XPutImage does not build PutImage request opcode 0x48"
require_match "$TMP/putimage" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XPutImage does not write its request opcode to the buffer"
echo " ok XPutImage builds PutImage opcode 0x48"
_addr=$(sym_addr XGetImage)
[ -n "$_addr" ] || fail "table has no XGetImage entry"
dis_at "$((_addr))" 512 "$TMP/getimage"
require_match "$TMP/getimage" 'movi[[:space:]]+0x49,[[:space:]]+a[0-9]+' \
"XGetImage does not build GetImage request opcode 0x49"
require_match "$TMP/getimage" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XGetImage does not write its request opcode to the buffer"
echo " ok XGetImage builds GetImage opcode 0x49"
}
# XLoadFont/XCopyArea are inherited from the M4 plan, not the termtris xlib.h.
# Their ROM bodies build OpenFont opcode 45 (0x2d) and CopyArea opcode 62
# (0x3e); both write the opcode to the request buffer.
check_font_copy() {
_addr=$(sym_addr XLoadFont)
[ -n "$_addr" ] || fail "table has no XLoadFont entry"
dis_at "$((_addr))" 512 "$TMP/loadfont"
require_match "$TMP/loadfont" 'movi[[:space:]]+0x2d,[[:space:]]+a[0-9]+' \
"XLoadFont does not build OpenFont request opcode 45 (0x2d)"
require_match "$TMP/loadfont" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XLoadFont does not write its request opcode to the buffer"
echo " ok XLoadFont builds OpenFont opcode 45 (not termtris xlib.h)"
_addr=$(sym_addr XCopyArea)
[ -n "$_addr" ] || fail "table has no XCopyArea entry"
dis_at "$((_addr))" 512 "$TMP/copyarea"
require_match "$TMP/copyarea" 'movi[[:space:]]+0x3e,[[:space:]]+a[0-9]+' \
"XCopyArea does not build CopyArea request opcode 62 (0x3e)"
require_match "$TMP/copyarea" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XCopyArea does not write its request opcode to the buffer"
echo " ok XCopyArea builds CopyArea opcode 62 (not termtris xlib.h)"
}
# XCreatePixmap/XSetInputFocus are used by the image client. Their request
# builders are CreatePixmap opcode 0x35 and SetInputFocus opcode 0x2a.
check_pixmap_focus() {
_addr=$(sym_addr XCreatePixmap)
[ -n "$_addr" ] || fail "table has no XCreatePixmap entry"
dis_at "$((_addr))" 512 "$TMP/createpixmap"
require_match "$TMP/createpixmap" 'movi[[:space:]]+0x35,[[:space:]]+a[0-9]+' \
"XCreatePixmap does not build CreatePixmap request opcode 0x35"
require_match "$TMP/createpixmap" 'movb[[:space:]]+a[0-9]+,[[:space:]]+\*a[0-9]+' \
"XCreatePixmap does not write its request opcode to the buffer"
echo " ok XCreatePixmap builds CreatePixmap opcode 0x35"
_addr=$(sym_addr XSetInputFocus)
[ -n "$_addr" ] || fail "table has no XSetInputFocus entry"
dis_at "$((_addr))" 256 "$TMP/setinputfocus"
require_match "$TMP/setinputfocus" 'movi[[:space:]]+0x2a,[[:space:]]+a[0-9]+' \
"XSetInputFocus does not build SetInputFocus request opcode 0x2a"
require_match "$TMP/setinputfocus" 'calla[[:space:]]+0x3fd526e0' \
"XSetInputFocus does not call the SetInputFocus request builder"
require_match "$TMP/setinputfocus" '\*a13\(0xffa0\)' \
"XSetInputFocus does not read the revert_to argument"
require_match "$TMP/setinputfocus" '\*a13\(0xffc0\)' \
"XSetInputFocus does not read the focus argument"
require_match "$TMP/setinputfocus" '\*a13\(0xffe0\)' \
"XSetInputFocus does not read the display argument"
echo " ok XSetInputFocus builds SetInputFocus opcode 0x2a"
}
check_xcreateimage() {
_addr=$(sym_addr XCreateImage)
[ -n "$_addr" ] || fail "table has no XCreateImage entry"
dis_at "$((_addr))" 256 "$TMP/createimage"
require_match "$TMP/createimage" 'movi[[:space:]]+0x58,[[:space:]]+a[0-9]+' \
"XCreateImage does not allocate 0x58 bytes (sizeof(XImage) == 88)"
require_match "$TMP/createimage" 'calla[[:space:]]+0x3f703d90' \
"XCreateImage does not call the ROM zeroing allocator (0x3F703D90)"
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.
check_error_handlers() {
_addr=$(sym_addr XSetErrorHandler)
[ -n "$_addr" ] || fail "table has no XSetErrorHandler entry"
dis_at "$((_addr))" 448 "$TMP/seterror"
require_match "$TMP/seterror" 'movi[[:space:]]+0x3f9bd9f0,[[:space:]]+a[0-9]+' \
"XSetErrorHandler does not install _XDefaultError (0x3F9BD9F0) when the handler is null"
require_match "$TMP/seterror" '\*a11\(0x60\)' \
"XSetErrorHandler does not store into the XG block at +0x60"
echo " ok XSetErrorHandler stores XG+0x60, default _XDefaultError"
_addr=$(sym_addr XSetIOErrorHandler)
[ -n "$_addr" ] || fail "table has no XSetIOErrorHandler entry"
dis_at "$((_addr))" 448 "$TMP/setioerror"
require_match "$TMP/setioerror" 'movi[[:space:]]+0x3f9bcd40,[[:space:]]+a[0-9]+' \
"XSetIOErrorHandler does not install _XDefaultIOError (0x3F9BCD40) when the handler is null"
require_match "$TMP/setioerror" '\*a11\(0x40\)' \
"XSetIOErrorHandler does not store into the XG block at +0x40"
echo " ok XSetIOErrorHandler stores XG+0x40, default _XDefaultIOError"
}
# Walk every symbol line. Keep this generic so a newly added entry cannot
# silently bypass the range/alignment/prologue gate.
echo "== validate every v2.2 table entry"
count=0
while read -r name addr rest; do
case "$name" in
'' | '#'*) continue ;;
esac
[ -n "$addr" ] || fail "malformed symbol line for '$name' (no address)"
check_prologue "$name" "$addr"
count=$((count + 1))
done < "$SYMS"
[ "$count" -gt 0 ] || fail "no entries found in $SYMS"
echo "== validate the correction-sensitive entries"
check_mapwindow
check_raisewindow
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; M7.3 wider Xlib opcodes pinned)"
+31
View File
@@ -0,0 +1,31 @@
-- varargs-check.lua -- load the varargs ABI probe with the M4 COFF loader and
-- check the three sums. The callee walks the contiguous program stack below
-- its last fixed argument; these values prove the variadic slots are real.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
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, 2 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format("M4: varargs sum1=%d sum2=%d sum3=%d",
m[0], m[1], m[2]))
if m[0] == 15 and m[1] == 150 and m[2] == 1500 then
print("M4 MAME: PASS")
else
print("M4 MAME: FAIL (want 15, 150, 1500)")
end
end
end, "varargs-check")
+13
View File
@@ -0,0 +1,13 @@
; varargs-entry.asm -- M4 entry for the varargs ABI probe.
.text
.globl _start
.globl _varargs_test
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _varargs_test
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+35
View File
@@ -0,0 +1,35 @@
/*
* varargs.c -- the contiguous-stack varargs ABI probe.
*
* M4 supports only the TI ABI's stack layout: a variadic callee takes the
* address of its last fixed argument and walks down one 32-bit slot per extra
* argument. There is no va_start/va_arg/va_list. The termtris compat.c
* sprintf uses exactly this pattern; this probe proves the values arrive.
*
* Markers (0x20 bits apart, written by the test):
* 018A8000 sumvar(1,2,3,4,5) == 15
* 018A8020 sumvar(10,20,30,40,50) == 150
* 018A8040 sumvar(100,200,300,400,500) == 1500
*/
#define MARK(n) (*(volatile int *)(0x018A8000UL + (n) * 0x20UL))
static int sumvar(int a, int b, ...)
{
int *p = &b;
int s = a + b;
p--;
s += *p; /* first variadic argument */
p--;
s += *p; /* second */
p--;
s += *p; /* third */
return s;
}
void varargs_test(void)
{
MARK(0) = sumvar(1, 2, 3, 4, 5);
MARK(1) = sumvar(10, 20, 30, 40, 50);
MARK(2) = sumvar(100, 200, 300, 400, 500);
}
+452
View File
@@ -0,0 +1,452 @@
/*
* Minimal X11R4-compatible declarations for the M4 VT1200 clients.
*
* The VT1200 X server is X11R4 on a 32-bit TMS34010, so this header models
* that ABI: XID/Window/KeySym/Time are 32-bit unsigned long, GC is a 32-bit
* pointer, and XImage carries the inline six-entry struct funcs tail.
*
* Display/Screen deliberately do NOT include the host X11R4 header. The
* VT1200 ROM's Display is the M3-verified layout: Display.screens at byte
* 0x90 (bit 0x480) and Screen.root at byte 0x8 (bit 0x40). Do not include
* scripts/m3/vt1200_xlib.h here; its XOpenDisplay/XCreateSimpleWindow
* prototypes conflict with the wider M4 ones below.
*
* Offset assertions live in scripts/m4/layout.c; the TI golden in
* scripts/m4/layout-ti.s carries the same bit displacements.
*/
#ifndef X11M4_H
#define X11M4_H
typedef unsigned long XID;
typedef XID Window;
typedef XID Drawable;
typedef XID Pixmap;
typedef XID Atom;
typedef XID Colormap;
typedef XID Cursor;
typedef XID Font;
typedef XID GContext;
typedef XID KeySym;
typedef unsigned long Mask;
typedef unsigned long Time;
typedef int Bool;
typedef unsigned char KeyCode;
typedef char *XPointer;
typedef struct _XGC *GC;
typedef struct _Visual Visual; /* opaque: clients only pass a Visual * */
typedef struct _XImage XImage;
/*
* The VT1200 ROM layout, reused from scripts/m3/vt1200_xlib.h. TMS34010
* indirect displacements are bit offsets, so screens is at byte 0x90 and
* root at byte 0x8.
*/
typedef struct _Display {
unsigned char pad[0x90];
void *screens;
} Display;
typedef struct _Screen {
unsigned char pad[0x8];
unsigned int root;
} Screen;
/* X11R4 xlib.h: the image function table is inline in XImage, not a pointer. */
struct funcs {
XImage *(*create_image)(Display *, Visual *, unsigned int, int, int, char *,
unsigned int, unsigned int, int, int);
int (*destroy_image)(XImage *);
unsigned long (*get_pixel)(XImage *, int, int);
int (*put_pixel)(XImage *, int, int, unsigned long);
XImage *(*sub_image)(XImage *, int, int, unsigned int, unsigned int);
int (*add_pixel)(XImage *, long);
};
typedef struct _XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask, green_mask, blue_mask;
void *obdata;
struct funcs f;
} XImage;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
} XAnyEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
Window root;
Window subwindow;
Time time;
int x, y;
int x_root, y_root;
unsigned int state;
unsigned int keycode;
Bool same_screen;
} XKeyEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
Window root;
Window subwindow;
Time time;
int x, y;
int x_root, y_root;
unsigned int state;
unsigned int button;
Bool same_screen;
} XButtonEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
int mode;
int detail;
} XFocusChangeEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
int x, y;
int width, height;
int count;
} XExposeEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window event;
Window window;
int x, y;
int width, height;
int border_width;
Window above;
Bool override_redirect;
} XConfigureEvent;
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
Atom message_type;
int format;
union {
char b[20];
short s[10];
long l[5];
} data;
} XClientMessageEvent;
typedef struct {
int type;
Display *display;
XID resourceid;
unsigned long serial;
unsigned char error_code;
unsigned char request_code;
unsigned char minor_code;
/*
* X11R4's 32-bit XErrorEvent is 20 bytes. The TMS34010 C ABI packs
* structs (and TI C does too), so the three trailing chars would make the
* packed object 19 bytes. This byte is an X11R4 object-size compatibility
* pad; the client reads only the handler-passed fields.
*/
unsigned char abi_pad;
} XErrorEvent;
/*
* X11R4's XEvent is 96 bytes: the largest member is pad[24] (the protocol
* xEvent is 24 longs). The termtris event buffer is vt_u32 evbuf[24].
*/
typedef union _XEvent {
int type;
XAnyEvent xany;
XKeyEvent xkey;
XButtonEvent xbutton;
XFocusChangeEvent xfocus;
XExposeEvent xexpose;
XConfigureEvent xconfigure;
XClientMessageEvent xclient;
XErrorEvent xerror;
long pad[24];
} XEvent;
/* Event codes (X11R4). */
#define KeyPress 2
#define KeyRelease 3
#define ButtonPress 4
#define ButtonRelease 5
#define FocusIn 9
#define FocusOut 10
#define Expose 12
/* Event masks (X11R4). */
#define NoEventMask 0L
#define KeyPressMask (1L << 0)
#define KeyReleaseMask (1L << 1)
#define ButtonPressMask (1L << 2)
#define ButtonReleaseMask (1L << 3)
#define ExposureMask (1L << 15)
#define StructureNotifyMask (1L << 17)
#define FocusChangeMask (1L << 21)
/* Image byte/bit order and format. */
#define LSBFirst 0
#define MSBFirst 1
#define XYBitmap 0
#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
typedef int (*XErrorHandler)(Display *, XErrorEvent *);
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 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,
unsigned int width, unsigned int height,
unsigned int border_width,
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,
unsigned int depth);
/* ConfigureWindow(CWStackMode=Above): map-and-raise for a client that must be
* above the Terminal Manager (XMapWindow alone does not raise). */
extern int XRaiseWindow(Display *display, Window window);
extern int XSync(Display *display, Bool discard);
extern int XFlush(Display *display);
extern int XSelectInput(Display *display, Window window, long event_mask);
extern GC XCreateGC(Display *display, Drawable drawable,
unsigned long valuemask, void *values);
extern int XSetForeground(Display *display, GC gc, unsigned long foreground);
extern int XFillRectangle(Display *display, Drawable drawable, GC gc, int x,
int y, unsigned int width, unsigned int height);
extern int XDrawString(Display *display, Drawable drawable, GC gc, int x, int y,
const char *string, int length);
extern int XNextEvent(Display *display, XEvent *event);
extern int XLookupString(XKeyEvent *event, char *buffer, int bytes,
KeySym *keysym, void *compose_status);
extern int XPending(Display *display);
/* The ROM's ms sleep (symbols/vt1200-v22.syms: 0x3FB33A20); yields so the
* X server and the other firmware processes keep running. */
extern int sleep(int ms);
extern int XGetInputFocus(Display *display, Window *focus, int *revert_to);
/*
* The ROM's XSetInputFocus reads three arguments (display, focus, revert_to)
* and supplies CurrentTime inside the request builder; the disassembly at
* 0x3FD536B0 reads 0xffe0/0xffc0/0xffa0 and builds SetInputFocus opcode 0x2a.
*/
#define RevertToParent 2
extern int XSetInputFocus(Display *display, Window focus, int revert_to);
/* ROM blitter memcpy used by _XPutImage; the ROM order is (src, dst, bytes). */
extern int blit_copy(void *src, void *dst, int nbytes);
extern Font XLoadFont(Display *display, const char *name);
extern int XCopyArea(Display *display, Drawable src, Drawable dest, GC gc,
int src_x, int src_y, unsigned int width,
unsigned int height, int dest_x, int dest_y);
extern XImage *XCreateImage(Display *display, Visual *visual,
unsigned int depth, int format, int offset,
char *data, unsigned int width,
unsigned int height, int bitmap_pad,
int bytes_per_line);
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);
/* Install the per-process XG block before XOpenDisplay (scripts/m4/xgfix.c). */
extern int vt_install_xg(void);
/* Follow Display.screens (bit 0x480) and read Screen.root (bit 0x40). */
static inline __attribute__((always_inline)) unsigned int
vt_root(Display *display) {
return ((Screen *)((Display *)display)->screens)->root;
}
#endif /* X11M4_H */
+21
View File
@@ -0,0 +1,21 @@
/*
* Per-process Xlib context (XG) installer for the VT1200 loader child.
*
* The ROM Xlib keeps its per-process state in the user word at
* *(current_process + 0x100). A process created by the loader inherits a
* zeroed cell there, so the ROM's _XEnq sees XG == NULL and XNextEvent reads
* garbage or never reports events. Points that word at a zeroed 1 KiB block
* before XOpenDisplay.
*
* This is a RAM write only; the ROM image is untouched. Must be called before
* XOpenDisplay, once per process.
*/
int vt_install_xg(void) {
unsigned int proc = *(volatile unsigned int *)0x001B3900u;
if (proc < 0x100u || proc > 0x01FFFFFFu) return 0;
unsigned int pp = *(volatile unsigned int *)(proc + 0x100u);
if (pp < 0x100u || pp > 0x01FFFFFFu) return 0;
static unsigned int xg[256]; /* 1 KiB zeroed .bss */
*(volatile unsigned int *)pp = (unsigned int)xg;
return 1;
}
+153
View File
@@ -0,0 +1,153 @@
-- xshow-check.lua -- load the M4 image/event COFF with dwt/loader/loader.lua,
-- inject a real LK401 `Q` key, and prove the mapped 1-bit XImage in VRAM.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_AT injection frame (default 2500)
-- LOADER_END loader inspection/exit frame (default 3400)
--
-- Markers (0x20 bits apart):
-- 018A8000 display nonzero
-- 018A8020 window nonzero
-- 018A8040 image nonzero
-- 018A8060 quit 1 after the `q` KeyPress
-- 018A8080 events count of XNextEvent calls (> 0)
-- 018A80A0 keycode ev.xkey.keycode (193 for the LK401 Q)
-- 018A80C0 keysym XLookupString keysym (XK_q = 0x71)
-- 018A80E0 xerrors 0
-- 018A8100 focus XGetInputFocus after XSetInputFocus
-- 018A8120 last last X event type (2 = KeyPress)
--
-- The client window is XCreateSimpleWindow(..., 20, 20, 640, 480, ...) with
-- no border. The VT1200 server copies a 1-bit bitmap correctly only when the
-- destination x is 32-bit aligned, so the client draws the aligned pixmap at
-- window x = 12 (screen x = 32) and fills the 12-pixel prefix with the
-- preceding cell's colour. The checker cells are 32 pixels wide with a
-- 12-pixel phase: image data x = sx - 20 - 12. The window-relative points
-- (30,30) and (50,30) are adjacent cells (0,0) and (1,0), as are (30,62) and
-- (50,62). The samples at data (368,280), (468,380) and (568,430) prove the
-- banded PutImage assembled the whole 640x480 image, not just its first band.
-- The prefix samples at screen (25,30)/(25,62) prove the preceding-cell fill.
-- The pixel is read from the exact VRAM bit address (VR319: 2048-bit rows,
-- LSB-first), not from a whole unaligned word that would cross a cell.
--
-- The focus path is the tablet click: XSetInputFocus alone leaves the DWT WM
-- at PointerRoot (verified: focus=0x1 and no key), so the gate moves the
-- absolute tablet (0..2199) to (700,500), the termtris-proven in-window point,
-- and clicks. That point maps inside termtris' (80..560,80..392) rectangle,
-- which is contained in this client's (20..660,20..500) window. The focus
-- marker must become the client's own window; the ButtonRelease handler
-- samples it after the click.
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local ports = manager.machine.ioport.ports
local key_q = ports[":lk401:K13"].fields["Q"]
local tabx = ports[":tablet:TABLET_X"].fields["Tablet X"]
local taby = ports[":tablet:TABLET_Y"].fields["Tablet Y"]
local tabb = ports[":tablet:TABLET_BTN"].fields["P1 Button 1"]
local MOVE_AT = 2900
local CLICK_DOWN = 2920
local CLICK_UP = 2930
local Q_DOWN = 3000
local Q_UP = 3010
local VRAM_BASE = 0x04000000
local VRAM_PITCH = 2048 -- VR319: 2048 bits per row
local WIN_X, WIN_Y = 20, 20
local IMG_PHASE = 12 -- pixmap is copied to window x=12 (screen x=32)
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 == MOVE_AT then
tabx:set_value(700)
taby:set_value(500)
print(string.format("M4: inject frame %d tablet (700,500)", frames))
elseif frames == CLICK_DOWN then
tabb:set_value(1)
print(string.format("M4: inject frame %d button down", frames))
elseif frames == CLICK_UP then
tabb:set_value(0)
print(string.format("M4: inject frame %d button up", frames))
elseif frames == Q_DOWN then
key_q:set_value(1)
print(string.format("M4: inject frame %d Q down", frames))
elseif frames == Q_UP then
key_q:set_value(0)
print(string.format("M4: inject frame %d Q up", frames))
end
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 9 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M4: display=%u window=%u image=%u quit=%d events=%d keycode=%d keysym=0x%X xerrors=%d focus=0x%X last=%d",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9]))
-- screen -> image (window-relative) -> 32-pixel cell
local function sample(sx, sy)
local b, bit = read_bit(prog, sx, sy)
local rx, ry = sx - WIN_X - IMG_PHASE, sy - WIN_Y
local cx, cy = math.floor(rx / 32), math.floor(ry / 32)
print(string.format(
"M4: pixel screen(%d,%d) image(%d,%d) cell(%d,%d) bit=0x%08X value=%d %s",
sx, sy, rx, ry, cx, cy, bit, b,
b == 1 and "white" or "black"))
return b
end
-- The task's exact pair plus the orthogonal pair, at cell centres and
-- at points well inside the cells (away from a 32-pixel boundary).
local b00 = sample(50, 50) -- data (18,30) cell (0,0) -> black
local b10 = sample(70, 50) -- data (38,30) cell (1,0) -> white
local b01 = sample(50, 82) -- data (18,62) cell (0,1) -> white
local b11 = sample(70, 82) -- data (38,62) cell (1,1) -> black
local c00 = sample(36, 36) -- data (4,16) cell (0,0) -> black
local c10 = sample(68, 36) -- data (36,16) cell (1,0) -> white
local c01 = sample(36, 68) -- data (4,48) cell (0,1) -> white
local c11 = sample(68, 68) -- data (36,48) cell (1,1) -> black
-- later bands, so a repeated first-band bug cannot pass
local d1 = sample(400, 300) -- data (368,280) cell (11,8) -> white
local d2 = sample(500, 400) -- data (468,380) cell (14,11) -> white
local d3 = sample(600, 450) -- data (568,430) cell (17,13) -> black
-- the 12-pixel prefix is the preceding cell: white in band 0, black
-- in band 1, so it cannot be a constant left stripe.
local p0 = sample(25, 30) -- data (-7,10) cell (-1,0) -> white
local p1 = sample(25, 62) -- data (-7,42) cell (-1,1) -> black
local keysym_ok = (m[6] == 0x71)
local image_ok = b00 == 0 and b10 == 1 and b01 == 1 and b11 == 0
and c00 == 0 and c10 == 1 and c01 == 1 and c11 == 0
and d1 == 1 and d2 == 1 and d3 == 0
and p0 == 1 and p1 == 0
local ok = m[0] ~= 0 and m[1] ~= 0 and m[2] ~= 0
and m[3] == 1 and m[4] > 0 and m[7] == 0
and m[5] == 193 and keysym_ok
and m[8] == m[1] and m[8] ~= 0 and m[9] == 2
and image_ok
if ok then
print("M4 MAME: PASS")
else
print(string.format(
"M4 MAME: FAIL (markers display/window/image=%u/%u/%u quit=%d events=%d keycode=%d keysym=0x%X xerrors=%d focus=0x%X last=%d; image %s)",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9],
image_ok and "checker-ok" or "checker-mismatch"))
end
end
end, "xshow-check")
+22
View File
@@ -0,0 +1,22 @@
; xshow-entry.asm -- M4 image/event client entry, linked at bit 018A0000.
;
; Calls the compiled xshow() client. Markers (0x20 bits apart):
; 018A8000 display nonzero
; 018A8020 window nonzero
; 018A8040 image nonzero
; 018A8060 quit 1 after the real `q` KeyPress
; 018A8080 events count of XNextEvent calls
; 018A80A0 keycode ev.xkey.keycode
; 018A80C0 keysym XLookupString keysym
; 018A80E0 xerrors 0
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _xshow
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+280
View File
@@ -0,0 +1,280 @@
/*
* xshow.c -- the M4 1-bit XImage + real-key-event client.
*
* The client installs the per-process XG block (Task 5), opens the VT1200 X
* display, creates a 640x480 window at (20,20), draws a 32-pixel checkerboard
* through a 1-bit LSBFirst XYBitmap XImage, then drains X events and quits on
* the real keyboard's `q`.
*
* Markers live at 0x018A8000 + n*0x20 (bit addresses):
* 0 Display * nonzero
* 1 Window nonzero
* 2 XImage * nonzero
* 3 quit 1 after the `q` KeyPress
* 4 events count of every XNextEvent
* 5 keycode ev.xkey.keycode of the last KeyPress
* 6 keysym XLookupString keysym of the last KeyPress
* 7 xerrors count of X protocol errors seen by on_error
* 8 focus XGetInputFocus window (0x400001 after the click)
* 9 last last X event type (2 = KeyPress)
*
* The static image is 480 * 80 bytes in .bss (640 pixels / 8 = 80 bytes per
* row). It is intentionally never passed to XDestroyImage: the ROM destructor
* frees the data pointer, which is .bss here, not heap memory.
*
* Two VT1200 server/Xlib constraints shape the drawing path. A single 38 KiB
* PutImage request does not complete (the ROM request buffer is 16 KiB), so the
* image is emitted in 32-row bands and each band selects its rows by moving
* XImage.data (the server ignores src_y). The server also copies a 1-bit
* bitmap correctly only when the destination x is 32-bit aligned, so the bands
* go into an aligned depth-1 pixmap and XCopyArea places the image at window
* x=12 (screen x=32); the 12-pixel prefix is filled with the first cell's
* colour. The checker cells are still 32 pixels, with a 12-pixel phase inside
* the (20,20) window.
*/
#include "x11m4.h"
#define MARK(n) (*(volatile unsigned int *)(0x018A8000u + (n) * 0x20u))
#define IMG_W 640
#define IMG_H 480
#define IMG_BPL 80 /* ((640 + 31) / 32) * 4 */
static int xerrors;
/*
* The image bytes: 480 rows * 80 bytes. It is built as 32-bit words because
* each word spans exactly one 32-pixel cell and LSBFirst makes word bit i
* pixel x = 32*cell + i. (The brief's per-bit byte OR loop compiles to an
* i8 load with `anyext`, which this target cannot select at -O2; the word
* form writes the identical bytes.) The 4-byte alignment lets the compiler
* use whole-word stores.
*/
static unsigned char data[IMG_H * IMG_BPL] __attribute__((aligned(4)));
/*
* The ROM calls this through the pointer installed by XSetErrorHandler. The
* Task 4 header's XErrorHandler is authoritative: int (Display*, XErrorEvent*).
*/
static int on_error(Display *d, XErrorEvent *e) {
(void)d;
(void)e;
xerrors++;
return 0;
}
/*
* Call the ROM sleep through a function pointer: the image then exercises the
* Task 3 indirect-call contract (CALL Rs) as well as the direct CALLA imports.
* It is volatile so the optimizer cannot devirtualise the load into a direct
* CALLA and erase that coverage. The pointer lives in .data as `.long _sleep`.
*/
static int (*volatile vt_sleep)(int) = sleep;
/*
* The ROM Xlib copies an XImage into its request buffer with the TMS34010
* blitter. `blit_copy` is the validated ROM entry _XPutImage calls
* (0x3F9CBFE0 -> 0x3FB44400): (source, destination, byte count). A process
* created by the loader inherits a zeroed blitter window/pitch context, so the
* first copy writes nothing; prime it once with a four-byte self-copy.
*/
static void prime_blitter(void) {
blit_copy(data, data, 4);
}
/*
* A single 640x480 1-bit PutImage is 0xC0 + 480*80 = 38592 bytes, but the ROM
* Xlib's request buffer is only 16384 bytes. XPutImage's direct-send path for
* an image larger than the buffer does not make progress in the harness, so
* emit the image in 32-row bands: each band's request fits the buffer, and the
* explicit flush/yield lets the X server drain it. The assembled drawable is
* still the whole 640x480 image.
*/
static void present(Display *d, Drawable target, Window w, GC gc) {
int y;
/*
* The server copies 1-bit bitmaps correctly only when the destination x is
* 32-bit aligned. Draw the aligned pixmap starting at window x = 12
* (screen x = 32) and fill the 12-pixel prefix with the preceding cell's
* colour, band by band, so the visible 32-pixel phase is preserved. The
* checker cells are still 32 pixels wide; the phase is offset by 12 pixels
* inside the (20,20) window. Only IMG_W - 12 = 628 columns are copied, so
* the rightmost 12 source columns (the final 12 px of the last cell) are
* not displayed and the last visible cell is 20 px, not 32.
*/
XCopyArea(d, target, w, gc, 0, 0, IMG_W - 12, IMG_H, 12, 0);
for (y = 0; y < IMG_H; y += 32) {
XSetForeground(d, gc, ((y / 32) & 1) == 0 ? 1 : 0);
XFillRectangle(d, w, gc, 0, y, 12, 32);
}
XSetForeground(d, gc, 1);
XFlush(d);
}
static void draw_image(Display *d, Drawable target, Window w, GC gc,
XImage *img) {
char *base = (char *)data;
int y;
prime_blitter();
for (y = 0; y < IMG_H; y += 32) {
/*
* src_y is ignored by the bitmap path, so select the band by moving
* the image data pointer.
*/
img->data = base + y * IMG_BPL;
XPutImage(d, target, gc, img, 0, 0, 0, y, IMG_W, 32);
XFlush(d);
vt_sleep(1);
}
img->data = base;
present(d, target, w, gc);
}
int xshow(void) {
Display *d;
Window w;
Pixmap pm;
GC gc;
XImage *img;
int tries;
int x, y;
if (!vt_install_xg())
return -1;
/*
* The display server may still be starting when the loader creates this
* process; retry as the termtris client does. XOpenDisplay allocates the
* connection, so one success ends the loop.
*/
d = 0;
for (tries = 0; tries < 40; tries++) {
d = XOpenDisplay("0::0");
if (d)
break;
vt_sleep(50);
}
MARK(0) = (unsigned)d;
if (!d)
return -1;
w = XCreateSimpleWindow(d, vt_root(d), 20, 20, IMG_W, IMG_H, 0, 0, 0);
MARK(1) = (unsigned)w;
/* These are counters/state, not loader-zeroed .bss: clear them first. */
MARK(3) = 0;
MARK(4) = 0;
MARK(5) = 0;
MARK(6) = 0;
MARK(7) = 0;
XSelectInput(d, w, ExposureMask | KeyPressMask | KeyReleaseMask |
ButtonPressMask | ButtonReleaseMask |
StructureNotifyMask | FocusChangeMask);
gc = XCreateGC(d, w, 0, 0);
XSetForeground(d, gc, 1);
pm = XCreatePixmap(d, w, IMG_W, IMG_H, 1);
/*
* 32-pixel checkerboard, LSB-first in each byte/word. Build whole 32-bit
* words (each word is exactly one 32-pixel cell) and toggle the row fill
* every 32 rows; this avoids the i8 anyext load and the i1
* sign_extend_inreg that the brief's per-bit loop creates at -O2.
*/
{
unsigned int fill = 0xFFFFFFFFu;
unsigned int band = 0;
for (y = 0; y < IMG_H; y++) {
unsigned int *row = (unsigned int *)(data + y * IMG_BPL);
unsigned int v = fill;
for (x = 0; x < IMG_BPL / 4; x++) {
row[x] = v;
v = ~v;
}
if (++band == 32) {
band = 0;
fill = ~fill;
}
}
}
/*
* visual 0 is safe for the ROM XCreateImage: it only dereferences the
* visual when the pointer is nonzero, and a depth-1 XYBitmap takes its
* byte/bit order from the Display. We set both orders explicitly below.
*/
img = XCreateImage(d, 0, 1, XYBitmap, 0, (char *)data, IMG_W, IMG_H, 32,
IMG_BPL);
MARK(2) = (unsigned)img;
if (!img)
return -1;
img->byte_order = LSBFirst;
img->bitmap_bit_order = LSBFirst;
XSetErrorHandler(on_error);
XMapWindow(d, w);
XRaiseWindow(d, w);
XSetInputFocus(d, w, RevertToParent);
draw_image(d, pm, w, gc, img);
XSync(d, 0);
{
Window fw = 0;
int rv = 0;
XGetInputFocus(d, &fw, &rv);
MARK(8) = (unsigned)fw;
}
for (;;) {
XEvent ev;
while (XPending(d)) {
XNextEvent(d, &ev);
MARK(4) = MARK(4) + 1;
MARK(9) = (unsigned)ev.type;
if (ev.type == KeyPress) {
char buf[8];
unsigned long ks = 0;
int n;
buf[0] = 0;
n = XLookupString(&ev.xkey, buf, 8, &ks, 0);
MARK(5) = (unsigned)ev.xkey.keycode;
MARK(6) = (unsigned)ks;
/* The server may hand back the shifted form. */
if (n > 0 && (buf[0] == 'q' || buf[0] == 'Q')) {
MARK(3) = 1;
break;
}
} else if (ev.type == ButtonRelease) {
Window fw = 0;
int rv = 0;
XGetInputFocus(d, &fw, &rv);
MARK(8) = (unsigned)fw;
} else if (ev.type == Expose) {
present(d, pm, w, gc);
}
}
MARK(7) = (unsigned)xerrors;
if (MARK(3))
break;
XFlush(d);
vt_sleep(5);
}
/*
* Quit: stop serving events, but keep the process alive so the harness can
* read the mapped image out of VRAM at LOADER_END. Returning here would
* let the firmware tear the process (and its window) down before the read.
*/
for (;;) {
MARK(7) = (unsigned)xerrors;
XFlush(d);
vt_sleep(5);
}
}
+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"
Loaded 100 of 273 files, more files were not shown because too many files have changed in this diff. Show more