193 Commits
m3 ... m12
Author SHA1 Message Date
arti 314ad047f4 docs: m12 is the repository default branch 2026-11-19 15:32:34 +00:00
arti 429ac96405 docs: correct the V wording and M12 tips
README repeats the accurate V limitation (no InlineAsm::ConstraintCode entry for the uppercase non-offsettable-memory constraint) and names the actual project/compiler tips. The M12 decisions log says 10 inline-asm flips, matching acceptance section 8.1 and the delivered stkalign re-reasoning.
2026-11-19 15:31:57 +00:00
arti 73506844a8 docs: correct the M12 return-address record and provenance
All three milestone docs now state the shipped capture arithmetic (SP + NumSaved*32 post-MMTM, SP + (NumSaved + 2)*32 after the two scratch pushes) and the PUSH32 A0/A1 sequence; the rejected A8 snippet is gone. README names eb9ca73 (docs tip 9a99acb) as the project state that reproduces 1,635/277 and Generic 152/45, adds the InvokeAsm manifest re-pin, and spells the missing V enum entry lowercase.

The M12 design's acceptance says 10 memory-constraint rows (stkalign is re-reasoned). The skip file qualifies the historical M9.1 stkalign sentence so it cannot be read as current.
2026-11-19 14:35:27 +00:00
arti 9a99acb01e docs: reconcile the M12 gate count and boundary
State the serial M0-M8 list as 58 invocations across 54 distinct gate scripts (the four env-variant re-runs are m5/native, m6/runtime, m6/i64 and m4/run) in README, the design spec and TMS34010.md; remove the superseded M11/M12 boundary sentence; call the five flip classes five; note that M12 re-exports 0005; add the M12 addr-label note to the Generic manifest header.
2026-11-19 13:33:01 +00:00
arti eb9ca73950 m12: document the conformance fixes and the abort triage
M12 is complete on the m12 milestone branch; promotion is pending the controller's review. This commit records the 17 row flips (10 inline-asm memory rows, 2 blockaddress, 3 level-0 frame rows, 1 dynamic alloca, eeprof-1), the suite accounting 1,912 = 1,635 pass / 277 skip / 0 fail / 0 crash, the target decisions (ST/o/V, jump Rd, the level-0 return-address capture, the alloca constant-fold fix), the triage headline and its committed probes, the permanently-out classes, and the M12/M13 boundary.

eeprof-1 is the one-flag/one-condition abort fix: dialect_flags() now forwards -finstrument-functions from dg-options and the row is removed. The probes move to scripts/tests/m12/probes/ with a README of invocations and observed statuses; the triage harness writes run-O0/run-O2 and the document's marker column is status-derived.

The final sweep found the M5 Generic sweep crashing on 2008-02-20-MatchingMem after M12 made the memory operand select but not print; the target now prints *An/*An(disp). The same sweep drops the stale addr-label manifest row because blockaddress now lowers, so Generic is 197 = 152 pass / 45 unsupported (one flip outside the curated 17).
2026-11-19 13:04:44 +00:00
arti 320e0117c1 docs: record the Task 5 review outcome 2026-11-19 09:31:00 +00:00
arti 7f1fc06bd8 m12: triage the runtime-abort skips for M13 2026-11-19 09:13:23 +00:00
arti c7e9e3a58b docs: record the Task 4 review outcome 2026-11-19 08:59:04 +00:00
arti 507dd6c615 m12: flip the dynamic-alloca row 2026-11-19 08:51:02 +00:00
arti 2601c8485f docs: record the Task 3 fix rounds 2026-11-19 08:46:19 +00:00
arti cbe617e2c0 docs: record the Task 3 severity divergence 2026-11-19 07:58:27 +00:00
arti 1fbf2a2598 m12: flip the level-0 frame rows and restate the level>0 skips 2026-11-19 07:41:38 +00:00
arti f5facf7d28 docs: record the Task 2 multi-model review outcome 2026-11-19 07:32:48 +00:00
arti 1f6ac7820c m12: flip the computed-goto rows 2026-11-19 07:15:33 +00:00
arti 61ed4ef070 docs: record the Task 1 multi-model review outcome 2026-11-19 07:06:10 +00:00
arti 817b6a03ec m12: flip the inline-asm memory-constraint rows 2026-11-19 06:56:44 +00:00
arti c779c7a725 docs: start the M12 multi-model review notes 2026-11-19 06:42:24 +00:00
arti 4bb6ce7e4c docs: M12 implementation plan 2026-11-19 06:36:35 +00:00
arti ef8a8545ac docs: M12 design (tractable conformance gaps) 2026-11-19 06:27:24 +00:00
arti 536c80a797 docs: m11 is the repository default branch 2026-11-18 19:00:19 +00:00
arti 8c1468978a m11: make the sysroot install refuse foreign directories 2026-11-18 18:59:53 +00:00
arti 537ed27d26 m11: apply the whole-branch review fix wave 2026-11-18 18:53:29 +00:00
arti dfd13ab1c1 m11: correct the M11 docs and the debug gate comment 2026-11-18 17:48:51 +00:00
arti 7fcae6e520 m7/debug.sh: track the llvm.tms34010.bitaddr lowering (M10 aliasing fix) 2026-11-18 15:40:53 +00:00
arti 7fada4d9d7 m11: document the conventional toolchain 2026-11-18 15:37:18 +00:00
arti d705e43d41 m11: gate the single-command build end to end 2026-11-18 14:38:12 +00:00
arti 9916bbce92 m11: add the sdk sources and the sysroot installer 2026-11-18 09:42:35 +00:00
arti 12fa71d394 m11: surface and assert the CRT completion magic in tms-run and crt.sh 2026-11-18 09:33:12 +00:00
arti c6b437b738 m11: build the CRT with llc (TI-COFF object) instead of llvm-mc 2026-11-18 09:21:24 +00:00
arti 28779e1800 docs: correct the M11 CRT build path (llc, not llvm-mc) 2026-11-18 09:14:16 +00:00
arti 20789d07f3 m11: add the llvm-mc CRT with the conformance runtime contract 2026-11-18 09:11:00 +00:00
arti 41c30eee99 m11: tms-link emits loader-valid COFF without repair 2026-11-18 08:40:53 +00:00
arti e17c28a5d5 docs: M11 implementation plan 2026-11-18 08:04:10 +00:00
arti a7bbefad47 docs: M11 (Phase 3) design and post-M11 roadmap 2026-11-18 07:56:24 +00:00
arti 48091850e1 docs: record M10 completion (README + design spec) 2026-11-17 23:08:16 +00:00
arti 9694497548 m10/m7 gates: accept the protected intrinsic address form
The scale-GEP and barrier emitters now spell a bit offset as
llvm.tms34010.bitaddr (lowered to a BITADDR node) instead of a foldable add, so
the offset stays relative rather than folding to the absolute byte-read addend.

- equivalence.sh _stride: accept ADDI 192 + ADDI 32 (sum 224 bits, still
  bit-scaled) and reject the byte-scaled ADDI 28.
- pointer-o2.sh late64/late64s: accept llvm.tms34010.bitaddr(..., 24) as the
  spelling of the 24-bit addend; keep the never-192 assertion.
2026-11-17 22:56:58 +00:00
arti e609a4b84e m10 final-review: document -disable-O0-optnone in spec §7.6 ToolChain defaults 2026-11-17 21:10:18 +00:00
arti abbee9f42f m10: re-pin m5/jr.sh .text to 910 and clarify gate counts
The 850 pin was measured through the pre-fix -O2 bit-offset-aliasing and
float-constant-folding hazards; closing them costs instructions and restores
the M9 legacy value of 910, which m5/jr.sh now pins (JR count, zero-disp JA,
relaxation and MAME markers unchanged).  Make the lit counts unambiguous:
TMS34010 131 (127 CodeGen + 4 MC), clang 10 (8 CodeGen + 1 Driver + 1 Sema),
sweep command 140 = 131 + 9 clang with Sema run separately (1/1).
2026-11-17 20:36:22 +00:00
arti d73dc9c020 m10: document the debug-cycle -O2 fixes and re-verified counts
Record the BITADDR aliasing node and shared bitAddr helpers, the
pre-optimizer f32/f64 constant protection, and the m3 -fno-inline gate
choice.  Lit is 140/140 (127 CodeGen + 4 MC + 8 clang CodeGen + the
driver test) plus the Sema test.  Note the m5/jr.sh side effect: -fno-inline
reverts the M3 linked .text to 910, leaving EXPECTED_TEXT_BYTES=850 stale.
2026-11-17 20:32:29 +00:00
arti 5daf528128 m10: stop -O2 inlining branch_test's callees in the M3 round-trip
branch.c is now compiled with -fno-inline so the disassembler round-trip
still has _sumto/_max2/_lt calls to check; -O2 alone inlines them into
branch_test and constant-folds sumto(10).  -fno-inline is used instead of
-O0 because -O0 also changes the branch condition codes the round-trip pins
(sumto LT/EQ, max2 GT).
2026-11-17 17:39:36 +00:00
arti 48eb9bd248 m10: document the native clang pipeline 2026-11-17 14:25:22 +00:00
arti f4442e8f6f m10: drop unused TMS_OPT/TMS_BITADDR gate references 2026-11-17 14:25:19 +00:00
arti 848a570b4f m10: tms-clang maps to clang; gates assert the driver seam 2026-11-17 11:37:48 +00:00
arti 16a7244bf6 m10: gate native/legacy object equivalence at -O0 2026-11-17 11:12:42 +00:00
arti 2a95b71509 m10: gate bit-address pipeline idempotency 2026-11-17 10:27:40 +00:00
arti 98eea9feb0 docs: M10 (Phase 2) implementation plan 2026-11-17 09:13:37 +00:00
arti 41ff4f68d2 docs: design Phase 2 (M10) and Phase 3 (M11) 2026-11-17 09:06:50 +00:00
arti 55a0991529 m9: add the Phase 1 tms-cc driver and tms-run 2026-11-17 07:59:44 +00:00
arti d91785457f docs: m9 is the repository default branch 2026-11-17 07:44:09 +00:00
arti 4a9636690f m9: finish the final-review documentation cleanup 2026-11-17 07:42:31 +00:00
arti 95b55dec97 m9: correct the final-review documentation 2026-11-17 07:40:36 +00:00
arti 739e48d8dd M9.4: document the final M9 state and full gate sweep
Record the two-tier counts, 22 flips, four-phase divide evidence, DWARF v5/rnglists gate and the M9/M10 boundary. The Generic sweep now classifies target asm-parser 'invalid instruction mnemonic' errors as unsupported for two x86-asm tests exposed by the inline-asm r support.
2026-11-17 07:26:49 +00:00
arti 24eca1c080 m9: record the fresh two-tier full-suite counts 2026-11-17 05:18:34 +00:00
arti b2dd323e71 m9: gate padded vector zero bytes and the inline-asm memory diagnostic 2026-11-17 04:21:54 +00:00
arti 8711dee37b m9: run the i64div perf gate through the native linker 2026-11-17 04:02:46 +00:00
arti 8b6eed2510 m9: gate vector .data bytes and record inline-asm r flips 2026-11-17 03:59:10 +00:00
arti b005cd13c4 m9: correct the run_wide bounds comment and self-check list 2026-11-17 03:40:22 +00:00
arti 30f0dd688e m9: fix task 3 review findings in the i64div perf gate
Force the wide phase's signed magnitudes to stay at or above 2^32 by capping
the dividend high word with 0x80000000|(lcg & 0x7FFEFFFF) (hi(|a|) is then
0xFFFFFFFF-hi(a) in [0x10000, 0x1FFFF] >= every divisor), so all four forms
take the M8.3 two-DIVU helper; re-pin wide to 0xF56810CFEDA9D656 (the model
shows zero deviating iterations).  Add INT64_MIN magnitude cases for the
single-DIVU divisor 0xFFFFFFFF (unsigned and signed) and a negative
32-bit-magnitude divisor (2^32/-3) to the self-check, and fix the stale
'two workloads'/'both paths' gate text.
2026-11-17 03:35:37 +00:00
arti 9700b5c44f m9: close the pre-v5 and address DWARF gate gaps
Review fix round 1 for the Task 2 DWARF input gate:
- refuse pre-DWARF5 .debug_info/.debug_line in multi-object --keep-debug
  links: their DW_AT_stmt_list is a raw DW_FORM_data4/8, which the merge
  cannot rehome (I1).
- require relocations on DW_FORM_addr (DW_AT_low_pc etc.) and document
  that DW_LNE_set_address / DW_OP_addr inside expressions are not
  decoded (I2).
- require whole 4-byte relocation coverage for 8-byte fields; drop
  supplementary/alternate-file forms from the required set and explain
  why; use the line header's address size; add a need(4) unit helper
  for the standalone walkers.
- add per-walker negatives (line/rnglists/addr/str_offsets) plus an
  unrelocated DW_FORM_addr and a pre-v5 CU; distinguish a producer that
  emits no rnglists (skip) from an unreadable object (fail).
- fix the fixture docstring (--tag AB, current emission behaviour).
2026-11-17 03:34:38 +00:00
arti 8f28483868 m9: form-aware DWARF input gate and .debug_rnglists coverage
Walk .debug_info DIEs through .debug_abbrev, the DWARF v5 line-table
directory/file formats, and the .debug_rnglists/.debug_loclists entries,
and require an R-RELLONG relocation on every section-relative form and
list/address/string-offset entry.  A raw field now fails loudly instead
of being silently mis-merged; the raw CU debug_abbrev_offset is still
patched as before.

Add scripts/tests/m9/dwarf-ranges.sh: a synthetic two-TU .debug_rnglists
fixture (start_end + startx_length, offset rehoming, addr table) plus a
real -O2 -g producer case, validated through the M7 ELF wrapper with
llvm-dwarfdump.  Single-TU bytes keep the M8 layout and the default
strip is unchanged.  Add an unrelocated DW_AT_stmt_list negative to the
tms-link unit gate.
2026-11-17 03:27:15 +00:00
arti 4d2c2dce5c m9: measure the 64/32 single-DIVU divide phase
Adds a fourth equal-iteration phase to the i64div perf driver that forces
hi(N) < D (dividend high word 1..0x10000, divisor >= 0x10001), so every
division takes the new single even-destination DIVU path, and tightens the
M8.3 wide phase to hi(N) >= D so it still measures the two-DIVU helper.
New markers 11/12/13 carry the phase flag and checksum; the Lua gate polls
the phase and requires it to be measurable and materially faster than the
wide phase (1.25x), with the pinned host checksums
fast=0x000000011E6F9AB4 slow=0x00000000007512AE
wide=0xF404E965A20F6984 div32=0x00002C61C63842EE.  The self-check adds
0x1_00000000/3, 0x1_FFFFFFFF/0x10000 and -2^32/3.  The compile-only preflight
now requires the i64div.div32 block; the map check covers 16 marker cells.
2026-11-17 03:27:09 +00:00
arti dd8c5ea3ce docs: M9 scope and plan 2026-11-17 03:15:02 +00:00
arti f340d74472 m8: default the full-loader exceptions to 2ine 2026-11-17 03:14:19 +00:00
arti 2a2efd61d7 m8: two-tier conformance harness (bare by default, loader exceptions) 2026-11-16 18:13:17 +00:00
arti 66d21ebc35 m8: add the 2ine OS/2 harness path and direct-loader default 2026-11-16 16:44:38 +00:00
arti 1315df5548 docs: m8 is the repository default branch 2026-11-16 15:59:53 +00:00
arti af0c5cb617 docs: tick the M8 plan 2026-11-16 12:18:22 +00:00
arti bb78a97313 M8.4: document the final M8 state and full gate sweep 2026-11-16 12:18:04 +00:00
arti e55287f218 M8.3: harden conformance evidence and mixed-provenance report 2026-11-16 06:57:35 +00:00
arti f9b51667c4 M8.3: extend conformance codegen classes and measure the i64 64/32 divide path 2026-11-16 06:30:37 +00:00
arti 5214938b6b tms-link: merge DWARF debug info from multiple translation units 2026-11-16 03:56:43 +00:00
arti dc7de6f3a7 tms-link: address M8 Task 1 review findings
Key archive member labels/placements by member offset so two same-named members cannot overwrite each other; add a dupnamed fixture asserting distinct address ranges. Treat an empty / index as absent, require ASCII decimal sizes, validate odd-member padding and final bounds, and dedupe index entries by member offset. Document the -l/archive ordering and the unit gate's FLIB_LIB/M4_SDK prerequisite (the real-LIB case is skipped with a reason when absent).

Accept the 1990 tools' metadata section bits (0x100/0x400) on allocated sections, which the M6 flib/rts members use, while still writing classic output flags.

Add M6_LINKER=tms-link to runtime.sh and i64.sh: after GSPA, link the same M6.OBJ + flib.lib/rts.lib with tms-link, compare allocated bytes/symbols to the GSPLNK oracle, and run the same MAME marker checks. M8 native-lib now compares tms-link's raw pre-coff-check image.

Add loud-path fixtures for index lies, BSD names, duplicate / and // tables, bad/missing padding, non-ASCII sizes and -l resolution failure; strengthen the no-index exclusion test; add 1990-flag and M5_NATIVE_LINKER docs.
2026-11-16 03:23:49 +00:00
arti 29c30ddcc6 tms-link: read ar archives and extract members selectively
Implement M8.1 native .lib linking: System V !<arch> parsing (/ symbol index, // long-name table, /N references, even-byte padding, loud malformed/truncated errors), in-memory member objects labelled lib(member), and extraction in the archive's own symbol-table order driven by currently undefined globals, iterated to a fixpoint without re-extracting a member. Duplicate definitions and unresolved references fail with object/member names.

Accept archive paths and -l/-lL in the CLI, preserve layout/map/debug behavior, and let scripts/m4/run.sh pass M4_NATIVE_LIBS/M4_NATIVE_RTS archives to tms-link. Relocation addends are now applied as signed 32-bit values (needed by the termtris rts.lib link).

Tests: tms-link archive fixtures and real flib extraction, m7 archive/-l parity, m5 native termtris with tms-link+rts.lib (dis34 match), m6 i64/runtime GSPLNK gates, and scripts/tests/m8/native-lib.sh (FLIB.LIB + RTS.LIB, MAME markers, GSPLNK byte/symbol parity).
2026-11-16 02:56:44 +00:00
arti dc94931eca docs: M8 scope and plan 2026-11-16 02:31:16 +00:00
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
323 changed files with 43756 additions and 356 deletions

No files matched your search

+1994 -109
View File
File diff suppressed because it is too large. Load diff
@@ -21,7 +21,7 @@
- **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 0x3FD645B0`, `XSync 0x3FD9F6B0`. The stubs are `JAUC <address>h`; `CALLA _XOpenDisplay` reaches the ROM function.
- **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`.
@@ -588,7 +588,7 @@ Then read the VRAM pixel inside the window: the window is at `(100,100)`, 400×2
`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`/`3FD645B0`/`3FD9F6B0`;
- 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);
@@ -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.
@@ -0,0 +1,103 @@
# TMS34010 M8 — Native Archives, Multi-TU DWARF, Conformance Depth and Hardware 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/M8 boundary: make `tms-link` read the 1990 TI-COFF archives so the native path no longer needs GSPLNK for `flib`/`rts`, merge debug information from multiple translation units, deepen the conformance pass rate and performance evidence, and close out M8 with the hardware status and boundary.
**Architecture:** `tms-link` gains an `ar` reader with iterative selective extraction over its existing TI-COFF object model, then a DWARF merge stage that rehomes section-relative offsets and relocations across objects. The conformance/perf work uses the existing full-suite driver and the i64 measurement harness. The hardware harness already exists; M8.4 only runs it if the unit is available and records the result.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m8`), `tms-clang`, `llc`, `tms-link`, TI COFF and `ar` archives, the dwt loader, MAME, `dis34`, `llvm-dwarfdump`, Python 3, the conformance harness, GCC 16.2.0/c-testsuite pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M8.1–M8.4); the M7 README/ledger boundary.
## Global Constraints
- M8 baseline: compiler `llvm-tms34010` `m7` at `e924e0c86343`, project `tms-c-compiler` `m7` at `0f7353c`; work on `m8` in both repos. `m7` remains the repository default unless the user asks; no force-push and no merge into `m0`–`m7`.
- Keep every M2–M7.4 gate green, the TI all-stack ABI, the asm/GSPLNK oracle, and the native loader contract (`nreloc=0` linked image).
- `.lib` archives are test/runtime inputs; do not vendor them. The 1990 `flib.lib`/`rts.lib` are System V `ar` (`!<arch>`) with TI-COFF members.
- Debug merging must keep section-relative DWARF offsets correct; the default load image stays debug-stripped and `--keep-debug` is the tool image.
- Full-suite accounting remains one row per file; no crash/unclassified result; skips always carry a reason.
- No push until the M8 final review is clean; then push `m8`.
## Review Focus
1. **Archive correctness:** `ar` header/member parsing, long names, symbol resolution, iterative extraction, duplicate/undefined behavior, determinism, GSPLNK parity.
2. **DWARF merge correctness:** CU/abbrev/str/line/addr offset rehoming, relocations, section-relative values, dwarfdump validation, single-TU compatibility, stripped load image unchanged.
3. **Conformance honesty:** full accounting, flipped classes recorded, no hidden passes, performance measurement causal.
4. **No regression** and the final boundary accurate.
---
### Task 1: Native `.lib` linking in `tms-link`
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `tools/tms-link/tests/` archive fixtures/cases
- Modify: `scripts/m4/run.sh` (`M4_LINKER=tms-link` accepts `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`)
- Test: `tools/tms-link/tests/run.sh`, `scripts/tests/m7/link.sh`, `scripts/tests/m5/native.sh`, `scripts/tests/m6/runtime.sh`, `scripts/tests/m6/i64.sh`
**Interfaces:**
- Consumes: `ar` archives with TI-COFF members (`build/m4-sdk/FLIB.LIB`, `RTS.LIB`), the existing object reader/linker, and the M4 hook.
- Produces: archive detection/reader; selective extraction of members that define currently-undefined symbols (iterated to a fixpoint); `-l`/path CLI support; duplicate definitions/undefined symbols/unsupported members loud; a linked image with the same section/loader contract.
- [x] **Step 1: Write failing tests.** A tiny archive fixture (2–3 members, one symbol each) linked by `tms-link`; a missing-symbol and a duplicate-definition negative; a `flib`-only program (e.g. `FD$ADD`) linked without GSPLNK; the current CLI does not read archives.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Parse `!<arch>\n`, 60-byte member headers, decimal sizes, even-byte padding, `/` and `//` special members, and `/N`/name forms; reject malformed archives loudly.
- Add archive members to the link as candidate objects; extract only members that define an undefined symbol, iterating (archive semantics), never re-extracting a member; duplicate/undefined symbols fail with names.
- CLI: accept `-l LIB` and archive paths; preserve object inputs, `--entry`, layout, map, debug strip/keep.
- `scripts/m4/run.sh`: allow `M4_LINKER=tms-link` with `M4_NATIVE_LIBS`/`M4_NATIVE_RTS`; pass library paths; keep GSPLNK the default and the oracle.
- [x] **Step 4: Run green.** Unit/archive tests; the M5 native and M6 runtime/i64 links with `tms-link` + libs; GSPLNK byte/symbol parity; MAME markers; one full native run. Do not regress non-library links.
- [x] **Step 5: Commit** (project; compiler unchanged unless a target bug appears).
### Task 2: Multi-TU DWARF merging
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `scripts/tests/m8/dwarf-multi.sh`, fixtures (`scripts/m8/debug-a.c`, `debug-b.c`, entry)
- Test: `scripts/tests/m7/debug.sh` (single-TU compatibility), `llvm-dwarfdump`, MAME
**Interfaces:**
- Consumes: multiple `--keep-debug`-capable debug-bearing objects from Task 1's linker and the M7 debug sections.
- Produces: merged `.debug_info`/`.debug_abbrev`/`.debug_str`/`.debug_str_offsets`/`.debug_line`/`.debug_addr` (and related) sections with rehomed section-relative offsets/relocations across CUs; single-TU output unchanged; loud failure on unsupported shapes.
- [x] **Step 1: Write failing tests.** Two TUs with functions/lines, linked `--keep-debug`; the current linker refuses >1 debug object. Wrap the sections in the test ELF container and require `llvm-dwarfdump` to show both TUs' files/functions/lines/addresses.
- [x] **Step 2: Run red.**
- [x] **Step 3: Implement.**
- Concatenate `.debug_info`/`.debug_line`/etc. while relocating each object's section-relative contributions: `.debug_abbrev` offsets in CU headers, `.debug_str_offsets` bases, `.debug_addr` bases, `.debug_line`/`.debug_line_str` offsets, and cross-section relocations to allocated sections.
- Resolve relocations against the linked section layout; keep debug sections section-relative (paddr 0), `nreloc=0`.
- Preserve the single-debug-TU output; refuse unsupported DWARF shapes loudly.
- [x] **Step 4: Run green.** Multi-TU dwarfdump, single-TU `m7/debug.sh`, the stripped image in MAME, the M7.2 gates.
- [x] **Step 5: Commit.**
### Task 3: Conformance depth and performance
**Files:**
- Modify: the relevant target lowering/tests for fixed classes; the full-suite skip file; the perf driver if extending it
- Test: `scripts/tests/m7/full-suite.sh` (accounting), `scripts/tests/m7/c-torture.sh`/`c-testsuite.sh`, `scripts/tests/m7/i64div.sh`
**Interfaces:**
- Consumes: the M7.4 full-suite baseline (1,576 pass / 336 skip / 0 fail / 0 crash).
- Produces: additional fixed classes with flipped counts, an updated honest skip list, and at least one new measured performance path (e.g. 64/32 i64 division when the divisor fits 32 bits).
- [x] **Step 1: Pick the highest-value classes** from the retained skip classes (rotates/`cttz`/`bswap`/`blockaddress`; inline-asm constraints; one ABI return shape; one timeout/image-size case) and write failing lit/runtime tests.
- [x] **Step 2: Implement** the fixes, update the skip curation only where the class remains a genuine M8/M9 boundary, and re-run the affected full-suite rows.
- [x] **Step 3: Performance:** implement and measure the 64/32 fast path (or an equally justified path) against the existing slow path; record frames/checksums.
- [x] **Step 4: Run green** and record the new exact counts/flips.
- [x] **Step 5: Commit.**
### Task 4: Hardware status, final M8 docs, full gates, final review, push
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, the spec (M8 status)
- Test: the full M0–M8 list
- [x] **Step 1: Hardware.** If the VT1200 is available, run `VT1200_HOST=… scripts/tests/m7/hardware.sh` and record the real-unit evidence; otherwise keep `HARDWARE: DEFERRED` explicit. Do not fake a pass.
- [x] **Step 2: Docs.** Record M8.1/M8.2/M8.3 results, the final full-suite/perf counts, the remaining limitations, and the M8/M9 boundary.
- [x] **Step 3: Gates and review.** Run the full serial list, commit, final whole-branch review, then push `m8` (default stays `m7` unless asked).
---
## Execution Handoff
M8.1 makes the native path library-complete; M8.2 makes debug info multi-TU; M8.3 raises the conformance/performance surface; M8.4 closes the milestone with the hardware status and boundary. The compiler repo remains canonical for target code; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,515 @@
# TMS34010 M10 (Phase 2) — Native clang Pipeline 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:** Make `clang --target=tms34010 -c` semantically correct for pointer code at `-O0` and `-O2` with no extra flags, by moving the bit-address barrier, the post-optimizer scaling and the barrier lowering into the TMS34010 target's own pass pipeline.
**Architecture:** A minimal clang `ToolChain` supplies this target's compile defaults (freestanding, no builtins, no system includes, `-replexitval=never`). The transform logic from `tools/tms-bitaddr/bitscale.cpp` is ported to new-PM module passes in `llvm/lib/Target/TMS34010/` and registered from `TMS34010TargetMachine::registerPassBuilderCallbacks`: the barrier on the pipeline-start extension point (which also lowers immediately at `-O0`), scale/lower/final-InstCombine on optimizer-last. A `"tms.bitaddr"` module flag makes repeated application impossible, and a legacy pass in `addISelPrepare` lowers any barrier calls that still reach codegen. `llc`'s IR contract is untouched because `llc` builds no new-PM pipeline.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`), `llvm/lib/Target/TMS34010`, clang driver `ToolChains`, new pass manager (`PassBuilder` EP callbacks), module flags, lit/FileCheck, shell gates, MAME for runtime gates.
**Spec:** `docs/superpowers/specs/2026-11-17-tms34010-phase-2-3-design.md` (§7 and §7.8 are this milestone; §8 is M11, which gets its own plan after M10 is promoted because it extends the same `ToolChain` file).
## Global Constraints
- Baseline: project `m9`/`55a0991`, compiler `m9`/`4e7d48d2717e`. Cut `m10` in both repos before Task 1; never force-push.
- LLVM/Clang stay pinned at 23.1.5. Export the driver change as `patches/llvm/0005-*.patch`.
- No new user-visible flag may be required for correctness: `clang --target=tms34010 -O2 -c` works with no extra arguments.
- `llc`'s IR contract is unchanged: for `i8` GEPs the byte offset is the bit offset (`m2-late-gep.ll` → `ADDI 24`).
- `opt` behaviour is unchanged: it builds no `TargetMachine`, so no target hook fires there.
- `clang -O0 -c` objects must be **byte-identical** to the M9 path (`scripts/tms-clang` + `llc -O0`) across the corpus. `-O2` is gated on behaviour, not bytes.
- Existing gates stay green: lit **129/129**, clang **5/5**, the M2–M9 gate list, the two-tier full suite **1,618 pass / 294 skip / 0 fail / 0 crash**, i64div **88/3302/221/120** with checksums `000000011E6F9AB4` / `00000000007512AE` / `F56810CFEDA9D656` / `00002C61C63842EE`.
- TI ABI, the all-stack convention, GSPLNK as the byte/symbol oracle and the two-tier harness are unchanged.
- `-O0` and `-O2` are both first-class. A change that only holds at one level is incomplete.
- Debug locations survive every new pass: the M9.2 gates (`scripts/tests/m9/dwarf-ranges.sh`, `scripts/tests/m8/dwarf-multi.sh`, `scripts/tests/m7/debug.sh`) must pass unchanged.
## Review Focus
1. **`clang -emit-llvm` output fed to `llc`** — a user's normal two-step flow must not double-transform; llc must accept the emitted IR and produce the same code as `-c` (Task 3).
2. **Hand-written IR through `llc`** — `getelementptr i8, ptr %p, i32 24` must still be `ADDI 24`; a barrier inside llc would silently redefine every existing fixture (Task 2).
3. **`-O0` parity with the legacy path** — byte drift here means a hidden semantic change (optnone, always-inline, an extra InstCombine) rather than a benign optimization difference (Task 4).
4. **Ordinary loop code at `-O2`** — `IndVarSimplify`'s i33 exit-value rewrite must not resurface as a compile failure once the shell wrapper stops passing `-replexitval=never` (Task 1, Task 5).
5. **Debug info through the port** — barrier/lower must copy `!dbg`, or `-g -c` objects lose their line table and the DWARF gates go red (Task 2, Task 6).
---
### Task 1: TMS34010 `ToolChain` with the target's compile defaults
**Files:**
- Create: `clang/lib/Driver/ToolChains/TMS34010.h`
- Create: `clang/lib/Driver/ToolChains/TMS34010.cpp`
- Modify: `clang/lib/Driver/ToolChains/CMakeLists.txt`
- Modify: `clang/lib/Driver/Driver.cpp` (arch switch in `Driver::getToolChain`, after the `msp430` case at ~line 7286)
- Test: `clang/test/Driver/tms34010-defaults.c`
**Interfaces:**
- Consumes: `toolchains::BareMetal` (`clang/lib/Driver/ToolChains/BareMetal.h`), whose ctor is `BareMetal(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)`.
- Produces: `class TMS34010ToolChain : public BareMetal` with the same ctor, overriding `void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const`, which appends `-ffreestanding`, `-fno-builtin`, `-mllvm`, `-replexitval=never` and then calls `BareMetal::addClangTargetOptions`.
- [ ] **Step 1: Write the failing driver test**
```c
// clang/test/Driver/tms34010-defaults.c
// RUN: %clang -### --target=tms34010 -c %s 2>&1 | FileCheck %s --check-prefix=FLAGS
// RUN: %clang -### --target=tms34010 -c %s 2>&1 | FileCheck %s --check-prefix=NOSYS
// FLAGS: "-cc1" {{.*}}-ffreestanding
// FLAGS-SAME: -fno-builtin
// FLAGS-SAME: "-mllvm" "-replexitval=never"
// NOSYS-NOT: "-internal-isystem"
int f(int n) { return n + 1; }
```
- [ ] **Step 2: Run it red**
Run: `ninja -C build/llvm-clean-build clang FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/Driver/tms34010-defaults.c`
Expected: FAIL — the `-###` line has no `-ffreestanding` / `-mllvm -replexitval=never`.
- [ ] **Step 3: Implement the ToolChain**
`TMS34010.h` subclasses `BareMetal` with the forwarding ctor and the `addClangTargetOptions` override. `TMS34010.cpp` pushes the four default arguments in this order (`-ffreestanding`, `-fno-builtin`, `-mllvm`, `-replexitval=never`) before delegating to the base. In `Driver.cpp`, insert after the `msp430` case:
```cpp
case llvm::Triple::tms34010:
TC = std::make_unique<toolchains::TMS34010ToolChain>(*this, Target, Args);
break;
```
Add the header to `Driver.cpp`'s include block and `TMS34010.cpp` to `ToolChains/CMakeLists.txt` (`add_clang_library(clangDriver ...)`).
- [ ] **Step 4: Run it green, plus the loop case**
Run: `ninja -C build/llvm-clean-build clang FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/Driver/tms34010-defaults.c`
Expected: PASS.
Then compile the shape that fails today, with no extra flags:
```sh
printf 'int sumto(int n){int s=0;for(int i=0;i<=n;i++)s+=i;return s;}\n' > /tmp/opencode/m10-loop.c
build/llvm-clean-build/bin/clang --target=tms34010 -O2 -c /tmp/opencode/m10-loop.c -o /tmp/opencode/m10-loop.o
```
Expected: exit 0, object written (before this task: `fatal error: TMS34010: i33 multiply (umul_lohi shape) reached code generation`).
- [ ] **Step 5: Commit**
```bash
git -C build/llvm-clean add clang/lib/Driver/ToolChains/TMS34010.h \
clang/lib/Driver/ToolChains/TMS34010.cpp \
clang/lib/Driver/ToolChains/CMakeLists.txt \
clang/lib/Driver/Driver.cpp clang/test/Driver/tms34010-defaults.c
git -C build/llvm-clean commit -m "tms34010: add the driver ToolChain with the target compile defaults"
```
---
### Task 2: Bit-address passes and pipeline hooks (`-O0` and `-O2` correct)
**Files:**
- Create: `llvm/lib/Target/TMS34010/TMS34010BitAddr.h`
- Create: `llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp`
- Modify: `llvm/lib/Target/TMS34010/CMakeLists.txt`
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.h`
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp`
- Test: `clang/test/CodeGen/TMS34010/bitaddr-o0.c`, `clang/test/CodeGen/TMS34010/bitaddr-o2.c`
**Interfaces:**
- Consumes: `tools/tms-bitaddr/bitscale.cpp` as the behavioural reference (modes `--bitptr`, `--scale`, `--lower-bitptr`); `OptimizationLevel` from the pipeline-start callback.
- Produces: free functions `bool tms34010BitPtr(Module &M, OptimizationLevel Level)`, `bool tms34010ScaleGEP(Module &M)`, `bool tms34010LowerBitPtr(Module &M)`; new-PM passes `TMS34010BitPtrPass(OptimizationLevel)`, `TMS34010ScaleGEPPass`, `TMS34010LowerBitPtrPass`, each `PassInfoMixin` with `PreservedAnalyses run(Module &M, ModuleAnalysisManager &)`; `void TMS34010TargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) override`.
- [ ] **Step 1: Write the failing asm tests**
```c
// clang/test/CodeGen/TMS34010/bitaddr-o0.c
// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -S -o - %s | FileCheck %s
struct S { char c; int i; };
int load_i(int *p) { return p[1]; }
int load_s(struct S *p) { return p[1].i; }
int load_b(char *p) { return p[4]; }
// CHECK-LABEL: _load_i:
// CHECK: ADDI 32, A{{[0-9]+}}
// CHECK-NOT: ADDI 4, A
// CHECK-LABEL: _load_s:
// CHECK: ADDI 40, A{{[0-9]+}}
// CHECK-LABEL: _load_b:
// CHECK: ADDI 32, A{{[0-9]+}}
```
```c
// clang/test/CodeGen/TMS34010/bitaddr-o2.c
// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -S -o - %s | FileCheck %s
int load_i(int *p) { return p[1]; }
int sumto(int n) { int s = 0; for (int i = 0; i <= n; i++) s += i; return s; }
// CHECK-LABEL: _load_i:
// CHECK: ADDI 32, A{{[0-9]+}}
// CHECK-NOT: ADDI 4, A
// CHECK-LABEL: _sumto:
```
- [ ] **Step 2: Run them red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-o0.c build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-o2.c`
Expected: FAIL — `ADDI 4` instead of `ADDI 32` (`_load_s` likewise off by the scale factor).
- [ ] **Step 3: Port the barrier pass**
In `TMS34010BitAddr.cpp`, implement `tms34010BitPtr` and `TMS34010BitPtrPass` by porting the `--bitptr` mode of `tools/tms-bitaddr/bitscale.cpp` **verbatim in behaviour**: the same `@__tms_bitptr(i32 bitoff, ptr base)` declaration with `nounwind readnone`, the same constant-expression-GEP rewrite to `inttoptr(add(ptrtoint, 8*off))`, the same declaration/body validation error, and every replaced instruction copies its `!dbg` location. Keep the `--normalize` mode out (nothing calls it).
- [ ] **Step 4: Port the lowering pass**
Implement `tms34010LowerBitPtr` and `TMS34010LowerBitPtrPass` from the `--lower-bitptr` mode: replace each call with `inttoptr(add(ptrtoint base, bitoff))` and drop the declaration; copy `!dbg` from the call. Then confirm the port compiles and is reachable (registration comes in Step 6):
Run: `ninja -C build/llvm-clean-build clang llc FileCheck`
Expected: clean build, no new warnings in the target.
- [ ] **Step 5: Port the scaling pass**
Implement `tms34010ScaleGEP`: multiply only the indices of GEPs that reach it (optimizer-created byte GEPs), keep the `switch.table.` special case (`isSwitchTableBase` → shift 3 even when `GepShift == 0`), and keep the `0 + x` / `x * 1` folding.
- [ ] **Step 6: Register the pipeline hooks**
In `TMS34010TargetMachine.cpp`:
```cpp
void TMS34010TargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
PB.registerPipelineStartEPCallback(
[](ModulePassManager &MPM, OptimizationLevel Level) {
MPM.addPass(TMS34010BitPtrPass(Level));
if (Level == OptimizationLevel::O0) {
MPM.addPass(TMS34010LowerBitPtrPass());
}
});
PB.registerOptimizerLastEPCallback(
[](ModulePassManager &MPM, OptimizationLevel,
ThinOrFullLTOPhase) {
MPM.addPass(TMS34010ScaleGEPPass());
MPM.addPass(TMS34010LowerBitPtrPass());
MPM.addPass(InstCombinePass(InstCombineOptions()
.setVerifyFixpoint(false)));
});
}
```
`-O0` deliberately adds no `scale` (no optimizer runs, so no optimizer-created GEPs) and no `InstCombine` — that is what keeps `-O0` byte-identical to the legacy path (Task 4). Declare the override in `TMS34010TargetMachine.h` and add `TMS34010BitAddr.cpp` to the target's `CMakeLists.txt`.
- [ ] **Step 7: Run both asm tests green**
Run: `ninja -C build/llvm-clean-build clang llc FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-o0.c build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-o2.c`
Expected: PASS at both levels.
- [ ] **Step 8: Prove `llc`'s contract is unchanged**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m2-late-gep.ll`
Expected: PASS — still `ADDI 24`, not `ADDI 192`.
- [ ] **Step 9: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010BitAddr.h \
llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp \
llvm/lib/Target/TMS34010/CMakeLists.txt \
llvm/lib/Target/TMS34010/TMS34010TargetMachine.h \
llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp \
clang/test/CodeGen/TMS34010/bitaddr-o0.c \
clang/test/CodeGen/TMS34010/bitaddr-o2.c
git -C build/llvm-clean commit -m "tms34010: move the bit-address barrier into the clang pipeline"
```
End-to-end native proof (compile → link → MAME) lands in Task 5, when
`tms-clang` routes every harness through native clang; at this point only the
asm-level tests can observe the pipeline directly.
---
### Task 3: State machine, idempotency and the codegen safety net
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp` (module-flag transitions)
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`addISelPrepare` legacy pass)
- Create: `scripts/tests/m10/bitaddr-idempotent.sh`
- Test: `llvm/test/CodeGen/TMS34010/m10-state1-lower.ll`
**Interfaces:**
- Consumes: the passes from Task 2.
- Produces: module flag `"tms.bitaddr"` with values `1` (barriered, not lowered) and `2` (lowered/final); `class TMS34010LowerBitPtrLegacyPass : public ModulePass` in `TMS34010BitAddr.h` for the legacy codegen pipeline; `TMS34010PassConfig::addISelPrepare()` override that adds it before `TargetPassConfig::addISelPrepare()`.
- [ ] **Step 1: Write the failing state-1 test**
```llvm
; llvm/test/CodeGen/TMS34010/m10-state1-lower.ll
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
@__tms_bitptr = external nounwind readnone
!llvm.module.flags = !{!0}
!0 = !{i32 4, !"tms.bitaddr", i32 1}
define ptr @advance(ptr %p) {
%q = call ptr @__tms_bitptr(i32 32, ptr %p)
ret ptr %q
}
; CHECK-LABEL: _advance:
; CHECK: ADDI 32, A{{[0-9]+}}
; CHECK-NOT: CALLA
```
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m10-state1-lower.ll`
Expected: FAIL — the call is not lowered, so the asm contains `CALLA __tms_bitptr`.
- [ ] **Step 3: Implement the flag transitions**
`TMS34010BitPtrPass` sets `"tms.bitaddr"` to `1` when absent and does nothing when the value is `1` or `2` (module-level check first, before touching any instruction). `TMS34010LowerBitPtrPass` lowers only when the value is `1`, then sets it to `2`; with no flag it is a no-op. Write the value with `M.addModuleFlag(ModFlagBehavior::Override, "tms.bitaddr", ConstantInt::get(Type::getInt32Ty(M.getContext()), 1))` — `Override` so a second write replaces the value instead of erroring.
- [ ] **Step 4: Implement the codegen safety net**
Add `class TMS34010LowerBitPtrLegacyPass : public ModulePass` (in `TMS34010BitAddr.h`, defined in the `.cpp`) whose `runOnModule` calls `tms34010LowerBitPtr`. In `TMS34010PassConfig`, override:
```cpp
void addISelPrepare() override {
addPass(new TMS34010LowerBitPtrLegacyPass());
TargetPassConfig::addISelPrepare();
}
```
- [ ] **Step 5: Run the state-1 test green**
Run: `ninja -C build/llvm-clean-build llc clang FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m10-state1-lower.ll`
Expected: PASS.
- [ ] **Step 6: Write the end-to-end idempotency gate**
`scripts/tests/m10/bitaddr-idempotent.sh` (shell, `set -eu`, `ROOT=$(cd "$(dirname "$0")/../../.." && pwd)`):
1. Compile a pointer file at `-O0` to IR: `clang --target=tms34010 -O0 -S -emit-llvm -o run1.ll src.c`.
2. Assert `run1.ll` contains `"tms.bitaddr", i32 2` and no `__tms_bitptr`.
3. Re-run the same command to `run2.ll` and `cmp` — identical.
4. `llc -march=tms34010 -O0 -filetype=asm run1.ll` and assert `ADDI 32` for `p[1]`.
5. Compile the same source with `clang --target=tms34010 -O0 -c` and validate the object: `python3 scripts/m4/coff-check.py native.o` must exit 0 (magic and section table valid).
- [ ] **Step 7: Run the idempotency gate**
Run: `scripts/tests/m10/bitaddr-idempotent.sh`
Expected: `m10 bitaddr idempotent: PASS`.
- [ ] **Step 8: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010BitAddr.h \
llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp \
llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp \
llvm/test/CodeGen/TMS34010/m10-state1-lower.ll
git -C build/llvm-clean commit -m "tms34010: make the bit-address pipeline idempotent"
git add scripts/tests/m10/bitaddr-idempotent.sh
git commit -m "m10: gate bit-address pipeline idempotency"
```
---
### Task 4: Static-variadic guard and the `-O0` equivalence gate
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp` (guard inside the barrier pass)
- Create: `scripts/tests/m10/legacy-tms-clang` (exact copy of the M9 script, `git show m9:scripts/tms-clang`)
- Create: `scripts/tests/m10/equivalence.sh`
- Test: `clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c`
**Interfaces:**
- Consumes: `TMS34010BitPtrPass(OptimizationLevel Level)` from Task 2.
- Produces: the diagnostic `error: static variadic definition '<name>' loses its '...' arguments at -O2 (dead argument elimination); remove 'static' or compile with -O0` emitted at `-O2` only; `scripts/tests/m10/equivalence.sh` returning non-zero with a per-file diff list.
- [ ] **Step 1: Write the failing guard test**
```c
// clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c
// RUN: not %clang_cc1 -triple tms34010-unknown-none -O2 -emit-obj %s -o /dev/null 2>&1 | FileCheck %s
// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -emit-obj %s -o /dev/null
// CHECK: static variadic definition 'sum' loses its '...' arguments
static int sum(int n, ...) { int *p = &n; return p[0] + p[1]; }
int call(void) { return sum(1, 2); }
```
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c`
Expected: FAIL — compiles silently (the guard still lives in the shell script).
- [ ] **Step 3: Move the guard into the barrier pass**
Port the `awk` guard's condition exactly: at `Level != O0`, scan each function definition; if it has `internal`/`private` linkage AND a variadic signature AND no `llvm.va_start`/`va_arg` use, report that diagnostic with the function's name and fail compilation (`report_fatal_error` or a diagnostic the driver prints as `error:`). Keep the `-O0` exemption.
- [ ] **Step 4: Run it green**
Run: `ninja -C build/llvm-clean-build clang FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c`
Expected: PASS (both RUN lines).
- [ ] **Step 5: Create the legacy reference copy**
Run: `git show m9:scripts/tms-clang > scripts/tests/m10/legacy-tms-clang && chmod +x scripts/tests/m10/legacy-tms-clang`
Expected: byte-identical to the M9 script; it is the oracle for the rest of the milestone.
- [ ] **Step 6: Write the equivalence gate**
`scripts/tests/m10/equivalence.sh` compiles each corpus file twice and compares objects:
- native: `clang --target=tms34010 -O0 -c "$f" -o native.o`
- legacy: `scripts/tests/m10/legacy-tms-clang -O0 -o legacy.ll "$f"` then `llc -march=tms34010 -O0 -filetype=obj legacy.ll -o legacy.o`
- require `cmp native.o legacy.o`.
Corpus: every `*.c` in `scripts/m4`, `scripts/m5`, `scripts/m6` plus `scripts/tests/m5/conformance/shim.c` and `heap.c`. Run the whole set at `-O0`, then at `-O0 -g`, and report per-file pass/fail with a summary line `m10 equivalence: pass=<n> fail=<n>`.
Then a second phase in the same script covers `-O2`, where byte identity is not
expected: compile a heredoc fixture at `-O2` and FileCheck its asm shapes —
`p[1]` for `int*` (`ADDI 32`), a struct-array stride, a `switch` table load and
an aggregate return — so the scaling pass is pinned on optimizer-created GEPs.
- [ ] **Step 7: Run the gate, then prove it discriminates**
Run: `scripts/tests/m10/equivalence.sh`
Expected: `fail=0`.
Then temporarily run the native side at `-O2` (edit a copy, not the gate) and confirm the comparison reports failures — proving the gate is not vacuous. Revert the copy.
- [ ] **Step 8: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010BitAddr.cpp \
clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c
git -C build/llvm-clean commit -m "tms34010: reject static variadics in the pre-optimizer barrier"
git add scripts/tests/m10/legacy-tms-clang scripts/tests/m10/equivalence.sh
git commit -m "m10: gate native/legacy object equivalence at -O0"
```
---
### Task 5: `tms-clang` becomes a wrapper; gates move to the new seam
**Files:**
- Modify: `scripts/tms-clang` (replace the body with the flag mapper)
- Modify: `scripts/tests/m4/mul.sh:29`
- Modify: `scripts/tests/m5/jr.sh:114-120`
- Modify: `scripts/tests/m5/policy.sh:51-70`
- Modify: `scripts/tests/m3/run.sh` (the `TMS_OPT` wrapper it installs)
- Test: those four gates plus `scripts/tests/m10/equivalence.sh`
**Interfaces:**
- Consumes: the `ToolChain` defaults (Task 1) and the pipeline hooks (Task 2, Task 3).
- Produces: `scripts/tms-clang` with the unchanged CLI (`-O0|-O2|-g|-I dir -o OUT.ll IN.c`) that maps to `clang --target=tms34010 [-O0|-O2] [-g] [-I dir] -S -emit-llvm -o OUT.ll IN.c` and no longer invokes `$TMS_OPT` or `$TMS_BITADDR`.
- [ ] **Step 1: Record the current gate behaviour as the baseline**
Run: `scripts/tests/m4/mul.sh && scripts/tests/m5/jr.sh && scripts/tests/m5/policy.sh && scripts/tests/m3/run.sh`
Expected: all PASS on the pre-rewrite script (this is the behaviour that must survive).
- [ ] **Step 2: Rewrite `scripts/tms-clang`**
Keep the argument parser, `set -eu`, and the `TMS_CLANG`/`TMS_CLANG_EXTRA_FLAGS` overrides; delete the temp-dir pipeline, the awk guard (now in the pass), the `run_bitaddr` calls and both `opt` invocations. The whole script becomes the argument parse plus one `exec` of clang with `-S -emit-llvm`.
- [ ] **Step 3: Repoint the four gates**
- `m4/mul.sh`: replace the `grep -q -- '-replexitval=never' scripts/tms-clang` check with an assertion on the driver seam, e.g. `"$TMS_CLANG" -### --target=tms34010 -O2 -c ... 2>&1 | grep -q -- '-replexitval=never'`.
- `m5/jr.sh`: drop the `OPT_NOREPLEXIT` wrapper and call `tms-clang -O2` directly; keep the same final assertion on the emitted IR/asm.
- `m5/policy.sh`: replace the `opt-trace` harness with the `-###` check plus the existing final-IR/asm assertions for the switch-table and loop shapes.
- `m3/run.sh`: same treatment for whatever `TMS_OPT` wrapper it installs.
Each edit must assert the same invariant, just observed at the driver seam instead of inside the script.
- [ ] **Step 4: Run the four gates green**
Run: `scripts/tests/m4/mul.sh && scripts/tests/m5/jr.sh && scripts/tests/m5/policy.sh && scripts/tests/m3/run.sh`
Expected: all PASS, with the `-replexitval=never` policy still asserted.
- [ ] **Step 5: Prove native end-to-end**
With `tms-clang` now mapping to clang, the conformance harness compiles with
native clang. Write a small pointer program and run it through the harness:
```sh
cat > /tmp/opencode/m10-ptr.c <<'EOF'
#include <stdio.h>
int main(void) {
int a[3] = {10, 20, 30};
int *p = a;
printf("%d %d\n", p[2], (int)(p + 2 - p));
return 0;
}
EOF
scripts/tests/m5/conformance/run.sh --id m10-ptr --mode native \
--expect 'status=0;stdout=30 2\n' /tmp/opencode/m10-ptr.c
```
Expected: `PASS m10-ptr` (status 0, stdout `30 2`). The full breadth proof is the
suite in Task 6, which now also compiles through native clang.
- [ ] **Step 6: Re-run the equivalence gate against the new wrapper**
Run: `scripts/tests/m10/equivalence.sh`
Expected: `fail=0` — the oracle copy is unchanged, so this proves the wrapper
produces the same IR the old script did.
- [ ] **Step 7: Commit**
```bash
git add scripts/tms-clang scripts/tests/m4/mul.sh scripts/tests/m5/jr.sh \
scripts/tests/m5/policy.sh scripts/tests/m3/run.sh
git commit -m "m10: tms-clang maps to clang; gates assert the driver seam"
```
---
### Task 6: Full gate sweep, docs, patch export, promote `m10`
**Files:**
- Modify: `README.md` (M10 status, `tms-clang` description, gate list)
- Modify: `build/llvm-clean/TMS34010.md` (M10 section, pipeline description)
- Modify: `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` (M10 acceptance met)
- Create: `patches/llvm/0005-tms34010-toolchain.patch`
- Test: the full M0–M10 gate list
- [ ] **Step 1: Export the driver patch**
Run: `git -C build/llvm-clean diff m9..m10 -- clang/ > patches/llvm/0005-tms34010-toolchain.patch`
Expected: the patch contains only `ToolChains/TMS34010.{h,cpp}`, `ToolChains/CMakeLists.txt`, `Driver.cpp` and the driver test.
- [ ] **Step 2: Run the compiler tests**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010 build/llvm-clean/llvm/test/MC/TMS34010 build/llvm-clean/clang/test/CodeGen/TMS34010 build/llvm-clean/clang/test/Driver/tms34010-defaults.c`
Expected: 129 TMS34010 lit tests plus the new ones, and 5 clang tests plus the new ones, all PASS.
- [ ] **Step 3: Run the M9/M10 behaviour gates**
Run: `scripts/tests/m10/equivalence.sh && scripts/tests/m10/bitaddr-idempotent.sh && tools/tms-bitaddr/tests/run.sh && scripts/tests/m9/dwarf-ranges.sh && scripts/tests/m8/dwarf-multi.sh && scripts/tests/m7/debug.sh`
Expected: all PASS; DWARF output unchanged.
- [ ] **Step 4: Run the full suite and the divide measurement**
Run: `scripts/tests/m7/full-suite.sh --corpus all --work build/m10-bare`
Expected: `all total=1912 pass=1618 skip=294 fail=0 crash=0`.
Every row now compiles through native clang, because `tms-clang` is the thin
wrapper — so this run is the breadth proof for the new pipeline, not just a
regression check.
Run: `scripts/tests/m7/i64div.sh`
Expected: `fast=88 slow=3302 wide=221 div32=120`, ratios 37.5/14.9/1.8, all four checksums exact.
- [ ] **Step 5: Run the remaining M0–M8 gates**
Run the serial list from `README.md`'s gate section (M0, M2–M8 native/object/JR/MMTM/policy/robust/spike/i64/float/varargs/bitfield/aggregate/runtime, the curated c-torture and c-testsuite tiers, `hardware.sh` → `HARDWARE: DEFERRED`).
Expected: every gate PASS; hardware DEFERRED.
- [ ] **Step 6: Update the docs**
Record in `README.md`, `TMS34010.md` and the spec: M10 complete, `clang --target=tms34010 -c` now correct with no flags, the ToolChain defaults, the pipeline hooks and state flag, the `-O0` byte-identity result, the new gates, and the M10/M11 boundary (M11 = CRT/headers/`libtms.a`/sysroot/link job).
- [ ] **Step 7: Commit, review, push, promote**
```bash
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "docs: record the M10 native pipeline"
git add README.md docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md \
patches/llvm/0005-tms34010-toolchain.patch
git commit -m "m10: document the native clang pipeline"
```
Then run the M10 whole-branch review. Only after it is clean: push `m10` in both repositories, set it as the default branch on both remotes, and update the README's default-branch language. `m9` stays as the previous snapshot.
---
## Execution Handoff
M10 ends with `clang --target=tms34010 -O2 -c` correct for pointer code and for ordinary loops, `-O0` objects byte-identical to the M9 path, and every existing gate green. M11 (Phase 3: CRT, headers, `libtms.a`, sysroot, `tms-link` link job) is planned separately once M10 is promoted, because it extends the `ToolChain` file created in Task 1.
@@ -0,0 +1,101 @@
# TMS34010 M9 — Conformance Classes, Debug Depth and Performance 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:** Raise the full-suite pass rate with the highest-value remaining classes, close the M8 DWARF/linker caveats, add a measured 64/32 divide fast path, and close M9 with the hardware status and boundary.
**Architecture:** Vector `.data` becomes another recursive aggregate in both the raw and object emitters; the target supplies an inline-asm register resolver for the A-register classes. The linker gains a form-aware DWARF input check (or walker) plus `.debug_rnglists` merging. The i64 outliner adds a single-DIVU 64/32 path when the quotient fits. The bare conformance tier and the full-loader list remain the two-tier harness.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`, branch `m9`), `tms-clang`, `llc`, `tms-link`, TI COFF, the dwt loader, MAME, `llvm-dwarfdump`, Python 3, the M8 two-tier harness and pins.
**Spec:** `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md` §8 (M9.1–M9.4); the M8 README/ledger boundary.
## Global Constraints
- M9 baseline: compiler `m8`/`e3ad91edd130`, project `m8`/`f340d74`; work on `m9`. The default is promoted to `m9` only after the final review.
- Keep every M2–M8.4 gate green, the TI all-stack ABI, the asm/GSPLNK oracle, the native loader contract, and the two-tier harness.
- `M5_CONFORMANCE_BARE=1` remains the conformance default; full-loader exceptions need a reason in `full-suite.full-loader`.
- Vector and inline-asm changes must be tested at `-O0` and `-O2`; unsupported shapes stay loud.
- DWARF merging must stay section-relative and stripped-image compatible; single-TU output remains byte-compatible with M8.
- Full-suite accounting remains one row per file; no crash/unclassified result; skips always carry a reason.
- No push until the M9 final review is clean; then push `m9`, promote it, and update the README.
## Review Focus
1. **Vector bytes:** exact element order/padding for integer/fp vectors, packed widths, aggregate zero, raw and object paths; no over-read/write; existing scalar/record output unchanged.
2. **Inline asm:** constraint mapping for i16/i32, clobbers, output/input ties, unsupported constraints loud; `-O0`/`-O2`.
3. **DWARF:** form walker completeness, rnglists merging, offset rehoming, single-TU compatibility, dwarfdump and stripped MAME.
4. **Divide:** 64/32 condition and quotient-fit, magnitudes/sign, `INT64_MIN`, divide-by-zero, measured frames/checksums, no M8 path regression.
5. **No M2–M8.4 regression**, two-tier counts, and the final boundary.
---
### Task 1: Vector `.data` and inline-asm `r` constraints
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010AsmPrinter.cpp` (raw/object vector initializers)
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.{h,cpp}` (inline-asm register resolver)
- Create/modify: `llvm/test/CodeGen/TMS34010/m9-vector-data.ll`, `m9-inline-asm.ll`
- Test: `scripts/tests/m7/data.sh`, the full-suite vector/inline-asm rows, M6/M5 gates
**Interfaces:**
- Consumes: the recursive `.data` emitter and the A-register classes (`ARegs`, `ARegsEven`, …).
- Produces: exact vector initializer bytes (integer/fp element vectors, aggregate zero, byte-multiple only) in raw and object modes; `getRegForInlineAsmConstraint` mapping `r`/`=r` (and documented accepted subsets) to the target register classes; unsupported vectors/constraints loud.
- [ ] **Step 1: Write failing tests.** `m9-vector-data.ll` with `<2 x i32>`, `<4 x i16>`, an fp vector if supported, and a vector zero; `data.sh` raw/object bytes. `m9-inline-asm.ll` with `r` input/output at `-O0`/`-O2`. Current emitter rejects vectors; inline asm fails to allocate.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement.** Vector constants as ordered element bytes with exact alloc size; `ConstantAggregateZero` vector zero; keep unsupported widths/types loud. Implement the inline-asm resolver and clobber handling; reject unsupported constraints with a named error.
- [ ] **Step 4: Run green.** Lit, data.sh, and the affected full-suite rows (bare/full-loader as appropriate); record flips.
- [ ] **Step 5: Commit** (compiler + project gates/tests).
### Task 2: DWARF form walker and `.debug_rnglists`
**Files:**
- Modify: `tools/tms-link/tms-link`, `tools/tms-link/tmscoff.py`
- Create: `scripts/tests/m9/dwarf-ranges.sh`, fixtures
- Test: `scripts/tests/m8/dwarf-multi.sh`, `scripts/tests/m7/debug.sh`, `llvm-dwarfdump`
**Interfaces:**
- Consumes: M8's multi-TU debug merge and the current CU-abbrev-only raw patch.
- Produces: a form-aware check/walker that rejects (or correctly patches) unrelocated section-relative fields, and `.debug_rnglists` concatenation/rehoming with a fixture; single-TU bytes unchanged.
- [ ] **Step 1: Write failing tests.** A synthetic object with an unrelocated `DW_AT_stmt_list`/`strp` (or a documented rejection), and a multi-TU `.debug_rnglists` fixture; current code silently assumes relocations.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement** the form walk (or input gate) and rnglists merge; keep the loud paths.
- [ ] **Step 4: Run green.** `dwarf-ranges.sh`, `dwarf-multi.sh`, `m7/debug.sh`, stripped MAME.
- [ ] **Step 5: Commit.**
### Task 3: 64/32 single-DIVU fast path
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010TargetMachine.cpp` (`lowerDivRem`)
- Create/modify: `llvm/test/CodeGen/TMS34010/m9-i64div-64-32.ll`
- Modify: `scripts/m7/i64div-perf.c`, `scripts/tests/m7/i64div.sh`
- Test: `scripts/tests/m6/i64.sh`, `m6/runtime.sh`, `i64div.sh`
**Interfaces:**
- Consumes: the M8 fast/wide/loop CFG and the target `DIVU` 64-bit pair.
- Produces: when the divisor's high word is zero and the quotient fits 32 bits (e.g. `hi(N) < D`), a single even-destination `DIVU` fast path; otherwise the M8 two-DIVU/loop path. Signed normalization and fixups unchanged.
- [ ] **Step 1: Write failing tests.** A 64/32 case with `hi(N) < D` requiring one `DIVU`; the M8 wide cases still two; perf phase measured.
- [ ] **Step 2: Run red.**
- [ ] **Step 3: Implement** the single-DIVU branch; preserve `INT64_MIN`, divide-by-zero UB and signs.
- [ ] **Step 4: Run green.** Lit, M6 i64/runtime, i64div measurements; record frames/checksums.
- [ ] **Step 5: Commit.**
### Task 4: Hardware status, final M9 docs, full gates, review, promote
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, spec (M9 status)
- Test: the full M0–M9 list
- [ ] **Step 1: Hardware.** Run `VT1200_HOST=… scripts/tests/m7/hardware.sh` if a unit is available; otherwise keep `HARDWARE: DEFERRED`.
- [ ] **Step 2: Docs.** Record M9.1/M9.2/M9.3 results, flips, perf, the final two-tier counts and the M9/M10 boundary; update the gate commands.
- [ ] **Step 3: Gates and review.** Run the full serial list, commit, final whole-branch review, then push `m9`.
- [ ] **Step 4: Promote.** Set `m9` as the repository default on both remotes (per the standing policy), update the README/docs default language, and verify `refs/heads/m9` is HEAD.
---
## Execution Handoff
M9 closes the highest-value conformance classes, the DWARF future-producer and rnglists caveats, and adds a measured 64/32 divide fast path. The remaining classes (`blockaddress`, nested functions, VLAs, sret/aggregate/variadic/float returns, libm), broader hardware/link depth and any further performance work are M10. The compiler repo is canonical; the project holds the linker, harness, plans and gates.
@@ -0,0 +1,311 @@
# TMS34010 M11 (Phase 3) — Conventional Toolchain 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:** Make `clang --target=tms34010 hello.c -o hello` build a loader-valid image that `tms-run` can execute — CRT, headers and `libtms` found through a resource-directory sysroot, linked by `tms-link` through a real driver link job, with no wrapper and no project variables.
**Architecture:** `sdk/` holds the sources (CRT IR, shim, heap, headers, committed vendor archives); `scripts/tms-sdk` builds `crt0.o` with `llc` and `libtms.a` with `llvm-ar`, then installs everything plus the `tms-link`/`tmscoff.py` pair into `<resource-dir>/tms34010-unknown-none/{include,lib,bin}`. `TMS34010ToolChain` grows sysroot discovery and a `TMS34010Linker` Tool that maps driver flags onto `tms-link`. `tms-link` must emit loader-valid COFF on its own, because the production path no longer runs `coff-check.py --repair`.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`), clang driver `ToolChains/TMS34010.*`, `llc`, `llvm-ar`, `tools/tms-link` (Python + `tmscoff.py`), TMS34010 GSPA assembly, TI-COFF, MAME + the dwt loader, shell gates.
**Spec:** `docs/superpowers/specs/2026-11-18-tms34010-m11-conventional-toolchain-design.md` (§8 is this milestone; §11 is the roadmap, not this plan).
## Global Constraints
- Baseline: project `m10`/`a7bbefa`, compiler `m10`/`7fc2ac37b5ad`. Cut `m11` in both repos before Task 1; never force-push.
- LLVM/Clang stay pinned at 23.1.5. All driver work stays inside `clang/lib/Driver/ToolChains/TMS34010.{h,cpp}` plus its two registration lines; patch `0005` grows, nothing else.
- The driver must never bake in a checkout path: discovery is `--tms-sysroot=`, then `--sysroot`/`-isysroot`, then `<resource-dir>/tms34010-unknown-none`.
- M10's contract must not regress: `clang --target=tms34010 -c` stays correct at `-O0`/`-O2`, and `-O0` objects stay byte-identical to the M9 path (`scripts/tests/m10/equivalence.sh` is the gate).
- The CRT/runtime contract is fixed: status `01B00000`, out-len `01B00020`, magic `01B00040` = `0x434F4E46`, err-len `01B00060`, output `01B10000`, error `01B30000` (16 KiB each), `_cstack` 32768 bits (4096 bytes) at 16-bit alignment, `_conformance_argv` 64 bits, `_start` entry; `libtms`'s `exit`/`abort` publish and spin.
- Link defaults: `--entry _start --text 018A0000 --bss 01A00000 --prog-len 40000h --ram-len 80000h`.
- `coff-check.py --repair` leaves the production path; `tms-link` emits valid images unaided.
- Vendor `flib.lib`/`rts.lib` are committed and gated against freshly extracted copies.
- Existing gates stay green: lit suites, the serial M0–M10 list, the two-tier suite **1,618 pass / 294 skip / 0 fail / 0 crash**, i64div `88/3302/221/120` with the same four checksums, `HARDWARE: DEFERRED`.
- No force-push, no default-branch change before the whole-branch review.
## Review Focus
1. **A fresh shell after one setup command** — `clang --target=tms34010 hello.c -o hello` must work with no `M4_*`, `TMS_*`, `PATH` or include entries, from a directory outside the repo (Task 5).
2. **Link-reduction knobs** — `-nostdlib`, `-nostartfiles`, `-nodefaultlibs` must each drop exactly their part and still link (Task 4).
3. **Missing pieces are diagnosed, not guessed** — no sysroot, no installed `tms-link`, no `python3` must each name the cause and `scripts/tms-sdk`, never a raw linker error (Task 4).
4. **CRT contract** — argv vector, 4 KiB stack, result-block addresses, `_start`, and `exit`/`abort` publishing must survive the assembly rewrite, because `tms-run` and the harness read them (Task 2).
5. **M10 is untouched** — `clang -c` at `-O0`/`-O2` and the `-O0` byte-identity gate stay exactly as they were; the link work must not perturb codegen (Task 6).
---
### Task 1: `tms-link` emits loader-valid images unaided
**Files:**
- Modify: `tools/tms-link/tmscoff.py` (`write_coff`, only if the header is defective)
- Modify: `tools/tms-link/tms-link` (only if the writer needs input)
- Modify: `tools/tms-link/tests/{run.sh,linktest.py}`
- Test: a new case in `tools/tms-link/tests/`
**Interfaces:**
- Consumes: `tmscoff.write_coff(path, sections, symbols, *, entry, text_size, data_size, …)` and the existing `scripts/m4/coff-check.py [--repair] [--entry HEX] FILE` validator.
- Produces: whatever the linker emits today must pass `coff-check.py` **without** `--repair`, including an odd-length `.bss`.
- [ ] **Step 1: Write the failing gate case**
Add to `tools/tms-link/tests/run.sh` a case that links a small object (reuse an existing fixture) and then runs
`python3 scripts/m4/coff-check.py OUT.coff` expecting exit 0, plus a fixture whose `.bss` length is odd (e.g. one 8-bit symbol) checked the same way.
- [ ] **Step 2: Run it red**
Run: `tools/tms-link/tests/run.sh`
Expected: FAIL on the new case with the validator's magic/size complaint (or on the odd-`.bss` case).
- [ ] **Step 3: Fix the writer**
If the file/optional header or section table is defective, fix `write_coff`. If an odd `.bss` is emitted unrounded, round only `.bss` to a whole 16-bit word, as `coff-check.py --repair` does. Do not change `.text`/`.data` contents, relocation handling, or the entry point.
- [ ] **Step 4: Run it green**
Run: `tools/tms-link/tests/run.sh`
Expected: PASS, including the two new cases.
- [ ] **Step 5: Commit**
```bash
git add tools/tms-link/tmscoff.py tools/tms-link/tms-link tools/tms-link/tests/
git commit -m "m11: tms-link emits loader-valid COFF without repair"
```
---
### Task 2: `sdk/crt0.ll` — the CRT as IR with a naked `_start`
**Files:**
- Create: `sdk/crt0.ll`
- Create: `scripts/tests/m11/crt.sh`
- Test: `scripts/tests/m11/crt.sh`
**Interfaces:**
- Consumes: `llc -march=tms34010 -filetype=obj`, `tools/tms-link/tms-link`, `scripts/tms-run`, and the result-block contract in Global Constraints.
- Produces: `sdk/crt0.ll`, a `naked` `_start` built by `llc`, defining `_start`, `_conformance_name` (12 bytes, `"conformance\0"`), `_conformance_argv` (64 bits), `_cstack` (32768 bits, 16-bit alignment), and preserving the register/stack setup of `scripts/tests/m5/conformance/entry.asm`.
- [ ] **Step 1: Write the failing contract test**
`scripts/tests/m11/crt.sh` builds `sdk/crt0.ll` with `llc`, compiles a heredoc `main.c` (`int main(int argc, char **argv) { printf("%d %s\n", argc, argv[0]); return 7; }`), links them with `tms-link` (`--entry _start --text 018A0000 --bss 01A00000 --prog-len 40000h --ram-len 80000h`) plus the existing conformance `shim.o`, and runs `scripts/tms-run`. Expected: status 7, stdout `1 conformance`.
- [ ] **Step 2: Record the red state**
Run: `scripts/tests/m11/crt.sh`
Expected: FAIL — `sdk/crt0.ll` does not exist. Also record the known fact that `llvm-mc` emits ELF for this triple (and rejects `scripts/tests/m5/conformance/entry.asm`'s `.bss` operands, `h`-suffixed hex, `.even`), so this is an IR rewrite built with `llc`, not a copy.
- [ ] **Step 3: Write `sdk/crt0.ll`**
Express the CRT as IR (`sdk/crt0.ll`) with a `naked` `@start` whose single inline-asm block carries the instruction sequence, plus module globals for `_conformance_name`, `_conformance_argv` and `_cstack`. Keep the contract: `setf 16,1,0`/`setf 32,0,1`, clear the four result cells, point `A14` at `_cstack` and `A13` at it, build `argv = { _conformance_name, NULL }`, push `argv` then `1`, `calla _main`, store `A8` as the status and `0x434F4E46` as the magic, `rets`. Build it with `llc -march=tms34010 -filetype=obj`: `llvm-mc` emits ELF for this triple, so only CodeGen reaches the TI-COFF writer.
- [ ] **Step 4: Run the contract test**
Run: `scripts/tests/m11/crt.sh`
Expected: `m11 crt: PASS` (status 7, stdout `1 conformance`).
- [ ] **Step 5: Commit**
```bash
git add sdk/crt0.ll scripts/tests/m11/crt.sh
git commit -m "m11: add the llc CRT with the conformance runtime contract"
```
---
### Task 3: `sdk/` sources and `scripts/tms-sdk`
**Files:**
- Create: `sdk/include/` (moved from `scripts/tests/m5/conformance/include`, 10 headers)
- Create: `sdk/shim.c`, `sdk/heap.c` (moved from `scripts/tests/m5/conformance/`)
- Create: `sdk/lib/flib.lib`, `sdk/lib/rts.lib` (committed copies of `build/m6-sdk/{flib,rts}.lib`)
- Create: `scripts/tms-sdk`
- Create: `scripts/tests/m11/sdk.sh`
- Modify: `scripts/tests/m5/conformance/run.sh` (point at `sdk/include`)
- Test: `scripts/tests/m11/sdk.sh`
**Interfaces:**
- Consumes: `sdk/crt0.ll` (Task 2), `llc`, `clang --target=tms34010 -c`, `llvm-ar`, `tools/tms-link/{tms-link,tmscoff.py}`.
- Produces: `scripts/tms-sdk [--sysroot DIR]`, which installs `<sysroot>/{include,lib,bin}` with `include/*.h`, `lib/{crt0.o,libtms.a,flib.lib,rts.lib}`, `bin/{tms-link,tmscoff.py}`. Default sysroot: `$(clang -print-resource-dir)/tms34010-unknown-none`.
- [ ] **Step 1: Write the failing gate**
`scripts/tests/m11/sdk.sh` runs `scripts/tms-sdk --sysroot "$TMP/sysroot"` and asserts: the seven expected layout entries exist; `llvm-ar t libtms.a` lists `shim.o` and `heap.o`; a second run is idempotent; `cmp` of `crt0.o` against a fresh `llc` build is identical; `cmp` of `libtms.a` against a fresh `llvm-ar rcsD` build is identical; `sdk/lib/{flib,rts}.lib` match `build/m6-sdk/{flib,rts}.lib` when those exist.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m11/sdk.sh`
Expected: FAIL — `scripts/tms-sdk` does not exist.
- [ ] **Step 3: Move the sources and commit the archives**
Move the headers, `shim.c` and `heap.c` into `sdk/`; copy `build/m6-sdk/{flib,rts}.lib` to `sdk/lib/`; update the conformance runner and any harness path that referenced `scripts/tests/m5/conformance/include` so exactly one copy exists.
- [ ] **Step 4: Implement `scripts/tms-sdk`**
Build `crt0.o` with `llc`, `shim.o`/`heap.o` with `clang --target=tms34010 -O2 -c`, `libtms.a` with `llvm-ar rcsD`, then install the layout above (copying the linker pair and marking `tms-link` executable). Rebuild `llvm-ar` if missing: `ninja -C build/llvm-clean-build llvm-ar`.
- [ ] **Step 5: Run it green**
Run: `scripts/tests/m11/sdk.sh`
Expected: `m11 sdk: PASS`.
- [ ] **Step 6: Commit**
```bash
git add sdk scripts/tms-sdk scripts/tests/m11/sdk.sh scripts/tests/m5/conformance/run.sh
git commit -m "m11: add the sdk sources and the sysroot installer"
```
---
### Task 4: ToolChain sysroot discovery and the link job
**Files:**
- Modify: `clang/lib/Driver/ToolChains/TMS34010.h`, `TMS34010.cpp`
- Create: `clang/test/Driver/TMS34010-link.c`
- Test: that driver test plus `clang/test/Driver/tms34010-defaults.c` (unchanged)
**Interfaces:**
- Consumes: the installed sysroot from Task 3 and `tms-link`'s CLI (`--entry --text --bss --prog-len --ram-len --map --keep-debug -L -l`).
- Produces: `class TMS34010Linker final : public Tool` with `ConstructJob`; `TMS34010ToolChain::buildLinker()`; sysroot-derived include/lib paths; `--tms-linker=PATH`; `-nostartfiles`/`-nodefaultlibs`/`-nostdlib`; `-g` → `--keep-debug`; `-Wl,` passthrough.
- [ ] **Step 1: Write the failing driver tests**
`clang/test/Driver/TMS34010-link.c` (model on `avr-link-nostdlib-nodefaultlibs.c`), using `-###`:
- default link: `tms-link`, `--entry _start`, `--text 018A0000`, `--bss 01A00000`, the objects, `libtms.a`, `flib.lib`, `rts.lib`;
- `-nostdlib`: none of `crt0.o`, `libtms.a`, `flib.lib`, `rts.lib`;
- `-nostartfiles`: no `crt0.o`, libraries still present;
- `-nodefaultlibs`: `crt0.o` present, no libraries;
- `-g`: `--keep-debug`;
- `-Wl,--prog-len=80000h`: appears verbatim;
- `--tms-linker=/tmp/x`: that path replaces the sysroot linker;
- `-l tms`: accepted, and `libtms.a` appears once;
- a nonexistent `--tms-sysroot=/nope` and a sysroot without `bin/tms-link`: each produces the named "run scripts/tms-sdk" diagnostic, not a linker error;
- `-c`: no link job at all.
- [ ] **Step 2: Run them red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/Driver/TMS34010-link.c`
Expected: FAIL — clang emits no link job for this target.
- [ ] **Step 3: Implement discovery and the linker Tool**
Search order `--tms-sysroot=`, `--sysroot`/`-isysroot`, `<resource-dir>/tms34010-unknown-none`. Add `<sysroot>/include` as a system include and `<sysroot>/lib` as a library path, without touching the M10 freestanding defaults. Implement `ConstructJob` with the argument order in the spec §8.2, and make a missing sysroot, missing `tms-link` or missing `python3` a `Diag` naming `scripts/tms-sdk` (check `python3` with `llvm::sys::findProgramByName`).
- [ ] **Step 4: Run them green**
Run: `ninja -C build/llvm-clean-build clang FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/Driver/TMS34010-link.c build/llvm-clean/clang/test/Driver/tms34010-defaults.c`
Expected: PASS for both files.
- [ ] **Step 5: Commit**
```bash
git -C build/llvm-clean add clang/lib/Driver/ToolChains/TMS34010.h \
clang/lib/Driver/ToolChains/TMS34010.cpp clang/test/Driver/TMS34010-link.c
git -C build/llvm-clean commit -m "tms34010: add sysroot discovery and the tms-link job"
```
---
### Task 5: Single-command build end to end
**Files:**
- Create: `scripts/tests/m11/e2e.sh`
- Test: `scripts/tests/m11/e2e.sh`
**Interfaces:**
- Consumes: `scripts/tms-sdk` (Task 3), the link job (Task 4), `scripts/tms-run`.
- Produces: the acceptance gate for the milestone's headline command.
- [ ] **Step 1: Write the failing gate**
`scripts/tests/m11/e2e.sh` (run from a temp directory outside the repo, with `env -u M4_WORK -u TMS_CLANG …`): install the sysroot into a temp dir with `scripts/tms-sdk --sysroot`, export `CLANG` and pass `--tms-sysroot` once, then:
- `clang --target=tms34010 hello.c -o hello` (a heredoc `hello.c` printing one line) and `tms-run hello` → status 0, stdout matches, and `hello.map` exists;
- a two-TU build (`add.c` + `main.c`) → `add=42`;
- `-c`, `-S`, `-E` produce an object, assembly and preprocessed source respectively;
- `-O0` and `-O2` both run correctly;
- `-g` links and the image keeps `.debug_*` while a default link is stripped;
- `-nostdlib` with a user `_start` links;
- `clang -### --target=tms34010 hello.c -o hello` contains no checkout path.
- [ ] **Step 2: Run it red**
Run: `scripts/tests/m11/e2e.sh`
Expected: FAIL at the first link with the missing-sysroot/link-job diagnostic.
- [ ] **Step 3: Fix what the gate exposes**
Only driver/ToolToolchain or `tms-sdk` changes belong here; if a defect is in `tms-link`, note it and fix it with its own test.
- [ ] **Step 4: Run it green**
Run: `scripts/tests/m11/e2e.sh`
Expected: `m11 e2e: PASS`.
- [ ] **Step 5: Verify one existing harness program and the compatibility alias**
Run the M4 harness with `M4_NATIVE=1 M4_LINKER=tms-link` on one program (e.g. `scripts/m4/unsigned.c`) and confirm its MAME markers still pass. Then run `scripts/tms-cc hello.c -o hello` and `scripts/tms-run hello` to confirm the Phase 1 alias still works after the sysroot change.
- [ ] **Step 6: Commit**
```bash
git add scripts/tests/m11/e2e.sh
git commit -m "m11: gate the single-command build end to end"
```
---
### Task 6: Docs, full sweep, patch export, promote `m11`
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md`
- Modify: `patches/llvm/0005-*.patch`
- Test: the full M0–M11 gate list
- [ ] **Step 1: Re-export the driver patch**
Run: `git -C build/llvm-clean diff m9..m11 -- clang/ > patches/llvm/0005-tms34010-toolchain.patch`
Expected: only `ToolChains/TMS34010.{h,cpp}`, the two registration edits and the M10/M11 clang tests.
- [ ] **Step 2: Run the compiler and toolchain tests**
Run: lit for `llvm/test/CodeGen/TMS34010`, `llvm/test/MC/TMS34010`, `clang/test/CodeGen/TMS34010`, `clang/test/Driver/TMS34010*`; `tools/tms-link/tests/run.sh`; `tools/tms-bitaddr/tests/run.sh`.
Expected: all PASS.
- [ ] **Step 3: Run the M11 gates and the M10 regressions**
Run: `scripts/tests/m11/{sdk,crt,e2e}.sh`, `scripts/tests/m10/equivalence.sh` (`pass=46 fail=0`), `scripts/tests/m10/bitaddr-idempotent.sh`, `scripts/tests/m9/dwarf-ranges.sh`, `scripts/tests/m8/dwarf-multi.sh`, `scripts/tests/m7/debug.sh`.
Expected: all PASS.
- [ ] **Step 4: Run the suite and the divide measurement**
Run: `scripts/tests/m7/full-suite.sh --corpus all --work build/m11-final`
Expected: `all total=1912 pass=1618 skip=294 fail=0 crash=0`.
Run: `scripts/tests/m7/i64div.sh`
Expected: `88/3302/221/120`, ratios 37.5/14.9/1.8, the same four checksums.
- [ ] **Step 5: Run the remaining M0–M10 gate list**
The serial list from `README.md`'s gate section, including `hardware.sh` → `HARDWARE: DEFERRED`.
Expected: every gate PASS.
- [ ] **Step 6: Update the docs**
Record M11 complete: the single command, the sysroot layout and `scripts/tms-sdk`, `python3` as a link-time dependency, the link-reduction knobs, the CRT dialect rewrite and its preserved contract, the `tms-link` validity fix, `tms-cc` as a compatibility alias, and the M11/M12 boundary with a pointer to the roadmap (§11 of the design).
- [ ] **Step 7: Commit, review, push, promote**
```bash
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "docs: record the M11 toolchain"
git add README.md docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md \
patches/llvm/0005-tms34010-toolchain.patch
git commit -m "m11: document the conventional toolchain"
```
Then run the whole-branch review, and only when it is clean: push `m11` in both repositories, set it as the default on both remotes, and update the README's default-branch wording. `m10` stays as the previous snapshot.
---
## Execution Handoff
M11 ends with `clang --target=tms34010 hello.c -o hello` working from a clean shell after one `scripts/tms-sdk`, every M0–M10 gate still green, and the suite unchanged at 1,618 passes. M12 (conformance classes) is the next milestone per the roadmap; it gets its own design and plan.
@@ -0,0 +1,383 @@
# TMS34010 M12 — Tractable Conformance Gaps 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:** Close the backend gaps that account for 17 curated full-suite skips — inline-asm memory operands, the `ST` clobber, computed `goto`, return/frame address at level 0, and dynamic-alloca scaling — and produce a costed triage of the runtime-abort skips for M13.
**Architecture:** All compiler work stays in `llvm/lib/Target/TMS34010/` (plus `"st"` in clang's target register list). Inline-asm memory operands get a real selector in `TMS34010ISelDAGToDAG::SelectInlineAsmMemoryOperand`; computed goto needs the ISA's `jump Rd` instruction end to end plus `ISD::BlockAddress`/`ISD::BRIND` lowering; the frame intrinsics lower against the existing system-stack layout; the alloca fix keeps bit units throughout. The abort triage is a harness plus a research document, not a fix pass.
**Tech Stack:** LLVM/Clang 23.1.5 fork (`llvm-tms34010`), SelectionDAG/ISel, MC (encoding, parser, printer, disassembler), lit/FileCheck, the TMS34010 MAME harness, shell gates.
**Spec:** `docs/superpowers/specs/2026-11-19-tms34010-m12-tractable-gaps-design.md` (§7 per workstream, §8 acceptance).
## Global Constraints
- Baseline: project `m11`/`ef8a854`, compiler `m11`/`18b7fc9cd6df`. Cut `m12` in both repos before Task 1; never force-push.
- LLVM/Clang stay pinned at 23.1.5. No generic-LLVM behaviour changes: `InlineAsm::ConstraintCode` is not extended, so `V` stays loud.
- No TI ABI change: the all-stack convention, argument slots, the bit pointer model and the frame layout are unchanged.
- `clang --target=tms34010 -c` and the M11 `hello.c -o hello` flow must keep working, including `-O0` byte identity (`scripts/tests/m10/equivalence.sh` `pass=46 fail=0`).
- Build with `-j4` on this host (unbounded ninja has been OOM-killed).
- Every gate stays green; the suite stays `0 fail / 0 crash`. A curated row is removed only in the task that makes it pass, with the flip recorded.
- No gate expectation, checksum or recorded count moves beyond those recorded flips.
- Out of scope, permanently: nested functions and VLA-in-struct (clang frontend refusals), dialect strictness, timeouts and region limits.
## Review Focus
1. **Inline-asm memory operands that are not a plain `*An`** — a user writing `"m"(*p)` where `p` is an argument, an sp-relative local, or a post-increment form must get a valid address, or a named error — never a silent register copy (Task 1).
2. **Computed `goto` and the new instruction's encoding round-trip** — the block address must be section-relative, and `jump Rd` must assemble, disassemble and select consistently (Task 2).
3. **`__builtin_return_address(0)` after a dynamic alloca or in a variadic callee** — the frame may not hold a fixed offset; the level-0 value must still be the caller's return address (Task 3).
4. **A dynamic alloca whose size is not a multiple of 32 bits** — the stack adjust and the pointer arithmetic must agree (Task 4).
5. **The triage's own honesty** — a row that aborts must be recorded with its actual status and cause, and the harness must not turn a curated skip into a fail row (Task 5).
---
### Task 1: Inline-asm memory operands and the `ST` clobber
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelDAGToDAG.cpp:35-45` (`SelectInlineAsmMemoryOperand`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp:650` (`getConstraintType`) if `o`/`V` need distinguishing
- Modify: `clang/lib/Basic/Targets/TMS34010.cpp:73` (`getGCCRegNames`)
- Test: `clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c`, `llvm/test/CodeGen/TMS34010/m12-inline-asm-st.ll`, `llvm/test/CodeGen/TMS34010/m12-inline-asm-mem-reject.ll`
**Interfaces:**
- Consumes: the target's existing addressing-mode selection (the matcher used by `LD`/`ST` in `TMS34010ISelDAGToDAG.cpp`) and the M9 constraint plumbing (`getRegForInlineAsmConstraint`, `getConstraintType`).
- Produces: `bool TMS34010DAGToDAGISel::SelectInlineAsmMemoryOperand(const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, SmallVectorImpl<SDValue> &OutOps)` that selects the five ISA memory forms (`*An`, `*An(disp)`, `*An+`, `*-An`, `*An(disp),N`) for `m`/`g`, and a named error for anything else; `"st"` present in clang's GCC register list.
- [ ] **Step 1: Write the failing tests**
```c
// clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c
// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -S -o - %s | FileCheck %s
// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -S -o - %s | FileCheck %s
int load_via_asm(int *p) {
int x;
__asm__ volatile("" : "=r"(x) : "m"(*p) : "memory");
return x;
}
int store_via_asm(int *p, int v) {
__asm__ volatile("" : : "m"(*p), "r"(v) : "memory");
return v;
}
// CHECK-LABEL: _load_via_asm:
// CHECK-NOT: error:
// CHECK-LABEL: _store_via_asm:
```
```llvm
; llvm/test/CodeGen/TMS34010/m12-inline-asm-st.ll
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define i32 @clobber_st(i32 %x) {
%r = call i32 asm sideeffect "", "=r,0,~{st}"(i32 %x)
ret i32 %r
}
; CHECK-LABEL: _clobber_st:
; CHECK-NOT: error:
```
```llvm
; llvm/test/CodeGen/TMS34010/m12-inline-asm-mem-reject.ll
; RUN: not llc -march=tms34010 -O0 -filetype=asm < %s 2>&1 | FileCheck %s
define i32 @bad(i32 %x) {
%r = call i32 asm sideeffect "", "=r,0,~{memory}"(i32 %x)
ret i32 %r
}
; CHECK: TMS34010: unsupported inline asm
```
- [ ] **Step 2: Run them red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-inline-asm-st.ll`
Expected: FAIL — the first with `TMS34010: inline asm memory constraints ('m'/'o'/'V') are not supported`, the second with `unknown register name 'st' in asm`.
- [ ] **Step 3: Implement the selector and the clobber name**
In `SelectInlineAsmMemoryOperand`, match the operand to a memory form using the same `SelectAddr`-style helper the loads/stores use; push the base register and the displacement (if any) as `OutOps`. For `m`/`g` accept any matched form; for `o` accept only forms without a post-increment and with a non-negative displacement; for `V` keep the existing named error, extended to say that `V` needs core LLVM support. Add `"st"` to `getGCCRegNames()`; leave the register class and operand constraints untouched so `ST` is clobber-only.
- [ ] **Step 4: Run them green**
Run: `ninja -C build/llvm-clean-build -j4 clang llc FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-inline-asm-st.ll build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-inline-asm-mem-reject.ll`
Expected: PASS for all three.
- [ ] **Step 5: Flip the eleven corpus rows**
```sh
awk -F'\t' '$2 ~ /^inline-asm: TMS34010 memory constraints/ {print $1}' \
scripts/tests/m7/full-suite.skip > /tmp/opencode/m12-inline.txt
scripts/tests/m7/full-suite.sh --corpus c-torture --list /tmp/opencode/m12-inline.txt \
--redo --work build/m12-inline
```
Expected: all pass. Remove exactly those rows from `scripts/tests/m7/full-suite.skip` and record the count.
- [ ] **Step 6: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010ISelDAGToDAG.cpp \
llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp clang/lib/Basic/Targets/TMS34010.cpp \
llvm/test/CodeGen/TMS34010/m12-inline-asm-*.ll clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c
git -C build/llvm-clean commit -m "tms34010: select inline-asm memory operands and name the st clobber"
git add scripts/tests/m7/full-suite.skip
git commit -m "m12: flip the inline-asm memory-constraint rows"
```
---
### Task 2: `jump Rd`, `BRIND` and computed `goto`
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010InstrInfo.td` (new `JumpReg` definition, opcode `0x0160`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010InstrInfo.cpp` if the instruction needs custom sizing
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp` (`LowerOperation`: `ISD::BlockAddress`, `ISD::BRIND`; `setOperationAction`)
- Modify: `llvm/lib/Target/TMS34010/MCTargetDesc/{TMS34010AsmParser,TMS34010InstPrinter,TMS34010MCCodeEmitter,TMS34010Disassembler}.cpp` as the generated tables require
- Test: `llvm/test/MC/TMS34010/m12-jump-reg.s`, `llvm/test/CodeGen/TMS34010/m12-computed-goto.ll`
**Interfaces:**
- Consumes: the existing branch machinery (`JUncond`, `JR`, `TMS34010Jrc`) and `TMS34010TargetLowering::LowerOperation`'s switch.
- Produces: instruction `TMS34010::JumpReg` (`"jump $src"`), `ISD::BRIND` lowered to it, and `ISD::BlockAddress` lowered to a section-relative bit address (`TMS34010ISD::BITADDR`-style constant material, with the existing relocation path).
- [ ] **Step 1: Write the failing MC test**
```asm
# llvm/test/MC/TMS34010/m12-jump-reg.s
# RUN: llvm-mc -triple=tms34010 -show-encoding %s | FileCheck %s
# RUN: llvm-mc -triple=tms34010 -filetype=obj %s -o %t.o
# RUN: llvm-mc -triple=tms34010 -disassemble %t.o | FileCheck %s --check-prefix=DIS
# CHECK: jump a0 # encoding: [0x60,0x01,0x00,0x00]
# DIS: jump a0
jump a0
```
Confirm the expected encoding against `vendor/vt1200/tools/smart34010/README.md` (opcode `0x0160`) and the ISA's word order before pinning the bytes.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010/m12-jump-reg.s`
Expected: FAIL — `invalid instruction mnemonic 'jump'`.
- [ ] **Step 3: Define the instruction and its MC surface**
Add `def JumpReg : TMS34010Inst<(outs), (ins ARegs:$src), "jump $src", …>` with the opcode and encoding the ISA specifies; update the assembler match table, printer and disassembler as generated. The disassembly assertion in the test is what proves the round-trip; keep `JUncond`/`JR` untouched.
- [ ] **Step 4: Run the MC test green and the MC suite**
Run: `ninja -C build/llvm-clean-build -j4 llvm-mc llc FileCheck && build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/MC/TMS34010`
Expected: the new test plus the four existing MC tests pass.
- [ ] **Step 5: Write the failing computed-goto test**
```llvm
; llvm/test/CodeGen/TMS34010/m12-computed-goto.ll
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
define i32 @cg(i32 %x) {
entry:
indirectbr ptr blockaddress(@cg, %a), [label %a, label %b]
a:
ret i32 1
b:
ret i32 2
}
; CHECK-LABEL: _cg:
; CHECK: jump
; CHECK-LABEL: .Lcg$a:
```
- [ ] **Step 6: Run it red, then implement the lowerings**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-computed-goto.ll`
Expected: FAIL — `Cannot select: … BlockAddress`.
Implement `ISD::BlockAddress` (section-relative bit address with the existing relocation path) and `ISD::BRIND` (jump through the selected register) in `LowerOperation`, and mark both `Custom` in the constructor. Then rerun the test.
- [ ] **Step 7: Flip the two corpus rows**
Run the two rows (`c-torture/920501-3`, `c-torture/990208-1`) through the suite in isolation; both must pass at `-O0` and `-O2`. Remove them from `full-suite.skip`.
- [ ] **Step 8: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010 llvm/test/MC/TMS34010/m12-jump-reg.s \
llvm/test/CodeGen/TMS34010/m12-computed-goto.ll
git -C build/llvm-clean commit -m "tms34010: add jump Rd, BRIND and blockaddress lowering"
git add scripts/tests/m7/full-suite.skip
git commit -m "m12: flip the computed-goto rows"
```
---
### Task 3: Return and frame address at level 0
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp` (`LowerOperation`, `setOperationAction` for `ISD::RETURNADDR`/`ISD::FRAMEADDR`)
- Modify: `llvm/lib/Target/TMS34010/TMS34010FrameLowering.cpp` only if the level-0 value needs a slot recorded
- Test: `llvm/test/CodeGen/TMS34010/m12-frameaddr.ll`
**Interfaces:**
- Consumes: the system-stack layout documented in `TMS34010FrameLowering.cpp:120-145` — the callee saves the caller's state below the return address, and `LOADSTK`/`ADDSTK` already encode `(NumSaved + 1) * 32`.
- Produces: `ISD::RETURNADDR` at level 0 → the caller's return address (a slot computed from the saved-register count or an `SP`-relative load emitted after PEI); `ISD::FRAMEADDR` at level 0 → `A13`; levels above 0 → a named error that says which intrinsic and level.
- [ ] **Step 1: Write the failing test**
```llvm
; llvm/test/CodeGen/TMS34010/m12-frameaddr.ll
; RUN: llc -march=tms34010 -O0 -filetype=asm < %s | FileCheck %s
declare ptr @llvm.returnaddress(i32)
declare ptr @llvm.frameaddress(i32)
define ptr @ra0() {
%p = call ptr @llvm.returnaddress(i32 0)
ret ptr %p
}
define ptr @fa0() {
%p = call ptr @llvm.frameaddress(i32 0)
ret ptr %p
}
; CHECK-LABEL: _ra0:
; CHECK-NOT: error
; CHECK-LABEL: _fa0:
; CHECK-NOT: error
```
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-frameaddr.ll`
Expected: FAIL with `unexpected TMS34010 custom lowering operation`.
- [ ] **Step 3: Implement the two lowerings**
Read `TMS34010FrameLowering.cpp` to derive the level-0 return-address offset from the saved-register count (the same expression the prologue/epilogue use), and lower `RETURNADDR(0)` to a load from it; `FRAMEADDR(0)` is `A13`. For a level above 0, fail with `TMS34010: <intrinsic> level <n> is unsupported (only level 0)`.
- [ ] **Step 4: Run the test green, then probe the frame cases**
Add a case with a dynamic alloca and a variadic callee to the same test and confirm the emitted offset changes with the frame instead of being hard-coded. Run the test.
- [ ] **Step 5: Flip the three corpus rows**
Run `c-torture/20030811-1`, `c-torture/frame-address`, `c-torture/pr17377` through the suite; remove those three from `full-suite.skip`. `20010122-1` and `20030323-1` stay curated; update their reasons to `level > 0 unsupported` if they do not already say so.
- [ ] **Step 6: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp \
llvm/test/CodeGen/TMS34010/m12-frameaddr.ll
git -C build/llvm-clean commit -m "tms34010: lower returnaddress/frameaddress at level 0"
git add scripts/tests/m7/full-suite.skip
git commit -m "m12: flip the level-0 frame rows and restate the level>0 skips"
```
---
### Task 4: Dynamic alloca scaling
**Files:**
- Modify: `llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp:1894` (`ISD::DYNAMIC_STACKALLOC` case) and whatever size scaling feeds it
- Test: `llvm/test/CodeGen/TMS34010/m12-dynalloca.ll`
**Interfaces:**
- Consumes: the bit-unit pointer model and the `MOVE A14, A13` / `ADDSTK FrameBits` epilogue path for `hasVarSizedObjects()` (`TMS34010FrameLowering.cpp:133-143`).
- Produces: a dynamic alloca whose stack adjustment and returned pointer agree in bits for non-multiple-of-32 sizes.
- [ ] **Step 1: Reproduce and write the failing test**
Run: `scripts/tests/m7/full-suite.sh --corpus c-torture --list <(echo c-torture/20070824-1) --redo --work build/m12-dyn` and capture the failure.
Then write `m12-dynalloca.ll` with a `dynamic alloca i8, i32 %n` and a store/load through the returned pointer, asserting the stack adjust is `8*n` bits (not `n`), at `-O0` and `-O2`.
- [ ] **Step 2: Run it red**
Run: `build/llvm-clean-build/bin/llvm-lit -v build/llvm-clean/llvm/test/CodeGen/TMS34010/m12-dynalloca.ll`
Expected: FAIL — the assertion from the corpus run, or the wrong stack-adjust constant.
- [ ] **Step 3: Fix the scaling**
Make the alloca size arrive in bits (multiply the byte size by 8 where the DAG builds it, or scale in the `DYNAMIC_STACKALLOC` lowering), and keep alignment rounding in bits.
- [ ] **Step 4: Run the test and the corpus row green**
Run the lit test, then the corpus row alone. Then remove `c-torture/20070824-1` from `full-suite.skip`.
- [ ] **Step 5: Commit**
```bash
git -C build/llvm-clean add llvm/lib/Target/TMS34010/TMS34010ISelLowering.cpp \
llvm/test/CodeGen/TMS34010/m12-dynalloca.ll
git -C build/llvm-clean commit -m "tms34010: scale dynamic alloca sizes in bit units"
git add scripts/tests/m7/full-suite.skip
git commit -m "m12: flip the dynamic-alloca row"
```
---
### Task 5: Abort triage
**Files:**
- Create: `scripts/tests/m12/abort-triage.sh`
- Create: `docs/superpowers/research/2026-11-19-tms34010-abort-triage.md`
- Test: the harness itself (run it; it must produce the document)
**Interfaces:**
- Consumes: `scripts/tests/m7/full-suite.sh` (for corpus discovery and the classifier), `scripts/tests/m5/conformance/run.sh --classify --mode native --expect-status 0`, and the manifest's status/marker contract.
- Produces: a document with one row per abort-skipped file: `corpus/name`, `-O0` result, `-O2` result, status word, first wrong marker or abort PC, cause class, evidence pointer, estimated cost; plus a summary grouped by cause and a proposed M13 scope. The harness discovers its set by re-running every curated `runtime-abort*`/wrong-result row, and must not edit `full-suite.skip`.
- [ ] **Step 1: Write the harness**
`scripts/tests/m12/abort-triage.sh`: enumerate the curated abort rows from `full-suite.skip`, run each at `-O0` and `-O2`, capture the runner's status and the first differing marker (reuse the runner's own output format), and emit the Markdown table. It must be hermetic apart from MAME, and serial.
- [ ] **Step 2: Run it and record the raw output**
Run: `scripts/tests/m12/abort-triage.sh`
Expected: a table covering the discovered set (49–51 rows at the time of writing) with no `fail` rows added to the suite file.
- [ ] **Step 3: Group and write the research document**
Fill `2026-11-19-tms34010-abort-triage.md` from the harness output: one row per file, cause classes with the evidence, and an M13 proposal ordering the causes by files affected and estimated cost. Apply the plan's ruling: at most three fixes may be proposed as one-line fixes inside M12.
- [ ] **Step 4: Commit**
```bash
git add scripts/tests/m12/abort-triage.sh docs/superpowers/research/2026-11-19-tms34010-abort-triage.md
git commit -m "m12: triage the runtime-abort skips for M13"
```
---
### Task 6: Accounting, docs, full sweep, promote `m12`
**Files:**
- Modify: `README.md`, `build/llvm-clean/TMS34010.md`, `docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md`
- Modify: `patches/llvm/0005-*.patch` (the compiler delta for M12)
- Test: the full M0–M12 gate list
- [ ] **Step 1: Re-record the suite accounting**
Run: `scripts/tests/m7/full-suite.sh --corpus all --work build/m12-final`
Expected: `0 fail / 0 crash`, pass = 1,618 + 17 (plus any abort fixes taken), skip = 294 − the same number, and every removed row named in the commit history.
- [ ] **Step 2: Run the compiler and toolchain tests**
Run: lit for `llvm/test/CodeGen/TMS34010`, `llvm/test/MC/TMS34010`, `clang/test/CodeGen/TMS34010`, `clang/test/Driver/TMS34010*`; `tools/tms-link/tests/run.sh`; `tools/tms-bitaddr/tests/run.sh`; `scripts/tests/m11/{sdk,crt,e2e}.sh`; `scripts/tests/m10/equivalence.sh` (`pass=46 fail=0`).
Expected: all PASS.
- [ ] **Step 3: Run the M0–M11 gate list and the divide measurement**
The serial list from `README.md`'s gate section, plus `scripts/tests/m7/i64div.sh` (expect `88/3302/221/120` and the four checksums) and `hardware.sh` (`HARDWARE: DEFERRED`).
Expected: every gate PASS.
- [ ] **Step 4: Export the patch and update the docs**
Re-export `patches/llvm/0005-*.patch`; record M12 complete in the three documents: the 17 flips with their rows, the `ST`/`o`/`V` decisions, `jump Rd`, the level-0 frame intrinsics, the alloca fix, the triage report's path and headline (what M13 inherits), the permanently-out classes, and `m12` as the milestone branch pending promotion.
- [ ] **Step 5: Commit and hand off for review**
```bash
git -C build/llvm-clean add TMS34010.md
git -C build/llvm-clean commit -m "docs: record the M12 state"
git add README.md docs/superpowers/specs/2026-11-10-tms34010-llvm-design.md \
patches/llvm/0005-tms34010-toolchain.patch
git commit -m "m12: document the conformance fixes and the abort triage"
```
Then run the whole-branch review. Only when it is clean: push `m12` in both repositories, set it as the default on both remotes, and update the README's default-branch wording.
---
## Execution Handoff
M12 ends with 17 more files passing, a triaged abort list that makes M13 plannable, and every M0–M11 gate plus the M11 end-to-end build still green. M13 (ABI shapes + the triaged abort causes) is planned after this milestone is promoted.
@@ -0,0 +1,93 @@
# Multi-model review observations (M12)
Started 2026-11-19. The partner asked for two reviewers per task (DeepSeek Flash always, plus a free
OpenCode model) and for anything noteworthy this surfaces to be written down.
## Protocol
| seat | model | role |
|---|---|---|
| A | `deepseek/deepseek-flash` | always present, first reader |
| B | `opencode/tidepool-alpha-free` | second opinion on every task review |
| C | `opencode/nemotron-3.5-super-vl-free` | third seat for the whole-branch review and risky tasks |
Both seats get the same brief, report and diff file, and neither sees the other's verdict. Findings
are compared by the controller; disagreements are adjudicated in the normal fix loop.
## Findings caught by a second seat that seat A missed
| task | seat | finding | outcome |
|---|---|---|---|
| 3 | A (flash) | **Critical**: the level-0 return-address load was chained only to the entry node, so at `-O1+` it sank into the caller's saved-STK push window and read the saved frame pointer. Reproduced from C. Seat B had approved after checking only `-O0`. | Fix round 1: capture the RA in the prologue into an A13-relative slot; test now uses the RA after an argument-bearing call. **This is the first genuine severity divergence between the seats.** |
| 1 | B (tidepool) | `ConstraintCode::X` is also accepted by the new memory selector (an unspecified superset, not in the rulings) | parked as Minor; harmless, `X` is an "any value" code |
| 1 | B (tidepool) | `stkalign`'s new skip reason is report-attested only — the test source is not in the pinned repo | parked; the assert status (0x86) is recorded |
## Findings caught by seat A that a second seat missed
| task | seat A finding | outcome |
|---|---|---|
| (none yet) | | |
## Notes on the free seats
- Task 1: both seats independently verified the same core contracts (no register-copy fallback,
`ST` outside every register class, skip accounting). Seat B added the `X`-superset observation and
the "report-attested reason" caveat; seat A added the release-build `llvm_unreachable` safety nit
and three test-strength nits. Neither found a defect the other's verdict would have missed at
Critical/Important level.
## Task 2
- Both seats independently reproduced the same escalation: `990208-1`'s `-O2` abort comes from
generic LLVM refusing to inline a function whose address is taken (`InlineCost.cpp:3320`), and the
test's own `__OPTIMIZE__` guard then aborts on x86-64 too. Neither seat treated it as a TMS34010
defect; the controller ruled to keep the row and record the caveat.
- Distinct contributions: seat A found the constant-integer `BRIND` path has no lit coverage and that
`920501-3` only ever adds a zero offset (so bit-unit scaling of a nonzero block-address offset is
untested); seat B checked the object-smoke direction and the `MO_BlockAddress` symbol path in
detail. Neither found a defect at Critical/Important that the other missed.
## Task 3 follow-ups
- The severity divergence was real and the fix loop needed two rounds: round 1 fixed the scheduling
bug but introduced illegal `A8` operands (caught by seat A via `-verify-machineinstrs`); round 2
used `A0`/`A1` and added the verifier to both tests.
- Seat B, whose original review had approved, caught a **stale diff** in the re-review: the diff file
described the A8 variant while the tree already carried the A0/A1 fix. It resolved the discrepancy
by verifying the head tree and flagging it explicitly — a failure mode worth remembering when
reviews and implementers overlap.
## Task 4
- Both seats converged on the same judgment: the dropped assertion only fired on constant-folded input,
so it guarded nothing real, and both paths now scale by value. No divergence.
- Seat A caught an evidence-hygiene problem nobody else would have looked for: the corpus RED log had
been overwritten by the post-fix run, so the claimed reproduction is no longer inspectable. Keep
pre-fix logs in their own work directory next time.
## Task 5
- Both seats approved and both independently re-derived the 54-row set from the skip file (52 aborts +
2 wrong results) and reconciled all three count tables.
- Seat A caught the evidence-durability problem: the load-bearing probe results lived only in an
untracked `build/` directory, which would leave an M13 engineer unable to re-inspect the claims that
killed the endianness "fix". Ruled: commit the probe sources.
- Seat B added the note that the report's "one-line" candidate is really one-flag/one-condition, and
that the stale 49-51/58 bounds should be read as history.
## Milestone summary
- Seats used: A = `deepseek/deepseek-flash` (every review), B = `opencode/tidepool-alpha-free` (every
task review), C = `opencode/nemotron-3.5-super-vl-free` (whole-branch review).
- **One genuine severity divergence:** Task 3, where seat B approved a return-address load that seat A
reproduced as a miscompile at `-O1+`. The reproducer decided it; the fix needed two rounds because
round 1 introduced illegal `A8` operands.
- **Second-seat value:** seat B caught a stale diff (round-1 text vs round-2 tree) and reasoned about
the tree; seat A caught an evidence-durability gap (probes only in `build/`); seat C contributed the
pointer↔int "invalid for the target model" analysis and the `OpNo > 0` printer guard.
- **Where the process was weakest:** two controller-supplied test/premise errors (a reject case using
a supported clobber; the `-O2` requirement for a test that only makes sense at `-O0`), and one
controller wording instruction that was simply wrong (`V` vs `v`). Each was caught by a review, but
the controller was the source.
- **Where the extra seats cost:** doubled review latency per task and several near-duplicate verdicts
on mechanical tasks (1, 4). The divergence on 3 alone justified the protocol for this milestone.
@@ -0,0 +1,451 @@
# TMS34010 runtime-abort triage (M12)
Date: 2026-11-19. Milestone: M12 (Task 5). Status: **evidence only — no
curated row was flipped and `full-suite.skip` was not modified.**
The M12 plan turns the largest remaining skip bucket into a costed list for
M13. This document is that list. Every row below was discovered from the
curated table, re-run uncurated at `-O0` and `-O2`, and assigned a cause with
runtime and source evidence. The harness is
`scripts/tests/m12/abort-triage.sh`.
## 1. Method
Discovery is mechanical, not a hardcoded list:
1. Read `scripts/tests/m7/full-suite.skip` and select every row whose reason
starts with `runtime-abort` plus every wrong-result row (reason contains
`wrong` and `result`).
2. Re-run each selected row through the standard M5 runner with the M7
driver's settings: `--classify --mode native --expect-status 0`, bare
tier, `LOADER_AT=200`, `LOADER_END=1000` (per-test overrides honored), the
driver's `-std`/`-fgnu89-inline`/`-fwrapv` dialect rules, and a 120 s MAME
timeout.
3. Run at `-O0` and `-O2`, serially, and capture the runner result, the status
word, the completion magic, and the last non-empty stdout marker.
The shipped bare checker does not expose the abort PC, and every discovered
test is silent (`stdout_len=0`). There is therefore no output marker to
compare; the table's marker column is **status-derived**: `0x86` is `abort()`
(the shim writes 134), and the two wrong-result rows return their wrong value
as the status. Where a group needed a sharper cause, a small probe was run
through the same runner; the probe sources, their run logs and the cause map
are committed under `scripts/tests/m12/probes/` (see its `README.md`).
Command and cost:
```
scripts/tests/m12/abort-triage.sh --work build/m12-abort-triage
```
108 serial MAME runs (54 rows × 2 opt levels) in **133 s**. All 108 runs
completed with magic `CONF` (`0x434F4E46`); there were no timeouts, no missing
completions, and no crash/unclassified runner rows in the baseline.
## 2. Discovered set
**54 rows**, all `c-torture`. The plan estimated 49–51 and the spec's §7.6
says 58; those numbers are stale. The 54-row table below is the Task 5
snapshot; Task 6 then removed the one flipped row (`eeprof-1`), so a re-run
of the harness now discovers 53. `m11` had 53 rows matching this rule; M12
re-reasoned `stkalign` from `inline-asm` to `runtime-abort-alignment`, adding
the 54th. The breakdown is 52 aborts plus 2 wrong results (`bitfld-6`,
`bitfld-7`).
| curated class | rows |
|---|---:|
| `runtime-abort` | 14 |
| `runtime-abort-alignment` | 3 |
| `runtime-abort-bitfield` | 9 |
| `runtime-abort-float` | 5 |
| `runtime-abort-i64` | 10 |
| `runtime-abort-varargs` | 6 |
| `runtime-abort-vector` | 5 |
| `runtime-bitfield` | 2 |
Seven rows pass at `-O2` and fail at `-O0`: `20031003-1`, `20050607-1`,
`pr123625`, `pr65427`, `pr79737-2`, `pr94412`, `scal-to-vec3`. No row passes
at `-O0`; no row fails only at `-O2`. The suite gate is `-O0`, so the `-O2`
passes do not flip any row, but they are a useful hint that generic
optimization folds away some of the `-O0` lowering bugs.
## 3. Per-file results
Status words are the runner's 8-digit hex; magic is `CONF` for every row.
The status column is the `-O0` status; the seven rows that pass at `-O2`
return `0x0` there (the raw table in `build/m12-abort-triage/abort-triage.md`
shows both opt levels explicitly). Evidence pointers are relative to
`build/m12-abort-triage/`:
`O0/O2: NAME` means `logs/-O0/c-torture/NAME.log` and
`logs/-O2/c-torture/NAME.log` (the `.rc` files sit beside them, and the
per-opt `result.txt` is under `run-O0/` or `run-O2/`). Costs are group costs
from §4 (`S` small, `M` medium, `L` large, `out` permanently out of scope).
A `probes/NAME` citation in §4–§5 means `scripts/tests/m12/probes/NAME`, where
the sources and their historical logs are committed.
| corpus/name | curated class | -O0 | -O2 | status | magic | status-derived marker | cause | cost | evidence |
|---|---|---|---|---|---|---|---|---|---|
| c-torture/20010904-1 | runtime-abort-alignment | fail:status | fail:status | 00000086 | CONF | abort (0x86) | align-packed-abi | L | O0/O2: 20010904-1 |
| c-torture/20010904-2 | runtime-abort-alignment | fail:status | fail:status | 00000086 | CONF | abort (0x86) | align-packed-abi | L | O0/O2: 20010904-2 |
| c-torture/20021127-1 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | freestanding-builtin | out | O0/O2: 20021127-1 |
| c-torture/20031003-1 | runtime-abort-float | fail:status | pass | 00000086 | CONF | abort (0x86) | float-conv | M | O0/O2: 20031003-1 |
| c-torture/20050604-1 | runtime-abort-float | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: 20050604-1 |
| c-torture/20050607-1 | runtime-abort-i64 | fail:status | pass | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: 20050607-1 |
| c-torture/20060420-1 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: 20060420-1 |
| c-torture/20080502-1 | runtime-abort-float | fail:status | fail:status | 00000086 | CONF | abort (0x86) | signed-zero | M | O0/O2: 20080502-1 |
| c-torture/20230630-1 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | endian-macro+sso | M | O0/O2: 20230630-1 |
| c-torture/20230630-3 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | endian-macro+sso | M | O0/O2: 20230630-3 |
| c-torture/920428-1 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | ptr-int-model | out | O0/O2: 920428-1 |
| c-torture/920625-1 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 920625-1 |
| c-torture/931004-10 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-10 |
| c-torture/931004-12 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-12 |
| c-torture/931004-14 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-14 |
| c-torture/931004-2 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-2 |
| c-torture/931004-4 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-4 |
| c-torture/931004-6 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-6 |
| c-torture/931004-8 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: 931004-8 |
| c-torture/991112-1 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | rts-shim | S | O0/O2: 991112-1 |
| c-torture/bitfld-3 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: bitfld-3 |
| c-torture/bitfld-5 | runtime-abort-bitfield | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: bitfld-5 |
| c-torture/bitfld-6 | runtime-bitfield | fail:status | fail:status | 00033333 | CONF | wrong result (0x33333) | endian-macro+sso | M | O0/O2: bitfld-6 |
| c-torture/bitfld-7 | runtime-bitfield | fail:status | fail:status | 00222222 | CONF | wrong result (0x222222) | endian-macro+sso | M | O0/O2: bitfld-7 |
| c-torture/eeprof-1 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | instr-flag | S | O0/O2: eeprof-1 |
| c-torture/floatunsisf-1 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | float-conv | M | O0/O2: floatunsisf-1 |
| c-torture/pr103255 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | ptr-int-model | out | O0/O2: pr103255 |
| c-torture/pr123625 | runtime-abort | fail:status | pass | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: pr123625 |
| c-torture/pr32244-1 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: pr32244-1 |
| c-torture/pr34971 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: pr34971 |
| c-torture/pr35456 | runtime-abort-float | fail:status | fail:status | 00000086 | CONF | abort (0x86) | signed-zero | M | O0/O2: pr35456 |
| c-torture/pr38051 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | ptr-int-model | out | O0/O2: pr38051 |
| c-torture/pr38151 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: pr38151 |
| c-torture/pr44575 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: pr44575 |
| c-torture/pr44683 | runtime-abort-float | fail:status | fail:status | 00000086 | CONF | abort (0x86) | signed-zero | M | O0/O2: pr44683 |
| c-torture/pr57344-3 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: pr57344-3 |
| c-torture/pr57344-4 | runtime-abort-i64 | fail:status | fail:status | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: pr57344-4 |
| c-torture/pr58209 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | ptr-int-model | out | O0/O2: pr58209 |
| c-torture/pr65401 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | endian-macro+sso | M | O0/O2: pr65401 |
| c-torture/pr65427 | runtime-abort | fail:status | pass | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: pr65427 |
| c-torture/pr79327 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | rts-shim | S | O0/O2: pr79327 |
| c-torture/pr79737-2 | runtime-abort | fail:status | pass | 00000086 | CONF | abort (0x86) | bitfield-64 | M | O0/O2: pr79737-2 |
| c-torture/pr85169 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: pr85169 |
| c-torture/pr94412 | runtime-abort | fail:status | pass | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: pr94412 |
| c-torture/scal-to-vec1 | runtime-abort-vector | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: scal-to-vec1 |
| c-torture/scal-to-vec2 | runtime-abort-vector | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: scal-to-vec2 |
| c-torture/scal-to-vec3 | runtime-abort-vector | fail:status | pass | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: scal-to-vec3 |
| c-torture/simd-1 | runtime-abort-vector | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: simd-1 |
| c-torture/simd-2 | runtime-abort-vector | fail:status | fail:status | 00000086 | CONF | abort (0x86) | vector-ops | L | O0/O2: simd-2 |
| c-torture/stdarg-3 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: stdarg-3 |
| c-torture/stkalign | runtime-abort-alignment | fail:status | fail:status | 00000086 | CONF | abort (0x86) | align-packed-abi | L | O0/O2: stkalign |
| c-torture/strct-stdarg-1 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: strct-stdarg-1 |
| c-torture/strct-varg-1 | runtime-abort-varargs | fail:status | fail:status | 00000086 | CONF | abort (0x86) | aggregate-varargs | L | O0/O2: strct-varg-1 |
| c-torture/zerolen-2 | runtime-abort | fail:status | fail:status | 00000086 | CONF | abort (0x86) | align-packed-abi | L | O0/O2: zerolen-2 |
## 4. Causes, grouped
| cause | rows | cost | one-flag/one-condition? |
|---|---:|---|---|
| aggregate varargs | 13 | L | no |
| vector arithmetic | 12 | L | no |
| 64-bit / packed bitfields | 7 | M | no |
| endianness macro + SSO | 5 | M | no (see §5) |
| packed/over-alignment ABI | 4 | L | no |
| pointer↔int model | 4 | out | no — not a compiler gap |
| signed zero / signbit | 3 | M | no |
| float↔int conversion | 2 | M | no |
| RTS / shim runtime | 2 | S–out | no |
| function-instrumentation flag | 1 | S | **yes** |
| freestanding builtins | 1 | out | no |
### 4.1 Aggregate varargs — 13 rows, L
`920625-1`, `931004-2/4/6/8/10/12/14`, `pr38151`, `pr44575`, `stdarg-3`,
`strct-stdarg-1`, `strct-varg-1`.
Every row takes an aggregate through `va_arg` (`struct tiny`, `point`,
`struct S`, `struct S1/S2`, or `__builtin_va_arg`). Seven are curated as
`runtime-abort-bitfield` but contain **no bitfields**; they are the same
`931004` aggregate-vararg family with different struct sizes. A representative
probe (`probes/va931004probe.c`) returns status 1: the very first
`va_arg(ap, struct tiny)` is wrong (`x.c != 10`); the trailing `long` is never
reached. Status is `0x86` at both opt levels.
This is the aggregate/variadic-argument ABI shape that M13 already owns, and
the largest single bucket. Cost L: one varargs/aggregate-call path, but it has
to be consistent between the caller, callee, and `va_arg` layout.
### 4.2 Vector arithmetic — 12 rows, L
`scal-to-vec1/2/3`, `simd-1/2`, `20050604-1`, `20050607-1`, `20060420-1`,
`pr123625`, `pr65427`, `pr85169`, `pr94412`.
The simplest operation is already wrong: a probe derived from `simd-1`
(`probes/simd1probe.c`) returns status `0x0A`, the line of the first
`k = i + j` check — vector **add** fails at `-O0`. Five rows pass at `-O2`
(`20050607-1`, `pr123625`, `pr65427`, `pr94412`, `scal-to-vec3`), so the gap
is in the `-O0` vector lowering/scalarization, not in vector loads/stores or
`.data` (which already pass). The remaining rows mix integer, float, `i64`,
and over-sized vector shapes and fail at both levels. Cost L: a vector
lowering family, not a single combine.
### 4.3 64-bit / packed bitfields — 7 rows, M
`bitfld-3`, `bitfld-5`, `pr32244-1`, `pr34971`, `pr57344-3`, `pr57344-4`,
`pr79737-2`.
These are fields wider than a word (33/40/41, 40, 40), packed 64-bit fields
(43/59), and a packed 18/24/15/14/1 layout. `pr79737-2` passes at `-O2`; the
others fail at both levels with `0x86`. This is extraction/insertion and
arithmetic on >32-bit (and packed) bitfields, distinct from the endianness
group. Cost M: a bounded set of wide-bitfield lowering cases, but each needs
an oracle check.
### 4.4 Endianness macro + `scalar_storage_order` — 5 rows, M
`20230630-1`, `20230630-3`, `bitfld-6`, `bitfld-7`, `pr65401`.
All five branch on `__BYTE_ORDER__`. The target's `TargetInfo` defines
`__BIG_ENDIAN__` (`__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__`) because the
unknown triple makes `TargetInfo::BigEndian` true, while the DataLayout is
`e` (little-endian) and the emitted bitfield loads/stores are little-endian.
`bitfld-6`/`bitfld-7` return wrong results (`0x33333`, `0x222222`): the
source takes the big-endian branch, but the IR extracts the **low** 20/24 bits
(`and 0xFFFFF` / `and 0xFFFFFF`), which is the little-endian extraction.
The evidence for the macro half is a frontend-only override
(`probes/` runs with `-U__BIG_ENDIAN__ -D__BYTE_ORDER__=1234`):
- `bitfld-6`, `bitfld-7`, `20230630-3`, `pr65401` pass at both `-O0` and
`-O2` with the override.
- `20230630-1` passes at `-O2` and through the full-loader tier at `-O0`,
but the bare tier **host-segfaults** at `-O0`; that is the same class of
bare-MAME instability already listed in `full-suite.full-loader`.
- The same override **regresses two currently passing rows**:
`20230630-2` (full-loader) and `20230630-4` (native) fail because they
select `scalar_storage_order("big-endian")` once the macro flips, and this
target does not honor the reversed storage order. They only pass today
because the macro is wrong in the matching direction.
So this is not a clean one-flag/one-condition fix: the macro and
`scalar_storage_order` must be corrected together. That is why the apparent
`BigEndian = false` single change is rejected in §5. Cost M, with a regression
guard on the two `20230630-*` passers.
### 4.5 Packed / over-alignment ABI — 4 rows, L
`20010904-1`, `20010904-2`, `stkalign`, `zerolen-2`.
Probes:
- `probes/astkalign.c` returns `1` for `__alignof__(struct { char c
__attribute__((aligned(64))); })`: the requested 64-byte member alignment
is clamped.
- `probes/azerolen.c` returns `2`: `sizeof(word) == sizeof(struct foo)` but
`__alignof__(word) != __alignof(struct foo)`.
- `20010904-*`: the linked `.bss` gives `Y` a stride of 1028 bytes (two `Y`
objects are 2056 bytes), not the 32-byte-aligned 1056; the test's
`(char *)&y[1] - (char *)&y[0]` is therefore `4 mod 32`, and the check is
legitimately true. The `if (expr & 31)` form folds to `true` while the
`return expr & 31` form folds to `0`; that fold disagreement is a second
symptom of the same layout confusion.
The root is the target's packed-struct policy (`Opts.PackStruct = 1`,
`UseBitFieldTypeAlignment = false`) not honoring over-alignment on members
and structs. Cost L: an ABI-level layout change, and it needs a decision about
what the 1987-compatible packed rule should do with `aligned(N)`.
### 4.6 Pointer↔integer model — 4 rows, out
`920428-1`, `pr103255`, `pr38051`, `pr58209`.
These test `(int)/(long)/(size_t)ptr` arithmetic as if a pointer value were a
byte address. On this ABI it is a **bit** address: a probe
(`probes/ptrdiff.c`) returns status `8` for
`(int)&a[1] - (int)&a[0]` with `char a[2]`. The tests then add byte counts to
integer-cast pointers (`ss + 1`, `srcp1 += 1`, `s + sizeof(T)`) or compare a
pointer cast to a byte address, so they are invalid for the target model, not
miscompiled. `pr103255` additionally compares `(size_t)&h->b` with
`ADDR + OFF + offsetof` as a byte address. Curate these with the bit-pointer
reason; no M13 code change.
### 4.7 Signed zero / signbit — 3 rows, M
`20080502-1`, `pr35456`, `pr44683`.
Probes: `pr35456` returns `1` (`not_fabs(-0.0)` loses the sign), `pr44683`
returns `3` (`__builtin_copysign(1.0, -0.0) < 0.0` is false), and `20080502-1`
returns `1` (`long double` signbit / literal comparison). The first two are
`-0.0` sign preservation and `copysign`; `20080502-1` may be the long-double
representation. Cost M: a small set of float semantics, but each needs its own
oracle.
### 4.8 Float↔int conversion — 2 rows, M
`20031003-1`, `floatunsisf-1`.
Probes: `20031003-1` returns `3` — **both** `(int)2147483648.0f` and
`(int)(float)2147483647` differ from `INT_MAX`; `floatunsisf-1` returns `1`
(`(float)volatile 0x80000081` differs from the literal conversion). The former
is C UB (out-of-range conversion) that GCC nevertheless tests; the latter is
a real unsigned→float rounding case. `20031003-1` passes at `-O2`. Cost M.
### 4.9 RTS / shim runtime — 2 rows, S–out
- `991112-1`: the test calls `isprint`. The 1990 `rts.lib` `_isprint` reads
`__ctypes_` at `01A080A0`, which is zero in the bare tier; a probe returns
status 2 (`isprint('a')` is false). This is a bare-tier runtime setup gap,
not compiler codegen.
- `pr79327`: a probe for `%#hhx` of 0 returns `3` (`"0x0"`); `sdk/shim.c`
documents this as a **known pre-existing M5 deviation** (C says `"0"`,
one byte) kept byte-identical. It is not a compiler gap; changing it would
move the documented shim output and gates.
### 4.10 Function-instrumentation flag — 1 row, S
`eeprof-1` carries `dg-options -finstrument-functions`, but
`full-suite.sh`'s `dialect_flags()` forwards only `-std`,
`-fgnu89-inline`, and `-fwrapv`. Without the flag no
`__cyg_profile_func_enter/exit` calls are emitted, so the test's counters stay
zero and it aborts. Running the unmodified test with the flag passes at both
`-O0` and `-O2`. This is a driver omission, not a compiler bug; it is the one
one-flag/one-condition candidate in §5. Task 6 took it: `dialect_flags()` now
forwards the flag per row, the row was removed from `full-suite.skip`, and the
gate suite passes it (see §9).
### 4.11 Freestanding builtins — 1 row, out
`20021127-1` calls `llabs(-1)` after defining `llabs` to `abort()`. The TMS
driver forces `-ffreestanding -fno-builtin`, so Clang does not recognize
`llabs` as a library builtin and calls the aborting definition. Host Clang
folds the same file to `llvm.abs.i64`. This is the target's freestanding
policy, not a TMS codegen gap; curate it as such (or revisit hosted mode
outside M13).
## 5. One-flag/one-condition ruling
At most three one-flag/one-condition fixes may be proposed for M12. The triage
supports **one**; the strongest-looking single-change compiler candidate is
explicitly rejected.
### Accepted candidate (harness, not compiler): forward `-finstrument-functions`
Add the flag to `dialect_flags()` in `scripts/tests/m7/full-suite.sh` when the
source's `dg-options` asks for it. Why it qualifies:
- Single shared cause: the driver drops one dg-option; the test compiles and
passes unchanged when it is forwarded (verified at `-O0` and `-O2`).
- One flag/one condition, one row affected (`eeprof-1`), no other abort row
requests the flag, and no compiler or ABI change.
- It is a harness fix, so it was taken as its own Task 6 commit: the
`eeprof-1` curated row is removed with the recorded flip. This Task 5
document did not edit the skip file.
### Rejected: `BigEndian = false` in `TMS34010TargetInfo`
This looked like the textbook one-flag/one-condition candidate: it would make
`__BYTE_ORDER__` agree with the little-endian DataLayout and flips `bitfld-6`, `bitfld-7`,
`20230630-3`, and `pr65401` at both levels (and `20230630-1` through the full
loader). But the same change flips `20230630-2` and `20230630-4` from pass to
`0x86`, because they then select `scalar_storage_order("big-endian")`, which
the target does not honor. A single-change fix that regresses two passing rows
is not a clean single-cause fix. The endianness macro and
`scalar_storage_order` belong together in M13.
### Rejected: shim `%#x`/`%#X` zero prefix
`pr79327` would flip if `emit_uint()` stopped printing `0x` for zero, but the
deviation is explicitly documented in `sdk/shim.c` as a pre-existing M5
byte-identical behavior. Changing it would move shim output and gate bytes;
not a safe M12 one-flag fix.
No other group qualifies: varargs, vectors, wide bitfields, alignment,
signed zero, and conversions are multi-line lowering/ABI work; pointer↔int
and freestanding builtins are target-model/policy, not defects to fix.
## 6. Proposed M13 scope
Ordered by files affected, with cost and dependencies. The counts cover 54
rows; 25 of them (varargs + vectors) are the first two items.
| order | cause | rows | cost | note |
|---:|---|---:|---|---|
| 1 | aggregate varargs | 13 | L | overlaps M13's ABI-shape work; one caller/callee/`va_arg` contract |
| 2 | vector arithmetic | 12 | L | `-O0` lowering/scalarization; 5 rows already pass at `-O2` |
| 3 | 64-bit / packed bitfields | 7 | M | wide and packed extraction/insertion; oracle-backed |
| 4 | endianness macro + SSO | 5 | M | fix `__BYTE_ORDER__`/`BigEndian` **and** reversed storage order; guard the two `20230630-*` passers |
| 5 | packed/over-alignment ABI | 4 | L | `aligned(N)` under the packed default; ABI decision first |
| 6 | signed zero / signbit | 3 | M | `-0.0`, `copysign`, long double |
| 7 | float↔int conversion | 2 | M | `20031003-1` is UB; decide whether to chase GCC's answer |
| — | pointer↔int model | 4 | out | re-curate with the bit-pointer reason; no code |
| — | RTS / shim runtime | 2 | out | bare-tier `__ctypes_` / documented `%#x` deviation |
| — | freestanding builtins | 1 | out | `-ffreestanding -fno-builtin` is deliberate |
| M12 (done) | instrumentation flag | 1 | S | the accepted one-flag/one-condition harness fix; `eeprof-1` flipped in Task 6 |
Suggested M13 execution order: **varargs → vectors → wide bitfields →
endianness+SSO → alignment**. Take the two float groups after the structural
work, and keep the four pointer↔int rows and the two runtime rows curated
with accurate reasons rather than spending M13 on them.
## 7. Curated label vs actual cause
The curated labels are not a cause taxonomy. This is the most important input
for M13 planning:
| curated class | rows | actual causes |
|---|---:|---|
| `runtime-abort` | 14 | 4 vector, 3 endianness, 2 pointer↔int, 2 RTS/shim, 1 alignment, 1 wide bitfield, 1 instrumentation |
| `runtime-abort-alignment` | 3 | 3 packed/over-alignment |
| `runtime-abort-bitfield` | 9 | **7 aggregate varargs**, 2 wide bitfields |
| `runtime-abort-float` | 5 | 3 signed zero, 1 conversion, 1 vector |
| `runtime-abort-i64` | 10 | 4 wide bitfields, 2 vector, 2 pointer↔int, 1 conversion, 1 freestanding builtin |
| `runtime-abort-varargs` | 6 | 6 aggregate varargs |
| `runtime-abort-vector` | 5 | 5 vector |
| `runtime-bitfield` | 2 | 2 endianness |
In particular, the `i64` label contains **no** plain 64-bit-codegen row: its one
conversion row (`floatunsisf-1`) is float↔int, and the rest are wide
bitfields, vectors, or pointer↔int. The `931004-*` rows are the clearest
mislabel: seven vararg tests curated as bitfields.
## 8. Limits and concerns
- **No abort PC.** The bare checker writes only the result block; it has no
PC hook, and every discovered test is silent. The status word plus the
source predicate is the evidence, and representative probes localize the
group causes. A future harness could tap the `abort` symbol/return address
in MAME, but that is a runner change, not this triage.
- **Probes are representative, not exhaustive.** The 13 varargs rows share the
same `va_arg` shape; one probe proves the first aggregate is wrong. The 12
vector rows share lowering; one probe proves vector add is wrong. Individual
rows may have additional causes (e.g. `pr123625` also has `i64` and `switch`
structure), which M13 will find when it touches each family.
- **`-O2` passes are not correctness evidence.** They show generic
optimization can fold the failing shape; the suite gate is `-O0`.
- **`20031003-1` is C UB** (out-of-range float→int). It is listed as a
conversion difference, not a promise to match GCC's saturated answer.
- **`20230630-1` has a bare-tier host segfault** once its check passes. Any
endianness fix must either add it to `full-suite.full-loader` (it passes
there) or resolve the MAME instability first.
- **The endianness one-flag change is a trap.** The regression on `20230630-2/-4`
is the reason it is not proposed; record it before M13 starts.
## 9. Raw evidence
- Harness: `scripts/tests/m12/abort-triage.sh`
- Raw Markdown table: `build/m12-abort-triage/abort-triage.md`
- Machine-readable tables: `build/m12-abort-triage/abort-triage.tsv`,
`build/m12-abort-triage/abort-triage.evidence.tsv`
- Per-test logs and results: `build/m12-abort-triage/logs/` and
`build/m12-abort-triage/run-O0/` / `run-O2/`
- Representative probe sources: `scripts/tests/m12/probes/` (with its
`README.md`, `cause-map.tsv` and historical `logs/`); the same files were
originally written under `build/m12-abort-triage/probes/`
## 10. Task 6 outcome
`eeprof-1` is the only row this triage fixes in M12. Task 6 added
`-finstrument-functions` forwarding to `dialect_flags()` (per row, when
`dg-options` asks for it), verified the unmodified test at `-O0` and `-O2`
through the M5 runner, and removed the curated row. The other 53 rows stay
curated with the causes above and are M13's input. The suite accounting moves
by this one row (1,618 → 1,635 pass, 294 → 277 skip across all M12 flips; see
the README's M12 section for the per-row list).
@@ -71,21 +71,28 @@ early GEP-scaling pass.
- Registers: A0–A12 general, A8 return value, A13 FP, A14 STK (program stack),
A15 system stack. B0–B14 are unused by TI's C compiler.
- Caller: if arguments are passed or a float/double is returned, push the old
STK on the system stack (`MOVE STK,-*SP`); push arguments on the program
stack in reverse order, widened to 32 bits; structs by value rounded to
16 bits; struct return address pushed on the program stack; call with
`CALLA` (direct) or `CALL Rs` (indirect).
- Caller: if arguments are passed or a float/double/`i64`/aggregate is
returned, push the old STK on the system stack (`MOVE STK,-*SP`); reserve
the hidden return slot (if any) at the top of the program stack **before**
saving STK; push arguments on the program stack in reverse order, widened
to 32 bits; structs by value rounded to 16 bits; call with `CALLA` (direct)
or `CALL Rs` (indirect). There is no `sret` pointer argument in the TI
ABI.
- Callee: save used A registers except A8 on the system stack (`MMTM SP,…`);
set `FP = STK`; `ADDI frame_size,STK`; locals at positive FP offsets, first
argument at `FP(-32)`; restore STK from `*SP(offset)`; `MMFM`; `RETS 2` if
arguments or stack return, `RETS 0` otherwise.
- `FS1` must be 32 inside C code and `FE0` must be 0; `FS0` may be changed
without restoring. Xlib clobbers the field-size state, so FS1 must be
re-established after every call.
- Struct return: caller allocates, pushes the address; callee copies. Float/
double return: caller allocates space on the program stack, callee copies.
(C guide §5.3.)
- `FS1` must be 32 inside C code and `FS0` must be 16 with its field-extension
bit set (`SETF 16,1,0`, sign-extending); both must be re-established after
every call because Xlib may change the field-size state.
- Hidden returns: the caller reserves `alignTo(size,2)` bytes at the top of
the program stack (before saving STK) for a struct/union, `float`/`double`
or `i64` result; the callee copies the object bytes to `saved_STK-size`
(the top of the slot) and ends `RETS 2`; the caller copies the bytes out
and releases the slot. The caller does not push a return address. Float/
double and `i64` use the same rule with a 4/8-byte object. (The 1987
`_mkbig`/`_callbig` oracle in the plan and `TMS34010.md` binds this form;
it supersedes the earlier sret wording in this document.)
- Symbols use a leading underscore (`_main`); sections are `.text`, `.data`,
`.bss`; code is position-dependent and linked at fixed bit addresses.
@@ -263,16 +270,22 @@ non-constant pointer expression by 8×.
- Custom calling convention `CC_TMS34010`.
- `LowerFormalArguments` / `LowerCall` / `LowerReturn` implement the caller and
callee rules in §4.2 exactly; `sret` and `byval` follow the TI layout.
callee rules in §4.2 exactly; `byval` follows the TI layout. An explicit
`sret` pointer is rejected: aggregate returns use the hidden slot above.
- **Explicit arguments**: pushed on the program stack (A14) in reverse order,
each widened to 32 bits. The first explicit argument is at `FP(-32)`, the
second at `FP(-64)`, etc.
- **Struct return**: the caller pushes the return-space address **after** the
explicit arguments, so it is the top program-stack slot: the callee reads it
at `FP(-32)` and the first explicit argument is at `FP(-64)`.
- **Hidden return slot**: for a struct/union, `float`/`double` or `i64`
result, the caller reserves `alignTo(size,2)` bytes at the top of its own
frame **before** saving STK and passes no return pointer. The callee
writes the object at `saved_STK-size` (= `FP-(argbytes+size)`) and ends
`RETS 2`; the caller copies the bytes out and releases the slot with
`ADDI -size,STK`. This is the 1987 `_mkbig`/`_callbig` form and supersedes
the earlier sret wording; an explicit `sret` argument is rejected.
- **Old STK**: the caller saves A14 on the system stack only when it passes
arguments or the callee returns a float/double. A no-argument function with
locals has no saved old STK; the callee restores STK from FP before `RETS 0`.
arguments or the callee returns a `float`/`double`/`i64`/aggregate through
the hidden slot. A no-argument function with locals has no saved old STK;
the callee restores STK from FP before `RETS 0`.
- **System stack layout** (grows down), after the callee's `MMTM` of `n`
registers:
@@ -324,7 +337,7 @@ non-constant pointer expression by 8×.
MAME, and the byte-exact ROM round-trip.
- Loads/stores: misaligned accesses allowed; `MOVB` for i8, `MOVE` with FS0 for
i16, `MOVE` with FS1 for i32/pointers; i64 as two 32-bit accesses. Ensure
FS1 is 32; use FS0 for 16-bit.
FS1 is 32 and FS0 is 16 sign-extending; use FS0 for 16-bit.
- `memcpy`/`memmove`/`memset`: lower to byte/word loops; lengths are bytes,
addresses bits; overlap semantics for `memmove`.
- `alloca`/VLA: size ×8; 16-bit alignment for standalone objects.
@@ -434,7 +447,502 @@ 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.
### M8 — object/link completeness, conformance depth, hardware
M8 closes the M7/M8 boundary in four workstreams, using the same plan,
subagent-driven execution, review and push discipline as M7. The `m7` branch
is the M8 baseline and the repository default; M8 work is on `m8` and does not
change the default unless the user asks.
- **M8.1 — native `.lib` linking.** `tools/tms-link` reads System V/`ar`
archives (the 1990 `flib.lib`/`rts.lib` are `!<arch>` with TI-COFF members),
performs iterative selective extraction of members that define needed
symbols, resolves duplicate/undefined symbols loudly, and exposes the
libraries through the CLI and the `M4_LINKER=tms-link` path. GSPLNK remains
the oracle; the M5/M6 native and runtime gates must produce the same
allocated bytes/symbol addresses (and MAME markers) with either linker.
Acceptance: M4/M5/M6 native links that need `flib`/`rts` link with
`tms-link`, produce a loader-accepted image with the expected markers, and
match GSPLNK on the allocated image; unmatched/duplicate archive symbols
fail loudly.
- **M8.2 — multi-TU DWARF merging.** The native linker merges debug
information from multiple debug-bearing objects: concatenate `.debug_info`
CUs while adjusting `.debug_abbrev`/`.debug_str_offsets`/`.debug_addr`/
`.debug_line` section-relative contributions and their relocations; keep
section-relative offsets correct, resolve line/file tables, and validate the
result with `llvm-dwarfdump`. The default load image remains debug-stripped;
`--keep-debug` is the tool image. Acceptance: a two- or three-TU program
built with debug info links with `--keep-debug`, `llvm-dwarfdump` reports
every TU's functions/lines/addresses, and the stripped image still runs in
MAME; a single-TU link remains byte-compatible with M7.
- **M8.3 — conformance depth and performance.** Raise the full-suite pass
rate by fixing or honestly re-curating the remaining classes (codegen
rotates/`cttz`/`bswap`/`blockaddress`/vectors, inline-asm constraints,
sret/aggregate/variadic/float returns, VLAs, nested functions, libm and the
frame-limited timeouts), and extend performance work beyond the 32-bit i64
fast path (e.g. a 64/32 path when the divisor fits 32 bits) with measured
evidence. Acceptance: the full pinned corpora still account for every file
with 0 unclassified crashes and an honest skip list; the newly fixed classes
flip to pass and are recorded; any new performance path is measured against
the existing slow path.
- **M8.4 — hardware and close-out.** Run the real VT1200 hardware harness when
the unit is available (the harness and MAME-equivalent acceptance already
exist), record the real-unit evidence, and produce the final M8 docs/counts/
limitations and the M8/M9 boundary. The hardware run remains deferred and
does not block M8.1–M8.3; if it is still unavailable, mark it deferred and
state that explicitly.
M8.3 also runs the corpora on a bare-metal MAME tier by default (sections
mapped, `.bss` zeroed, PC/SP set, no firmware/loader), using the 2ine-hosted
1990 OS/2 assembler and `tms-link`; the curated M5/M6 loader gates, X11/runtime
and an explicit full-loader exception list keep the loader tier. The accounting
and acceptance counts are unchanged.
M8.1 acceptance: a library-only link (no GSPLNK) resolves the needed members
and runs; M8.2 acceptance: multi-TU debug links and validates; M8.3
acceptance: the full corpora remain fully accounted with the recorded flips;
M8.4 acceptance: the final docs/boundary are accurate and the hardware status
is explicit.
M8 acceptance (met, M8 complete): `tms-link` reads the System V `ar`
`FLIB.LIB`/`RTS.LIB`, extracts needed members iteratively and links the M4/M5/
M6 library programs with allocated bytes, section metadata and public symbols
equal to GSPLNK 2.00 (`scripts/tests/m8/native-lib.sh`, 3 sections, 16 public
`C_EXT` addresses, MAME markers). Multi-TU `--keep-debug` concatenates and
rehomes the supported DWARF5 sections; `llvm-dwarfdump` shows both TUs'
functions, lines and linked PCs, the stripped image runs in MAME, and the
single-TU link is byte-identical to M7 (`scripts/tests/m8/dwarf-multi.sh`).
The bit-op class (rotate/`cttz`/`ctpop`/`ctlz`/`bswap`) lowers without invented
instructions. At M8 the three-phase gate measured the 64/32 i64 divide path at
**218** frames versus **2,440** for the 64-step loop (11.2×) and the fits-32
path at **87** (28.0×), status `600D600D`, checksums
`000000011E6F9AB4`/`00000000007512AE`/`00025AF70AF974E0`; M9.3 makes the gate
four-phase, narrows the wide input to force the two-`DIVU` helper, and re-pins
the wide checksum (see the M9 acceptance). The fresh end-to-end full suite
accounts for **1,912 = 1,596 pass / 316 skip / 0 fail / 0 crash** (c-torture
**1,386 / 306**, c-testsuite **210 / 10**), with 64 classifier plus 252
curated skips, each with a reason; the 20 flipped rows are the six rotates,
six `cttz`, four `bswap` and four per-test `LOADER_END=2000` runtime rows.
Lit is **120/120** (116 CodeGen + 4 MC) and clang Sema/CodeGen **5/5**. The
real VT1200 run remains **DEFERRED** (`VT1200_HOST` unset; the hardware gate
prints `HARDWARE: DEFERRED` on the MAME-equivalent acceptance). M9 closed vector
`.data` and inline-asm `r`, the DWARF future-producer/`.debug_rnglists`
caveats and the 64/32 divide path; M10 owns the remaining classes
(`blockaddress`, vector runtime, inline-asm memory constraints, nested
functions, VLAs, sret/aggregate/variadic/float returns, libm, runtime aborts),
the pre-existing `pr63843` hang, further performance work and the real VT1200
run when the unit is available.
### M9 — conformance classes, debug depth, performance
M9 builds on the M8 baseline (`m8`, default) and uses the same plan,
subagent-driven loop, review and push discipline. Work is on `m9`; the default
is promoted to `m9` only after the final review, per the repository policy.
- **M9.1 — conformance classes.** Remove the highest-value remaining M8 skips:
vector `.data` initializers (integer/fp vector constants emitted as their
exact element bytes in the raw and object paths) and inline-asm `r`/`=r`
register constraints (map the target's A-register classes; reject
unsupported constraints loudly). The affected full-suite rows must flip to
pass and be recorded; `blockaddress`, nested functions, VLAs, sret/
aggregate/variadic/float returns and libm remain explicit M10 boundaries.
- **M9.2 — debug/linker depth.** Replace the M8 raw-offset assumption with a
form-aware DWARF walker (or an input gate that rejects any unrelocated
section-relative field), add a `.debug_rnglists` fixture and merged-range
validation, and keep the single-TU output byte-compatible. The default load
image stays stripped; `--keep-debug` remains the tool image.
- **M9.3 — performance.** Add a single `DIVU` 64/32 fast path when the divisor
fits 32 bits and the quotient fits (or another equally justified path),
measured against the M8 64/32 two-DIVU path and the 64-step loop. The bare
conformance tier remains the default; no test-accounting regression.
- **M9.4 — hardware and close-out.** Run the real VT1200 harness when the unit
is available; otherwise keep `HARDWARE: DEFERRED` explicit. Produce the final
M9 docs/counts/limitations and the M9/M10 boundary.
M9 acceptance (met, M9 complete): vector `.data` and inline-asm `r`/`=r`
constraints are fixed with **22** recorded flips (20 inline-asm `r`, `simd-5`
and `pr123625-2`), and the five remaining candidates stay curated with
corrected reasons (i64 `r` pair, timeout, two vector runtime aborts, memory
operand). Lit is **129/129** (125 CodeGen + 4 MC). The multi-object
`--keep-debug` path walks every form and refuses pre-v5 producers and any
unrelocated section-relative field loudly; the two-TU `.debug_rnglists`
fixture and a real `-O2 -g` producer both validate with `llvm-dwarfdump`, the
single-TU bytes keep the M8 layout, and the stripped image still runs. The
four-phase i64 gate measures fast **88**, slow **3,302**, wide **221** and
div32 **120** frames — **37.5×** (fast) and **14.9×** (wide) versus the loop,
and **1.8×** for div32 versus the two-DIVU wide phase — with
status `600D600D` and checksums `000000011E6F9AB4`/`00000000007512AE`/
`F56810CFEDA9D656`/`00002C61C63842EE`; the new path is correct for
signed/unsigned, divide-by-zero UB, and `INT64_MIN` (which never fits 32 bits:
it keeps the two-step helper for a divisor of at most `2^31` and takes the
single-`DIVU` path for a divisor in `(2^31, 2^32)`). The fresh two-tier full
suite accounts for every file: **1,912 = 1,618 pass / 294 skip / 0 fail / 0
crash** (c-torture **1,408 / 284**, c-testsuite **210 / 10**), with every skip
carrying a reason and the 10 full-loader exceptions explicit. Every M2–M8.4
gate stays green and the new M9 lit/DWARF gates pass, while the real VT1200
run remains **DEFERRED**. M9 is complete; the remaining classes are the M9/M10
boundary.
### M10 — the native clang pipeline (Phase 2)
M10 moves the bit-address transform and this target's compile defaults into
the target, so native `clang --target=tms34010 -c` is correct for pointer code
at `-O0` and `-O2` with **no extra flags
and no wrapper**. `m10` is the repository default (the promotion lands with this
push; `m9` is the previous snapshot). The binding design is
`2026-11-17-tms34010-phase-2-3-design.md` §7.
- **The `ToolChain`.** A minimal `clang/lib/Driver/ToolChains/TMS34010.{h,cpp}`
(`BareMetal` subclass, registered in `CMakeLists.txt`/`Driver.cpp`) supplies
`-ffreestanding`, `-fno-builtin`, `-mllvm -replexitval=never`,
`-disable-O0-optnone` and no system includes; `-c`/`-S` are the surface (no
link job yet).
- **The pipeline.** `registerPassBuilderCallbacks` runs the
`@__tms_bitptr` barrier at pipeline start (plus lowering at `-O0`) and
scale → lower → final InstCombine at optimizer-last (gated to `Level != O0`);
a `"tms.bitaddr"` module flag (absent → `1` → `2`) makes it idempotent, and a
legacy lowering pass in `addISelPrepare` is the codegen safety net.
- **`tms-clang`** becomes a thin flag mapper; the four gates that traced its
internals assert the same invariants at the driver seam.
M10 acceptance (met, M10 complete): native
`clang/test/CodeGen/TMS34010/bitaddr-o0.c`/`bitaddr-o2.c` pin `p[1]` → `ADDI
32` (i32), `ADDI 16` (`short`), `ADDI 32` (`char p[4]`) at `-O0` and `-O2`, and
an ordinary `sumto` loop compiles at `-O2` with no extra flags;
`bitaddr-static-vararg.c` pins the guard at `-O0`/`-O1`/`-O2`,
`float-const-o2.c` pins the pre-optimizer f32/f64 constant protection, and
`tms34010-defaults.c` pins the `ToolChain` defaults. Native `-O0` (and `-O0
-g`) objects are **byte-identical** to the M9 path across the 23-file corpus
(`scripts/tests/m10/equivalence.sh`, **46/46** at `-O0` and `-O0 -g`);
idempotency is
`scripts/tests/m10/bitaddr-idempotent.sh`. TMS34010 lit is **132/132** (128
CodeGen + 4 MC) and clang is **10** (8 CodeGen + the driver
`tms34010-defaults.c` + the Sema subbyte-stride test), for **142** lit in
total; the serial M0–M8 gate list is **58 invocations across 54 distinct gate
scripts, all passing**, with `HARDWARE: DEFERRED`.
The fresh two-tier full
suite is unchanged at **1,912 = 1,618 pass / 294 skip / 0 fail / 0 crash**, the
four-phase i64 gate is unchanged at fast **88** / slow **3,302** / wide **221** /
div32 **120** frames (37.5× / 14.9× / 1.8×, checksums
`000000011E6F9AB4`/`00000000007512AE`/`F56810CFEDA9D656`/`00002C61C63842EE`),
and the hardware run remains **DEFERRED**. `m5/jr.sh` re-pins the linked
`.text` to **910** bytes (the first M10 pin of 850 was measured through the
pre-fix `-O2` bit-offset-aliasing and float-constant-folding hazards; the
correctness fixes below cost instructions and restore the M9 legacy value;
the JR count is unchanged).
The `-O2` bit-address aliasing gap is fixed with three changes. (1)
DAGCombiner's `BaseIndexOffset` aliasing reads address offsets in **bytes**, so
every target-computed bit offset now routes through a `TMS34010ISD::BITADDR`
node (selected straight to `ADDI`) for the f64/i64/aggregate return-slot and
hidden-return reads; `BaseIndexOffset` does not match the custom node, so
aliasing falls back to the byte-accurate `MachinePointerInfo` and the
program-order chain is kept, and a zero offset stays the base itself so `-O0`
objects remain byte-identical. (2) `f32`/`f64` literals are protected
**before** the optimizer: `TMS34010LowerFloatConstantsPass` runs at clang
pipeline start for `-O1`+ and replaces each literal store/return/argument with
a volatile load from a GSP-initialised global, so the middle-end cannot fold
`bitcast(float C to i32)` to IEEE bits (the late llc pass keeps plain loads and
still covers `-O0`). (3) Closing those two exposed the underlying class: any
address built as `inttoptr(add(ptrtoint, bits))` folds to a plain `ISD::ADD` on
this 32-bit-pointer target, so ordinary source pointer arithmetic was still
miscompiled at `-O2` (reproducer `p[0]=v; p[1]=w; ((char*)p)[5]=0x7f;` stored
the byte before the word store). This is the bit-address aliasing mechanism,
fixed by a target intrinsic `llvm.tms34010.bitaddr` that lowers to `BITADDR` and
is now used by **every** runtime pointer-offset emitter — the barrier lowering,
the aggregate/i64/narrow-mem leaves and both GEP-scaling passes (regression
tests `m10-bitaddr-chain-i64.ll`, `bitaddr-chain-o2.c`). The residual is
documented: `scaleConstantGep` emits a compile-time `ConstantExpr` address,
which cannot hold a call, so it folds to a `GlobalAddress+offset` and no
runtime `ADD` exists to mis-decompose (not reachable at `-O2`). With
these, `m6/float.sh` (8 float markers), `m6/aggregate.sh` (2 markers),
`m6/i64.sh`, `m6/bitfield.sh`, `m6/varargs.sh` and `m6/runtime.sh` all pass at
`-O0` and `-O2`. `scripts/m3/run.sh` compiles `branch` with `-fno-inline` at
`-O2` (chosen over `-O0` to keep the pinned condition codes), so
`m3/dis-roundtrip.sh` keeps its `_sumto`/`_max2`/`_lt` calls to check. The
**M10/M11 boundary** is Phase 3: a committed CRT
(`crt0.o` via `llvm-mc`), headers, `libtms.a`, a sysroot and a `tms-link` link
job, so `clang --target=tms34010 hello.c -o hello` works with no wrapper.
(The M11 design corrected the CRT build path: `llc -filetype=obj`, not
`llvm-mc` — see the M11 section below.)
### M11 — the conventional toolchain (Phase 3)
M11 closes the gap between "a compiler that emits objects" and "a toolchain you
can use": `clang --target=tms34010 hello.c -o hello` links a loader-valid TI-COFF
image through `tms-link`, with a CRT, headers and a C library discovered through
a sysroot — after one `scripts/tms-sdk`. The binding design is
`2026-11-18-tms34010-m11-conventional-toolchain-design.md` §8.
- **The sysroot.** `scripts/tms-sdk [--sysroot DIR]` builds `sdk/crt0.ll` with
`llc -march=tms34010 -filetype=obj` and `sdk/{shim,heap}.c` with
`clang --target=tms34010 -O2 -c` plus `llvm-ar rcsD` into `libtms.a`, then
installs `<sysroot>/{include,lib,bin}`: the **10** headers (`assert, limits,
math, stdarg, stdbool, stddef, stdint, stdio, stdlib, string` — there is no
`ctype.h`), `lib/{crt0.o,libtms.a,flib.lib,rts.lib}` and the
`tms-link`/`tmscoff.py` pair. The default sysroot is
`<clang -print-resource-dir>/tms34010-unknown-none`; `--sysroot DIR` installs
elsewhere (the driver then needs `--tms-sysroot=DIR`). Installing is
idempotent: `llc` and `llvm-ar rcsD` rebuild byte-identically.
- **The CRT.** `sdk/crt0.ll` is a `naked` `_start` with inline asm blocks, built
by `llc -filetype=obj`: `llvm-mc` emits ELF for this triple (and the generic
COFF path refuses a non-Windows triple), so the target's TI-COFF writer is
reachable only through CodeGen. The rewrite preserves the contract, not the
text: `setf 16/32`, the 4 KiB `_cstack`, the `{"conformance", NULL}` argv, the
result block at `01B00000`/`40`/`60`, the output buffers `01B10000`/`01B30000`,
and the `_start` symbol for `--entry`.
- **The link job.** `TMS34010Linker` invokes `<sysroot>/bin/tms-link` (or
`--tms-linker=PATH`) with `--entry _start --text 018A0000 --bss 01A00000
--prog-len 40000h --ram-len 80000h`, a default `--map`, `-g` → `--keep-debug`
(not `-g0`/`-ggdb0`), `-Wl,` passthrough (with `-Map=`/`-Map,<file>`
translated to `--map=<file>`), the CRT, the user objects, `libtms.a flib.lib
rts.lib`, `-L <sysroot>/lib` and the user `-L`/`-l`. A missing
sysroot/linker/`python3` is a named diagnostic pointing at `scripts/tms-sdk`
(except `python3`, which names installing `python3`) — `python3` is a
link-time dependency because `tms-link` is a Python program. A sysroot
directory that exists but lacks `crt0.o`/`libtms.a`/`flib.lib`/`rts.lib`
names the missing artifact instead of handing `tms-link` a bare name.
- **Link-reduction knobs.** `-nostartfiles` drops `crt0.o`, `-nodefaultlibs`
drops `libtms`/`flib`/`rts`, `-nostdlib` implies both. `-l tms` links
`libtms.a` once per request (a repeated `-l tms` links the archive again).
- **`tms-cc`** stays as a compatibility alias; new documentation points at
`clang --target=tms34010`.
M11 acceptance: `scripts/tests/m11/{sdk,crt,e2e}.sh` PASS — the headline
command from a clean shell, two TUs, `-c`/`-S`/`-E`, `-O0`/`-O2`, `-g` vs
stripped, `-nostdlib`, and the no-checkout-path assertion. TMS34010 lit is
**132/132** (128 CodeGen + 4 MC), clang **13** (10 CodeGen + 2 Driver + 1 Sema),
`tools/tms-link`/`tools/tms-bitaddr` tests PASS, the two-tier suite is unchanged
at **1,912 = 1,618 pass / 294 skip / 0 fail / 0 crash**, the four-phase i64
gate is unchanged at fast **88** / slow **3,302** / wide **221** / div32 **120**
frames (37.5× / 14.9× / 1.8×, checksums `000000011E6F9AB4` /
`00000000007512AE` / `F56810CFEDA9D656` / `00002C61C63842EE`), and
`HARDWARE: DEFERRED`. The linker emits images that pass
`scripts/m4/coff-check.py` unaided: M11 moved the `.bss` rounding into
`tms-link`, so `coff-check.py --repair` is no longer on the production path (it
survives only for the legacy GSPLNK harness). Known limitations: a bare
`-Wl,-Map` sets an explicit-map request but names no file, so it suppresses the
default map and produces none (use `-Wl,-Map=<file>`) — and a repeated `-l tms`
under `-nodefaultlibs` duplicates the archive. The Task 6
sweep's one stale M7 gate check was fixed in `7fcae6e`: `m7/debug.sh` now
asserts the `llvm.tms34010.bitaddr` spelling (the M10 aliasing fix replaced the
`add i32` lowering) and still requires `!dbg` on the barrier instructions.
### M12 — tractable conformance gaps, and the abort triage
M12 takes the conformance classes with known backend/driver mechanics and
turns the largest unknown bucket (runtime aborts) into a costed M13 list. The
binding design is
`2026-11-19-tms34010-m12-tractable-gaps-design.md`; the triage report is
`../research/2026-11-19-tms34010-abort-triage.md`. Branch `m12` is the
milestone branch on both repositories; promotion is pending the controller's
review (`m11` remains the default until then).
- **The 17 flips, row by row.** The inline-asm memory rows `pr103376`,
`pr40022`, `pr40657`, `pr56866`, `pr65053-2`, `pr68328`, `pr81588`,
`pr82954`, `pr85156`, `pr94130` (10); the computed-goto rows `920501-3`,
`990208-1` (2); the level-0 frame rows `20030811-1`, `frame-address`,
`pr17377` (3); the dynamic-alloca row `20070824-1` (1); and `eeprof-1` (1),
the one-flag/one-condition harness fix that forwards
`-finstrument-functions` from the test's own `dg-options`. The eleventh
inline-asm row, `stkalign`, now selects its memory operand but aborts on
`__alignof__(s) == 64` under the packed-struct ABI; it was re-reasoned as
`runtime-abort-alignment`, not flipped. Suite accounting is
**1,912 = 1,635 pass / 277 skip / 0 fail / 0 crash** (1,618 + 17,
294 − 17; c-torture 1,425/267, c-testsuite 210/10).
- **Inline-asm memory operands; the `ST`/`o`/`V` decisions.**
`SelectInlineAsmMemoryOperand` matches the reachable load/store addressing
forms for `m` and `g`; an unmatchable operand is a named error. A selected
memory operand must also print: `PrintAsmMemoryOperand` emits `*An` or
`*An(disp)` with the folded bit displacement (`SP` for `A15`), pinned by a
`-no-integrated-as` check; previously only empty templates worked. `o`
accepts only the non-post-increment, non-negative-displacement form. `V` stays loud:
`InlineAsm::ConstraintCode` has no `V` and `SelectionDAGBuilder` asserts
before the target hook, so it needs a core enum change outside this charter.
`"st"` joins `getGCCRegNames()` so `~{st}` is a nameable clobber, while `ST`
remains outside every register class and every operand constraint (no
allocation, no save/restore, value operands still rejected).
- **`jump Rd` and computed goto.** The ISA's indirect jump (opcode `0x0160`,
vendor ONEREG table) is implemented end to end (instruction definition, MC
encoding `jump A0` = `[0x60, 0x01]`, parser, printer, disassembler);
`ISD::BRIND` lowers to it, and `ISD::BlockAddress` lowers to a
section-relative **bit** address through the normal `MOVI`/R-RELLONG path —
no absolute load address.
- **Level-0 frame intrinsics, with the capture mechanism.** The return word is
on the system stack at `SP + NumSaved*32` measured from the post-FP/`MMTM`
pointer. A use-site SP-relative load was reproduced sinking into the
saved-STK push window at `-O1`/`-O2` (it read the saved `A13`); the shipped
lowering captures the word once in the prologue — after the FP/callee-save
pushes — into a normal `A13`-relative stack object with matching
fixed-stack MMOs, and every `llvm.returnaddress(0)` use loads that stable
slot. The two capture-scratch pushes move SP, so the sequence forms
`SP + (NumSaved + 2)*32`:
`PUSH32 A0; PUSH32 A1; MOVE A15, A0;
ADDI A0, A0, (1 + CSI.size() + 2)*32; MOVE32Load A0, A0; MOVEFP A1;
[ADDI slotoff, A1]; MOVE32Store A0, A1; POP32 A1; POP32 A0`.
`llvm.frameaddress(0)` is `A13`. Levels above 0 stay a named error naming
the intrinsic and level.
- **Dynamic alloca.** The byte→bit scale already existed; the failure was the
M8 shape assertion firing when the DAG constant-folds the `SHL 3` for a
non-entry-block constant-count alloca (`20070824-1`). Both the constant and
variable shapes now scale explicitly and no node shape is asserted.
- **Abort triage (M13 input).** `scripts/tests/m12/abort-triage.sh` discovers
the abort rows from the curated table and re-runs each at `-O0` and `-O2`:
**54 rows** (52 aborts + 2 wrong results), **108 runs in 133 s**, **11
causes** — aggregate varargs 13, vectors 12, 64-bit/packed bitfields 7,
endian macro + SSO 5, packed/over-alignment 4, pointer↔int 4, signed zero 3,
float↔int 2, RTS/shim 2, instrumentation 1, freestanding builtins 1. The
report (`docs/superpowers/research/2026-11-19-tms34010-abort-triage.md`)
carries the per-file evidence and §6's M13 ordering: **varargs → vectors →
wide bitfields → endianness+SSO → alignment**, then the float groups.
`eeprof-1` is the only row fixed here. The endianness `BigEndian = false`
single change is rejected: it regresses `20230630-2`/`-4` once they select
`scalar_storage_order("big-endian")`.
- **Permanently out of scope.** Nested functions (30 rows; clang frontend
refusal), VLA-in-struct (9; `will never be supported`), dialect strictness
(8; `-Wint-conversion`/`-Wparen`/K&R under the pinned language mode) and
timeouts/region limits (37; loader budget or the 45 KiB/64 KiB image
regions). The triage's pointer↔int (4), RTS/shim (2) and freestanding
builtins (1) are target-model/runtime policy and stay curated as well.
- **The M12/M13 boundary.** M13 is the ABI shapes (sret,
aggregate/variadic/float arguments and returns) plus the triaged abort
causes in the order above; M14 is performance and the real VT1200 run
(still `HARDWARE: DEFERRED`); M15 is optional hosted I/O. Every M0–M11 gate
and the M11 end-to-end build stay green, and the four-phase divide gate is
unchanged (88/3,302/221/120).
M12 acceptance: the full suite is **0 fail / 0 crash** with the accounting
above; TMS34010 lit **142/142** (137 CodeGen + 5 MC), clang **15** (12 CodeGen +
2 Driver + 1 Sema), the Generic sweep **197 = 152 pass / 45 unsupported**
(`addr-label` flips with `blockaddress`), `tools/tms-link` and
`tools/tms-bitaddr` PASS; the M11 gates, M10 equivalence (46/0) and the
M0–M11 serial list PASS; `HARDWARE: DEFERRED`.
## 9. Risks and mitigations
@@ -0,0 +1,474 @@
# TMS34010 Phase 2 and Phase 3 — native clang pipeline and conventional toolchain
Status: proposed, revised after the builder check. Phase 1 (`tms-cc` usability
driver) is complete and pushed on `m9` (project `55a0991`, compiler
`4e7d48d2717e`).
Decisions already taken by the human partner:
| Decision | Choice |
|---|---|
| Phase 2 mechanism | Target-level pass hooks (Approach A) |
| Phase 3 library scope | Freestanding, conventional UX (shim + SDK runtimes behind CRT/headers/ToolChain) |
| clang-level defaults (`-replexitval=never`, `-ffreestanding`, …) | A minimal `ToolChain` lands in Phase 2 |
| M10 success criterion | Runtime and suite equivalence, not byte-identical objects |
| Vendor `flib`/`rts` archives | Committed to the repository |
## 1. Intent and why
Phase 1 gave a working one-command build (`scripts/tms-cc hello.c -o hello.coff`)
but it hides a pipeline only the wrapper script knows about. Native
`clang --target=tms34010 -c` still **miscompiles pointer code**. Verified on
`m9`:
```c
int load(int *p) { return p[1]; }
```
- `clang --target=tms34010 -O0 -S` → `ADDI 4, A0` (byte offset — wrong; a 32-bit
element is 32 bit-addresses away)
- `scripts/tms-clang` + `llc` → `ADDI 32, A0` (bit offset — correct)
The cause is structural: LLVM GEP indices are byte units, TMS34010 pointers are
bit addresses, and the optimizer re-forms byte GEPs from
`inttoptr(add(ptrtoint, …))` unless an opaque barrier blocks it. Correctness
needs three ordered steps — **pre-optimizer barrier → middle-end →
post-optimizer scale, lower, final InstCombine**.
The builder check also showed the wrapper hides more than the barrier. Native
`clang -O2 -c` fails on an ordinary loop because `IndVarSimplify` rewrites the
loop's exit value into an i33 multiply that the target rejects;
`scripts/tms-clang` avoids it with `-replexitval=never`, a pass option no
`TargetMachine` can set. The wrapper additionally supplies `-ffreestanding`,
`-fno-builtin`, `-nostdinc`, `-Xclang -disable-O0-optnone`, a pre-optimizer
static-variadic guard, and `instcombine<no-verify-fixpoint>`. So Phase 2 is "the
target owns the transform **and** the target's compile defaults", not the
transform alone.
Phase 3 then makes the whole flow conventional: a CRT, headers, a library and a
link job, so `clang --target=tms34010 hello.c -o hello` works with no wrapper
and no project variables.
These are projects, not small changes. They map onto the repository's milestone
pattern as **M10 (Phase 2)** and **M11 (Phase 3)**.
## 2. Goals
### Phase 2 (M10)
1. `clang --target=tms34010 -c` is semantically correct for pointer code at
`-O0` and `-O2`, with **no extra flags** and no wrapper script.
2. `clang --target=tms34010 -O2 -c` compiles ordinary loop code (the i33 /
`-replexitval` class) without the user passing anything.
3. The transform lives in the target: `llvm/lib/Target/TMS34010/`, registered
through `TMS34010TargetMachine::registerPassBuilderCallbacks`.
4. A **minimal `ToolChain`** supplies this target's compile defaults
(freestanding, no builtins, no system includes, `-replexitval=never`).
5. `scripts/tms-clang` keeps its command-line contract but becomes a thin
`clang` wrapper.
6. Gates that observe the wrapper's internals are re-pointed at the new seam.
7. Every M2–M9 gate, lit test and the 1,618-pass full suite stays green.
### Phase 3 (M11)
1. `clang --target=tms34010 hello.c -o hello` produces a loadable TI-COFF image
that runs under `tms-run`, with no project wrapper and no `M4_*` variables.
2. A committed, reproducible **CRT** (`crt0`), **headers** and **library**
(`libtms.a`), plus the committed vendor `flib.lib`/`rts.lib`, resolved
through a sysroot.
3. The driver owns the link step: `tms-link` is the linker job, with `-l`, `-L`,
`-nostdlib`, `-Wl,` and layout options passed through.
4. `-c`, `-S`, `-E`, `-O0`, `-O2`, `-g`, multiple TUs and `-nostdlib` behave the
way they do for any freestanding clang target.
5. Phase 1's user-visible behaviour (`printf` output via `tms-run`) is preserved.
## 3. Non-goals
- **Hosted C library.** No file I/O, no console/terminal driver, no `libm`, no
locale. `printf` continues to write the conformance result block.
- **lld.** TI-COFF is not an lld flavour; `tms-link` remains the linker.
- **LTO.** Bitcode leaving a completed pipeline is final; re-optimizing it is
unsupported.
- **Changing the TI ABI, the all-stack convention, the GSPA/GSPLNK oracle, or
the pointer model.**
- **Replacing `llc`'s IR contract.** Hand-written IR passed straight to `llc`
keeps the M9 meaning (§7.4).
- **Byte-identical objects.** Explicitly dropped: native `-O2` IRGen differs
from M9's `clang -O0` IRGen + `opt`, and `-O2` codegen differs from `llc -O0`
(measured 424 vs 416 bytes on an integer-only file, different block layout).
- Real VT1200 hardware validation (still deferred; no unit).
## 4. Anti-goals
- A user-visible flag that must be remembered for correctness. Correctness and
this target's compile defaults are properties of the target.
- Divergence in generic clang/LLVM beyond (a) the new
`clang/lib/Driver/ToolChains/TMS34010.{h,cpp}` and (b) its two registration
edits. Exported as patch `0005`, extended by Phase 3.
- Two implementations of the transform that can drift. `tools/tms-bitaddr`
becomes a **test oracle**, not a second production path.
- Silently changing what a gate measures. Any gate edit must preserve the
invariant it was asserting.
## 5. Current state (verified on `m9`)
| Fact | Evidence |
|---|---|
| The transform is a standalone IR rewriter, not a pass | `tools/tms-bitaddr/bitscale.cpp` parses IR, mutates it, writes it; modes `--bitptr --scale --normalize --lower-bitptr` |
| `clang -O2` fails on ordinary loops | `IndVarSimplify` exit-value rewrite → i33 multiply → `TMS34010RejectUnsupportedIR` fatal |
| M9 avoids it with a pass option | `scripts/tms-clang`: `opt -passes='default<O2>' -replexitval=never` |
| The wrapper carries freestanding defaults | `clang --target=tms34010-unknown-none -O0 -Xclang -disable-O0-optnone -ffreestanding -fno-builtin -nostdinc` (always `-O0` IRGen) |
| A pre-optimizer guard lives in the wrapper | awk scan rejecting `internal` variadic definitions with no `llvm.va_start` (DAE would drop `...`) |
| A final InstCombine needs an option | `instcombine<no-verify-fixpoint>` for the shim's `emit_uint64` `zext … nneg` fixpoint |
| Gates observe the wrapper's internals | `m3/run.sh` and `m5/jr.sh` inject `opt` wrappers; `m5/policy.sh` traces `opt` arguments; `m4/mul.sh` greps `scripts/tms-clang` for the flag |
| The target already assumes bit offsets in codegen | `TMS34010PassConfig::addIRPasses()` hosts `ScaleMemExpansionGEPs`, `ExpandAggMem`, `LowerI64`, `ExpandNarrowMem` |
| clang builds a `PassBuilder` **with** the `TargetMachine` | `clang/lib/CodeGen/BackendUtil.cpp:937` |
| so target pass callbacks are reachable from clang | `PassBuilder::PassBuilder` calls `TM->registerPassBuilderCallbacks(*this)` (`llvm/lib/Passes/PassBuilder.cpp:581`) |
| Pipeline-start callbacks run at `-O0` | `PassBuilderPipelines.cpp:2438`, inside `buildO0DefaultPipeline` |
| Optimizer-last callbacks do **not** run at `-O0` | `invokeOptimizerLastEPCallbacks` only at `:1692`, `:1933`, `:2524` |
| `llc` runs no new-PM pipeline | `llc.cpp:839` only calls `Target->addPassesToEmitFile` |
| `opt` builds no `TargetMachine` | `tools/opt/NewPMDriver.cpp` registers plugin callbacks only |
| The driver has no TMS34010 `ToolChain` | no `tms34010` under `clang/lib/Driver/` |
| The native link needs a repair step today | `scripts/m4/run.sh` runs `coff-check.py --repair --entry 018A0000` on every linked image |
| SDK `flib`/`rts` are generated, not committed | `build/m6-sdk/{flib,rts}.lib`, extracted from the 1987 vendor image |
| A TMS34010 MC assembler exists | `llvm/test/MC/TMS34010` (4 tests) — usable for a committed CRT |
| `tms-link` reads System V `ar` archives | M8.1 (`scripts/tests/m8/native-lib.sh`) |
## 6. Approaches considered
### Phase 2
**A. Target-level pass hooks (chosen).** Barrier on the pipeline-start extension
point; scale/lower/final-InstCombine on optimizer-last (`-O0` handles both in
the start callback, §7.3); registered from
`TMS34010TargetMachine::registerPassBuilderCallbacks`. No user flag, and the
transform stays inside the target directory.
**B. In-tree clang frontend patch.** Insert the passes in
`clang/lib/CodeGen/BackendUtil.cpp`. Explicit ordering, but the fork's first
divergence in generic clang code, re-carried on every LLVM bump. Rejected: A
covers every clang path because clang passes its `TargetMachine` to the
`PassBuilder`.
**C. Out-of-tree pass plugin plus an opt-in flag.** Smallest divergence, but
correctness becomes flag-dependent and forgettable. Rejected: it does not
satisfy "plain clang is correct".
**Rejected outright: bit units in `DataLayout`.** LLVM's addressing unit is the
byte and `getTypeAllocSize` is byte-quantised; a bit-unit GEP cannot be
expressed. That is why the barrier exists.
**Amendment after the builder check.** A alone is not sufficient: the
`-replexitval`, freestanding and include defaults cannot come from a
`TargetMachine`. They come from a minimal `ToolChain`, which is also the natural
home for Phase 3's sysroot and link job. This keeps one driver file rather than
two phases of driver surgery, and it means Phase 3 extends a file instead of
introducing one.
### Phase 3
**A. Dedicated `ToolChain` + sysroot + CRT + `libtms.a` (chosen).** Follows how
freestanding clang targets work, gives conventional `-I`/`-l`/`-L`/`-nostdlib`
behaviour, and keeps `tms-link` behind a normal link job.
**B. Keep `tms-cc` and only rename it.** Cheapest, but it keeps a project script
as the interface and cannot satisfy `clang hello.c -o hello`.
**C. Target the vendor 2ine/VT1200 OS environment.** Real OS applications, but a
different runtime contract and acceptance path. Rejected: the chosen scope is
freestanding with conventional UX.
## 7. Phase 2 (M10) design
### 7.1 Pass inventory
Port `tools/tms-bitaddr/bitscale.cpp` into new-PM passes under
`llvm/lib/Target/TMS34010/`:
| New pass | Source mode | Responsibility |
|---|---|---|
| `TMS34010BitPtrPass` | `--bitptr` | Replace every GEP (and `inttoptr` of a bit addend over `ptrtoint`) with `@__tms_bitptr(i32 bitoff, ptr base)`; rewrite constant-expression GEPs as `inttoptr(add(ptrtoint, 8*off))`; copy `!dbg`; run the static-variadic guard (§7.6) |
| `TMS34010ScaleGEPPass` | `--scale` | Multiply optimizer-created byte-GEP indices by 8; keep the `switch.table.*` special case |
| `TMS34010LowerBitPtrPass` | `--lower-bitptr` | Replace each call with `inttoptr(add(ptrtoint base, bitoff))`, then drop the declaration |
`--normalize` is not ported: nothing in the shipped pipeline calls it, and its
input contract is what `llc` does natively. The tool keeps the mode for its own
tests and stays the equivalence oracle.
The port is a rewrite into `PassInfoMixin` form, not a move: the current code is
a `main()`-driven module mutator.
### 7.2 Pipeline registration
`TMS34010TargetMachine::registerPassBuilderCallbacks(PassBuilder &PB)`:
```
PB.registerPipelineStartEPCallback(<level L: append barrier; if L == O0 also
append lower>);
PB.registerOptimizerLastEPCallback(<append scale → lower → instcombine>);
```
At `-O0` no optimizer runs, so there are no optimizer-created GEPs to scale and
no InstCombine is needed; adding one would move `-O0` output away from the M9
path. `-O0` therefore runs barrier + lower only, which is what makes the
byte-identity check possible.
`TMS34010PassConfig::addISelPrepare()` prepends `<lower → instcombine>` for IR
that reaches codegen still holding barrier calls (hand-written or intermediate
IR). It is placed before `TargetPassConfig::addISelPrepare()` so it runs before
`PreISelIntrinsicLowering`/`CodeGenPrepare`, matching M9's "lower before the
backend sees it". `TMS34010PassConfig::addIRPasses()` is unchanged.
The final InstCombine is constructed with
`InstCombineOptions().setVerifyFixpoint(false)` — the in-tree equivalent of the
wrapper's `instcombine<no-verify-fixpoint>`.
Consequences that make this safe:
- `clang` reaches the hooks because it builds `PassBuilder PB(TM.get(), …)`.
- `llc` never builds a new-PM pipeline, so **direct `llc` on IR keeps the M9
contract** and the 129 lit tests are unaffected.
- `opt` builds no `TargetMachine`, so `opt` never fires the hooks.
### 7.3 State machine (idempotency)
A module flag carries the state so the barrier cannot run twice:
| Flag `"tms.bitaddr"` | Meaning | Pipeline start | Optimizer last | Codegen (`addISelPrepare`) |
|---|---|---|---|---|
| absent | not ours / hand-written IR | apply barrier → `1`; at `-O0` immediately lower → `2` | skip | skip |
| `1` | barriered, not lowered | skip | scale, lower, instcombine → `2` | lower, instcombine → `2` |
| `2` | lowered / final | skip | skip | skip |
Flag: `Module::addModuleFlag(ModFlagBehavior::Override, "tms.bitaddr", i32)`, set
only by the pass performing the transition.
Because `-O0` lowers inside the start callback, **clang never emits state-1
IR**, which closes the previous hole where `clang -O0 -emit-llvm` → `opt -O2` →
`llc` would have lowered unscaled optimizer GEPs.
Scenario check:
| Command | Result |
|---|---|
| `clang -O2 -c` | barrier → optimize → scale/lower/instcombine → codegen skips |
| `clang -O0 -c` | barrier + lower + instcombine in the start callback |
| `clang -O0 -S -emit-llvm` then `llc` | state 2; `llc` skips |
| `clang -O2 -S -emit-llvm` then `llc` | state 2; `llc` skips |
| `clang -O2` on state-1 IR | barrier skipped, optimization + lowering run once |
| `llc` on hand-written IR | no flag → untouched (M9 meaning) |
| `opt` on state-2 IR | hooks never fire; optimizing final IR is unsupported (§7.5) |
### 7.4 Why `llc`'s contract must not change
`m2-late-gep.ll` pins `getelementptr i8, ptr %p, i32 24` → `ADDI 24`: for `i8`
GEPs the byte offset *is* the bit offset. A barrier inside `llc` would turn every
such test into `ADDI 192` and redefine the IR contract the gate suite is built
on. The hooks therefore live only in the new-PM pipeline, which `llc` does not
build. This is a design invariant.
### 7.5 Limitations to document
- IR emitted by a completed `clang` pipeline (`-emit-llvm`) is **final**;
re-optimizing it with `clang`/`opt -O2` is unsupported.
- LTO is unsupported for this target (bitcode is already lowered).
- The barrier must preserve `!dbg`; this keeps `-g -c` DWARF correct (M9.2
depends on it).
### 7.6 Minimal `ToolChain` (new in M10)
`clang/lib/Driver/ToolChains/TMS34010.{h,cpp}`, registered in
`clang/lib/Driver/ToolChains/CMakeLists.txt` and the driver's target selection so
`tms34010-unknown-none` (and plain `--target=tms34010`) resolve to it.
M10 responsibilities (the whole file is ~150 lines):
- `addClangTargetOptions`: append `-ffreestanding`, `-fno-builtin`,
`-mllvm -replexitval=never`, and `-disable-O0-optnone` (the last because the
legacy M9 path ran `-O0` without the `optnone` attribute, so the flag keeps
native `-O0 -c` objects byte-identical to the M9 path).
- Include behaviour: no system include directories (`-nostdinc` semantics
without the flag); `-I` still works.
- Keep object emission as today (integrated TI-COFF writer, no external
assembler).
- No link job yet: `-c`/`-S` are the M10 surface; linking stays with `tms-cc`
until M11.
The static-variadic guard moves into `TMS34010BitPtrPass` as a pre-optimizer
rejection: an `internal`/`private` variadic definition with no
`llvm.va_start`/`va_arg` in the body is diagnosed with the same message the
wrapper prints today.
### 7.7 What `tms-clang` becomes, and the gates that must change
`scripts/tms-clang` becomes a flag mapper:
| `tms-clang` flag | becomes |
|---|---|
| `-O0` / `-O2` | `clang --target=tms34010 -O0` / `-O2` |
| `-g` | `-g` |
| `-I dir` | `-I dir` |
| `-o OUT.ll` | `-S -emit-llvm -o OUT.ll` |
| `$TMS_CLANG_EXTRA_FLAGS` | passed through unchanged |
| `$TMS_OPT` / `$TMS_BITADDR` | no longer used |
Gate edits required (same invariant, new seam):
| Gate | Today | M10 |
|---|---|---|
| `scripts/tests/m3/run.sh`, `scripts/tests/m5/jr.sh` | inject an `opt` wrapper to add `-replexitval=never` | pass nothing; assert the compile succeeds and the loop shape survives in the emitted IR |
| `scripts/tests/m5/policy.sh` | traces `opt` arguments, asserts the flag and no `-switch-to-lookup` | asserts `-replexitval=never` appears in `clang -###` output (the ToolChain seam) and inspects the final IR/asm for the same shapes |
| `scripts/tests/m4/mul.sh` | greps `scripts/tms-clang` for the flag | greps the ToolChain source/defaults, or asserts via `clang -###` |
### 7.8 Acceptance (M10)
1. **Native correctness:** `clang/test/CodeGen/TMS34010/` tests for `p[1]`
(i32 → `ADDI 32`), byte/struct pointers, array indexing and pointer
difference at `-O0` and `-O2`; an ordinary `for` loop compiles at `-O2`
without extra flags.
2. **Native end-to-end:** the pointer programs run correctly end to end
(compile with native clang, link with the existing `tms-cc`/`tms-link` path,
run under MAME) at `-O0` and `-O2`.
3. **Equivalence (chosen criterion):** the full suite stays **1,618 pass / 294
skip / 0 fail / 0 crash**; suite markers and checksums are unchanged; i64div
stays 88/3302/221/120 with the same four checksums; a curated asm-shape set
(pointer arithmetic, struct offsets, switch tables, aggregate returns)
matches M9's shapes.
4. **Pass equivalence:** proven end-to-end, because individual new-PM passes are
not addressable from `opt` (it builds no `TargetMachine`): `clang -O0 -c`
objects must be byte-identical to the M9 path, which exercises the barrier
and lowering port directly, while the scaling pass is pinned by the M5 policy
gate (switch table) and an `-O2` asm-shape set.
5. **Unchanged gates:** lit 129/129 plus the new tests, clang 5/5 plus driver
tests, every M2–M9 gate green after the §7.7 edits, which are reviewed as
part of the milestone.
6. **No user flags:** `clang --target=tms34010 -O2 -c` with nothing else.
## 8. Phase 3 (M11) design
### 8.1 Driver link job
Extend the M10 `ToolChain` with a link job invoking `tms-link`: `-o`,
`--entry _start`, `--text`, `--bss`, `--prog-len`, `--ram-len`, libraries,
optional `--map`. `-Wl,…` passes through; `-nostdlib` removes CRT and default
libraries; `-g` maps to `--keep-debug` (and the default stays stripped).
**Linker prerequisite:** the production path must not depend on
`coff-check.py --repair`. `tms-link` must emit a loader-valid image unaided
(valid file/optional header, even `.bss`), and `coff-check.py` stays a *checker*
in the gates. This is small linker work added to M11.1.
### 8.2 CRT, headers, library, sysroot
| Artifact | Source | Build |
|---|---|---|
| `crt0.o` | `sdk/crt0.asm`, generalised from `conformance/entry.asm`: `setf`, stack setup, call `main`, write status/magic | `llvm-mc -triple=tms34010 -filetype=obj`, reproducible |
| headers | `sdk/include/` (moved from `scripts/tests/m5/conformance/include`) | installed into the sysroot |
| `libtms.a` | `sdk/shim.c`, `sdk/heap.c` (printf family, `malloc`/`free`, `mem*`/`str*`) | System V `ar`, which `tms-link` reads |
| `flib.lib`, `rts.lib` | committed copies of the extracted 1987 vendor archives | linked by default for the shim's `%f` path |
The sysroot layout is `lib/clang/<ver>/tms34010-unknown-none/{include,lib}` plus
a `--tms-sysroot=` override. Because the vendor archives are committed and the
CRT is reproducible, `clang --target=tms34010 hello.c -o hello` needs no
project variables and no SDK extraction step.
The conformance harness and `tms-cc` point at the relocated headers rather than
keeping a second copy.
### 8.3 Command surface after Phase 3
```
clang --target=tms34010 hello.c -o hello # CRT + libtms + flib/rts + tms-link
clang --target=tms34010 -c hello.c -o hello.o # TI-COFF object
clang --target=tms34010 -S hello.c -o hello.s # GSPA assembly
clang --target=tms34010 -O2 -g a.c b.c -o app # multi-TU, debug kept
clang --target=tms34010 -nostdlib -Wl,--entry=_start ...
tms-run hello # unchanged
```
`scripts/tms-cc` stays as a compatibility alias adding `--run` and the project's
default layout; it is no longer the recommended interface.
### 8.4 Acceptance (M11)
1. `clang --target=tms34010 hello.c -o hello` then `tms-run hello` prints
`hello` with status 0, from a shell with no project variables set.
2. `-c`, `-S`, `-E`, `-O0`, `-O2`, `-g`, multi-TU and `-nostdlib` behave
conventionally; `clang/test/Driver/TMS34010*.c` pins the link and include
command lines.
3. The CRT rebuilds byte-identically from source with no DOSBox/2ine dependency,
and the committed vendor archives match the extracted originals.
4. The single-command flow builds one M4/M5/M6 harness program unchanged.
5. M2–M10 gates, lit, the conformance full suite and the i64div numbers are
unchanged.
## 9. Constraints
- Branch `m10` from `m9`; `m11` from `m10` after Phase 2 is promoted. Default
promotion only after a clean whole-branch review, per standing policy.
- LLVM/Clang stay pinned at 23.1.5. `patches/llvm/0001..0004` stay as they are;
Phase 2 adds `0005` (the `ToolChain` and its registration), extended in
Phase 3.
- Every existing gate, the TI ABI, the all-stack convention, GSPLNK as the
byte/symbol oracle and the two-tier conformance harness stay intact.
- No force-push, no default-branch change, no history rewrite.
- `-O0` and `-O2` are both first-class.
## 10. Risks and mitigations
| Risk | Mitigation |
|---|---|
| Barrier applied twice | Module-flag state machine (§7.3) with the scenario table as tests |
| `llc`'s IR contract silently changes | Hooks only in the new-PM pipeline; `m2-late-gep.ll` and the 129 lit tests guard it |
| Codegen-created late GEPs after lowering | Lowering in `addISelPrepare` before `CodeGenPrepare`, matching M9 order; `addrSinkUsingGEPs` stays disabled |
| Debug info lost in the port | Barrier copies `!dbg`; M9.2 gates (`m9/dwarf-ranges.sh`, `m8/dwarf-multi.sh`, `m7/debug.sh`) must pass unchanged |
| Pass port drifts from the oracle | `tools/tms-bitaddr` retained as the oracle (§7.8.4) |
| Gate edits weaken coverage | Each §7.7 edit must assert the same invariant at the new seam and be reviewed |
| `-replexitval` regresses on other loop shapes | Full suite plus the M3/M5 loop gates; the flag is a compile-time policy, not codegen |
| Native `-O2` differs from M9 in size | Accepted by decision; behaviour gates (§7.8.3) replace byte identity |
| Driver file grows into two phases of surgery | One file from M10, extended rather than rewritten in M11 |
| `coff-check --repair` hides a tms-link defect | M11.1 fixes `tms-link`; the checker stays in the gate with `--repair` removed from production |
| Committed vendor archives drift | Gate compares the committed copies against freshly extracted ones |
| Two copies of headers/CRT | Phase 3 relocates the single source and regenerates harness paths |
## 11. Sequencing and what is left to the builder
**M10.0** minimal `ToolChain` (defaults + include behaviour) → **M10.1** pass
port + oracle equivalence → **M10.2** pipeline hooks + state machine →
**M10.3** `tms-clang` rewrite, gate edits, equivalence sweep → **M10.4**
docs/gates/promote.
**M11.1** link job + `tms-link` header fix → **M11.2** `crt0` via `llvm-mc` →
**M11.3** headers, `libtms.a`, committed vendor archives, sysroot → **M11.4**
single-command end-to-end, docs, gates, promote.
Left to the builder (verify during implementation, do not re-litigate):
1. Exact pass signatures; whether InstCombine is added via
`createInstructionCombiningPass`/`InstCombinePass(InstCombineOptions...)`.
2. Whether `addISelPrepare` prepending is sufficient or `addIRPasses` also needs
the safety-net lowering (measure both `-O0` outputs).
3. Module-flag name/behaviour enum (`"tms.bitaddr"` / `Override` proposed).
4. Whether the static-variadic guard belongs in the barrier pass or a separate
pre-opt pass in the same callback.
5. Sysroot resolution order (`-resource-dir` relative versus `--tms-sysroot`).
6. Whether `libtms.a` is always linked or gated on `-l tms`, and how `flib`/`rts`
are selected (`%f` needs them; `-nostdlib` must not).
7. Whether `tms-cc`'s `--run` stays in the script.
## 12. Decisions log
| Decision | Choice | By |
|---|---|---|
| Phase 2 mechanism | Target-level pass hooks (Approach A) | user |
| clang-level defaults (`replexitval`, freestanding, includes) | Minimal `ToolChain` in Phase 2, extended in Phase 3 | user |
| M10 success criterion | Runtime + suite equivalence | user |
| Vendor `flib`/`rts` | Committed to the repo | user |
| Phase 3 library scope | Freestanding, conventional UX (no hosted libc/file I/O/libm) | user |
| Milestone mapping | Phase 2 = M10, Phase 3 = M11 | this doc |
| `-O0` pipeline | Barrier + lower in the start callback; no state-1 IR from clang | this doc |
| `tms-bitaddr` fate | Test oracle, not a production path | this doc |
| `llc` IR contract | Unchanged (bit offsets by definition) | this doc |
| `-g` at link | Maps to `--keep-debug`; default stays stripped | this doc |
| `coff-check.py --repair` | Leaves the production path; `tms-link` emits valid images | this doc |
| Gate edits for the new seam | Required and reviewed (§7.7) | this doc |
@@ -0,0 +1,306 @@
# TMS34010 M11 (Phase 3) — Conventional Toolchain Design
Status: proposed. M10 is complete and `m10` is the default on both repositories
(project `4809185`, compiler `7fc2ac37b5ad`). This document also carries the
short roadmap for M12 and later.
Decision already taken by the human partner: M11 is Phase 3 of
`docs/superpowers/specs/2026-11-17-tms34010-phase-2-3-design.md` §8 — a
freestanding toolchain with conventional UX — and its artifacts are discovered
through a resource-directory sysroot built and installed by a script
(approach A below).
## 1. Intent and why
M10 made `clang --target=tms34010 -c` correct. M11 closes the remaining gap
between "a compiler that emits objects" and "a toolchain you can use": a
single command that produces a runnable image.
Today the pieces exist but only the project knows how to wire them:
- `scripts/tms-cc` compiles each TU through `scripts/tms-clang` and `llc`, then
drives `scripts/m4/run.sh` with `M4_*` environment variables, which assembles
`entry.asm` with the 1987 tools and links with `tools/tms-link`.
- Headers live in `scripts/tests/m5/conformance/include`; the runtime is
`shim.c` + `heap.c` compiled on every invocation; the SDK archives come from
`build/m6-sdk`.
- Nothing tells `clang` where a CRT, headers or a library are.
The goal is that a user with a built compiler and one setup command can run:
```sh
clang --target=tms34010 hello.c -o hello
tms-run hello
```
and see `hello`, with no project variables, no wrapper script, and no DOSBox.
## 2. Goals
1. `clang --target=tms34010 hello.c -o hello` links to a loader-valid TI-COFF
image through `tms-link`, with a CRT, headers and a C library found through
a sysroot.
2. The sysroot is produced from in-repo sources by one documented command and
installed at a relocatable, conventional location.
3. `-c`, `-S`, `-E`, `-O0`, `-O2`, `-g`, multiple TUs, `-I`, `-L`, `-l` and
`-nostdlib` behave the way they do for any freestanding clang target, and
`-###` shows the real compile and link jobs.
4. The CRT is reproducible from source with `llc` — no DOSBox, no 2ine, no
vendor assembler. (`llvm-mc` cannot be used: it emits ELF for this triple, and
the generic COFF path refuses a non-Windows triple. The target's TI-COFF
writer is reachable only through CodeGen, so the CRT is an IR file whose
`_start` is `naked` with inline assembly.)
5. `libtms.a` is built from `shim.c` + `heap.c` with `llvm-ar`; the committed
vendor `flib.lib`/`rts.lib` supply the `%f` formatting path.
6. `tms-link` emits a loader-valid image on its own, so the production path no
longer needs `coff-check.py --repair`.
7. Every M0–M10 gate, the lit suites and the 1,912-row conformance suite stay
unchanged.
## 3. Non-goals
- **Hosted C library.** No file I/O, no console driver, no `libm`, no locale.
`printf` keeps writing the conformance result block that `tms-run` reads.
- **A new linker.** `tms-link` stays the linker; M11 only calls it correctly.
- **lld.** TI-COFF is not an lld flavour.
- **Changing the TI ABI, the all-stack convention, the pointer model, or the
M10 pipeline.** M11 adds no codegen behaviour.
- **Bare-metal debugger integration** beyond `-g` → `--keep-debug`.
- **Removing `tms-cc`.** It stays as a compatibility alias.
## 4. Anti-goals
- A driver that shells out to project scripts or bakes a checkout path into
`clang`. Both break the "conventional toolchain" property.
- Committing built `crt0.o`/`libtms.a`. Sources are the truth; a drift gate is
still cheaper than a checked-in binary.
- Growing the driver patch into generic clang code. The fork's driver change
stays inside `clang/lib/Driver/ToolChains/TMS34010.*` plus its two
registration lines, exported as an extension of patch `0005`.
- Making the conformance harness depend on the installed sysroot in a way that
breaks its hermetic MAME runs.
## 5. Constraints
- LLVM/Clang stay pinned at 23.1.5; the fork's exported patches remain
`patches/llvm/0001..0005`.
- Branch `m11` from `m10`; promote only after a clean whole-branch review, per
standing repository policy.
- Every existing gate and the two-tier harness stay green; `HARDWARE` stays
`DEFERRED` until a unit exists.
- No force-push, no history rewrite.
- `clang --target=tms34010 -c` (M10's contract) must not regress, including
`-O0` byte identity with the M9 path.
## 6. Current state (verified on `m10`)
| Fact | Evidence |
|---|---|
| CodeGen emits TI-COFF; `llvm-mc` does not | `llc -march=tms34010 -filetype=obj` writes the target's COFF object; `llvm-mc -triple=tms34010 -filetype=obj` writes ELF (`7f 45 4c 46`), and `-triple=tms34010-unknown-none-coff` aborts with "cannot initialize MC for non-Windows COFF object files" |
| A `naked` function keeps inline asm verbatim | `llc` on a `naked` `_start` with `setf`/`movi`/`move`/`rets` inline asm emits no prologue and no epilogue |
| `tms-link` already has the driver's surface | `--entry --text --data --cinit --bss --prog-len --ram-len --map --keep-debug -L -l` |
| A working `_start` exists | `scripts/tests/m5/conformance/entry.asm`: `setf` 16/32, 4 KiB `_cstack`, argv vector `{"conformance", NULL}`, result block at `01B00000`/`20`/`40`/`60`, output buffers `01B10000`/`01B30000`, `exit`/`abort` publish status themselves |
| Headers exist but uninstalled | 10 headers in `scripts/tests/m5/conformance/include` (`assert, limits, math, stdarg, stdbool, stddef, stdint, stdio, stdlib, string`) |
| Runtime sources exist | `scripts/tests/m5/conformance/{shim.c,heap.c}` |
| SDK archives are extracted, not committed | `build/m6-sdk/{flib,rts}.lib`; the design commits them in M11 |
| The link path needs a repair step today | `scripts/m4/run.sh` always runs `coff-check.py --repair --entry 018A0000` |
| The driver file exists | `clang/lib/Driver/ToolChains/TMS34010.{h,cpp}` from M10, patched by `0005` |
| No sysroot or link job exists | `clang -###` shows compile jobs only |
## 7. Approaches considered
**A. Resource-directory sysroot, built and installed by a script (chosen).**
`sdk/` holds the sources; `scripts/tms-sdk` builds `crt0.o` and `libtms.a` and
installs them, with the headers and the committed vendor archives, into
`<resource-dir>/tms34010-unknown-none/{include,lib}`. The `ToolChain` searches
there. Sources stay authoritative, the location is the conventional one for
cross targets, and clang stays relocatable. Cost: one setup command after a
compiler build.
**B. Repo-relative `sdk/` with committed prebuilt artifacts.** No setup step,
but it bakes a checkout path into the driver, breaks when clang moves, and puts
binaries in git that can drift. Rejected: it trades a real property
(relocatable clang) for skipping one command.
**C. Explicit `--tms-sysroot` only.** Most predictable, worst UX, and it fails
goal 1 (working from a shell with no flags). Rejected.
**Why A.** It is the only option that keeps both properties the milestone is
for: a single conventional command, and a clang that can be moved or installed
anywhere.
## 8. Design
### 8.1 Artifacts and layout
| Source | Built by | Installed to |
|---|---|---|
| `sdk/crt0.ll` (a `naked` `_start` with inline asm) | `llc -march=tms34010 -filetype=obj` | `<sysroot>/lib/crt0.o` |
| `sdk/shim.c`, `sdk/heap.c` | `clang --target=tms34010 -c` + `llvm-ar` | `<sysroot>/lib/libtms.a` |
| `sdk/include/*.h` (moved from the conformance harness) | — | `<sysroot>/include/` |
| `sdk/lib/{flib,rts}.lib` (committed copies of the extracted 1987 archives) | — | `<sysroot>/lib/` |
| `tools/tms-link/{tms-link,tmscoff.py}` | copied as a pair (the script imports its sibling) | `<sysroot>/bin/` |
The installed linker is a Python program: `python3` is a documented runtime
dependency of the toolchain, and the driver reports its absence by name rather
than as a bare link failure.
`<resource-dir>` is `clang -print-resource-dir` (for this fork,
`build/llvm-clean-build/lib/clang/23`), so the sysroot defaults to
`<resource-dir>/tms34010-unknown-none`.
`scripts/tms-sdk` performs all four steps, is idempotent, and accepts
`--sysroot DIR` to install elsewhere (the driver then needs
`--tms-sysroot=DIR`). The conformance harness points at `sdk/` for its headers
so there is exactly one copy.
### 8.2 Driver discovery and the link job
`TMS34010ToolChain` gains:
- **Sysroot search order:** `--tms-sysroot=DIR`, then `--sysroot`/`-isysroot`,
then `<resource-dir>/tms34010-unknown-none`. Headers come from
`<sysroot>/include`; libraries from `<sysroot>/lib` plus `-L` paths.
- **A link `Tool`** (`TMS34010Linker`) that invokes the installed
`tms-link`. **Linker discovery:** `--tms-linker=PATH` first, otherwise
`<sysroot>/bin/tms-link` — the same sysroot the headers and libraries come
from, so one setup command covers everything and nothing is baked into the
driver. A missing sysroot, a missing linker or a missing `python3` is a named
diagnostic, never a bare link error; the first two point at `scripts/tms-sdk`
and the `python3` one says to install `python3`.
Arguments: `-o <output>`, `--entry _start`, `--text 018A0000`,
`--bss 01A00000`, `--prog-len 40000h`, `--ram-len 80000h`,
`--map <output>.map` when `-Wl,-Map` is absent, the objects, then
`libtms.a`, `flib.lib`, `rts.lib` (unless `-nostdlib`/`-nodefaultlibs`), then
user `-L`/`-l`. `-Wl,` arguments pass through verbatim.
- **`-g`** also passes `--keep-debug` to the link so the image keeps its DWARF;
the default stays stripped.
- **`-###`** shows both jobs, and `clang/test/Driver/TMS34010-link.c` pins the
link command line and the include path.
Compile jobs are unchanged from M10.
### 8.3 CRT contract
`sdk/crt0.ll` expresses the CRT as LLVM IR: `_start` is a `naked` function whose
body is a sequence of `call void asm sideeffect "…"` blocks (`setf`, `movi`,
`move`, `calla _main`, the status/magic stores, `rets`), plus globals for
`_conformance_name` (`"conformance\0"`), `_conformance_argv` and `_cstack`.
`llc -filetype=obj` lowers it through CodeGen and the target's TI-COFF writer,
which is the only path that emits this object format; `llvm-mc` is not usable
(see the current-state table). `naked` is required so no prologue touches the
stack before `_start` sets it.
What the rewrite must preserve is the **contract**, not the text:
- `setf 16,1,0` / `setf 32,0,1`, and a 4 KiB `_cstack` at 16-bit alignment;
- the two-element argv vector `{"conformance", NULL}` so `main(int, char**)`
keeps working (`main(void)` is unaffected);
- the result block exactly as today: status at `01B00000`, magic at
`01B00040` set after `main` returns, and `libtms`'s output/error buffers at
`01B10000`/`01B30000` with their length cells;
- the `_start` symbol that `--entry _start` names;
- `exit`/`abort` in `libtms` still publish status and spin.
Those addresses and sizes are the interface `tms-run` and the conformance
harness already rely on.
### 8.4 Library policy
`libtms.a` always links when the CRT does. `flib.lib`/`rts.lib` are needed by
`libtms`'s `%f` path, so they link by default. The conventional knobs are
independent: `-nostartfiles` drops `crt0.o` but keeps the libraries,
`-nodefaultlibs` keeps `crt0.o` but drops `libtms`/`flib`/`rts`, and
`-nostdlib` implies both. `-l tms` is accepted and is a no-op beyond ensuring
the archive is present once. Order is fixed: CRT, user objects, `libtms`,
`flib`, `rts`, user `-l` archives.
### 8.5 `tms-link` prerequisite
`coff-check.py --repair` leaves the production path. `tms-link` must emit a
valid file header, optional header and section table, and round `.bss` to whole
16-bit words itself; `coff-check.py` stays in the gates as a checker (`--repair`
becomes test-only). This is small linker work and it is the reason the link job
can stay clean.
### 8.6 `tms-cc`
Kept as a compatibility alias documented as such: it adds `--run` and the
project's M4 defaults. New documentation points at `clang --target=tms34010`.
It is not deleted in M11.
### 8.7 Acceptance
1. From a clean shell after `scripts/tms-sdk`:
`clang --target=tms34010 hello.c -o hello` then `tms-run hello` prints
`hello` with status 0. No `M4_*`, `TMS_*`, or include paths set.
2. `-c`, `-S`, `-E`, `-O0`, `-O2`, `-g`, two-TU linking and `-nostdlib` all
behave conventionally; `clang/test/Driver/TMS34010-link.c` pins the jobs.
3. `crt0.o` and `libtms.a` rebuild byte-identically from `sdk/` (`llc`
self-consistency, not parity with the 1987 assembler), and a gate compares
the committed `flib.lib`/`rts.lib` against the extracted originals.
4. One existing M4/M5/M6 harness program builds through the new path and still
passes its MAME markers. (M11 adds no separate harness-program-through-driver
case: `scripts/tests/m11/e2e.sh` plus the unchanged full suite cover that
risk.)
5. The conformance suite stays `1,912 = 1,618 / 294 / 0 / 0`; lit and every
M0–M10 gate stay green; `HARDWARE: DEFERRED`.
## 9. What is left to the builder
1. Whether `scripts/tms-sdk` is a shell script, a CMake custom target, or both
(a `make sdk` shim is likely enough).
2. The exact `Tool` subclass shape (`GnuTool`-style vs plain `Tool`), and
whether `-Wl,` parsing belongs in the Tool or the ToolChain.
3. Whether `libtms` also carries `__tms_bitptr`-adjacent helpers or stays
purely C.
4. The precise `clang -###` line splits the driver test pins.
5. Whether `-Map` defaults on or only on `-Wl,-Map` (leaning: default on, next
to the output, because the map is the debugging surface this toolchain has).
6. How the installed `tms-link` should signal a missing interpreter (shebang
plus the driver's pre-flight check), and whether `tms-sdk` normalises the
copied pair's permissions.
## 10. Risks and mitigations
| Risk | Mitigation |
|---|---|
| Sysroot drift from sources | `scripts/tms-sdk` is the only writer; a gate rebuilds and compares the CRT and library |
| Committed vendor archives drift | A gate compares them against freshly extracted copies |
| Installed linker drifts from `tools/tms-link` | `scripts/tms-sdk` copies it; a gate compares the installed pair against the sources |
| `python3` missing at link time | The driver detects it and names `scripts/tms-sdk` and `python3` in the diagnostic |
| The IR CRT shifts the runtime contract | The contract list in §8.3 is the test: `tms-run` output, argv, status and buffer addresses |
| `naked` + inline asm is fragile across LLVM bumps | The CRT gate pins the emitted bytes and `llc`'s no-prologue output |
| Driver bakes in a checkout path | Discovery is resource-dir relative; the driver test asserts it |
| Link failures from an uninstalled sysroot | A missing sysroot is a named diagnostic telling the user to run `scripts/tms-sdk`, not a link error |
| `tms-link` header defects surface late | M11.1 fixes the linker first and `coff-check` gates it |
| Conformance harness forks its headers | Harness and sysroot share `sdk/include` |
| `-g` silently stripped | Driver test pins `--keep-debug`; an M8-style dwarfdump check confirms the linked image |
| Driver patch grows into generic clang | All new code stays in `ToolChains/TMS34010.*`; patch `0005` grows, nothing else |
## 11. Roadmap after M11
| Milestone | Scope | Why this order |
|---|---|---|
| **M12 — conformance classes** | inline-asm memory constraints (`m`/`o`/`V`), the `ST` clobber, `blockaddress`, nested functions, VLAs, sret/aggregate/variadic/float returns, runtime aborts, `pr63843` | Raises the suite's pass rate from 1,618 and removes the largest remaining silent-failure classes |
| **M13 — performance and hardware** | attribute the slow-phase 2,440 → 3,302-frame delta; further divide/loop work; the real VT1200 run when a unit exists | Needs a stable correctness baseline (M10–M12) before measuring |
| **M14 — hosted I/O (optional)** | real console/serial output, then file APIs; a terminal `printf` instead of the result block | Largest scope and the least certain requirement; deliberately last |
Each milestone gets its own design and plan; this table only fixes the order.
## 12. Decisions log
| Decision | Choice | By |
|---|---|---|
| M11 scope | Phase 3: freestanding toolchain with conventional UX | user (earlier) |
| Artifact discovery | Resource-directory sysroot built and installed by `scripts/tms-sdk` (approach A) | user |
| Linker discovery | `scripts/tms-sdk` installs `tms-link` + `tmscoff.py` into `<sysroot>/bin/`; the driver resolves it relative to the sysroot, `--tms-linker=` overrides | user |
| CRT source/build | `sdk/crt0.ll` (naked `_start` + inline asm) built by `llc`; acceptance is `llc` self-consistency | this doc (corrected during M11 execution: `llvm-mc` emits ELF) |
| Link-reduction knobs | `-nostartfiles`, `-nodefaultlibs`, `-nostdlib` all supported | this doc |
| `libtms.a` fidelity | Rebuild-and-compare against `sdk/`, plus the suite | this doc |
| Vendor archives | Committed to the repo, compared by a gate | user (earlier) |
| Hosted libc | Out of scope | user (earlier) |
| `tms-cc` | Kept as a compatibility alias | this doc |
| `coff-check --repair` | Leaves the production path; `tms-link` emits valid images | this doc |
| Milestone order | M11 → M12 (conformance) → M13 (performance/hardware) → M14 (hosted I/O, optional) | this doc |
@@ -0,0 +1,274 @@
# TMS34010 M12 — Tractable Conformance Gaps (Design)
Status: proposed. M11 is complete and `m11` is the default on both repositories
(project `536c80a`, compiler `18b7fc9cd6df`).
The human partner chose this split: M12 takes the gaps that are backend or
driver work with known mechanics, and **nested functions and VLA-in-struct are
out of scope permanently** because both are frontend refusals, not gaps in our
backend. The runtime-abort class is triaged here and fixed in M13.
## 1. Intent and why
The suite accounts for 1,912 files: 1,618 pass, 294 skip, none fail. The skips
are curated, not random — each carries a reason. This milestone removes the
ones that are genuinely ours and reachable, and turns the largest unknown
bucket ("runtime aborts", 58 files) into a costed list.
Everything below was verified against the `m11` compiler, not inferred from the
skip file.
| Class | Files | Verified failure | Verdict |
|---|---|---|---|
| inline-asm memory constraints | 11 | `LLVM ERROR: TMS34010: inline asm memory constraints ('m'/'o'/'V') are not supported; use a register or an immediate operand` — the target's own diagnostic, added deliberately in M9. All eleven use `m`/`g` with an empty template; **no corpus row uses `o`, `V`, or `~{st}`** | ours, bounded |
| `ST` clobber | 0 (feature) | `ST` exists in `TMS34010RegisterInfo.td:46` but not in clang's GCC register list (`clang/lib/Basic/Targets/TMS34010.cpp:73`), so `~{st}` cannot be named | ours, small, no suite flip |
| inline-asm, not memory-operand | 2 | `20030222-1`: i64 value tied to a 32-bit `r`; `990413-2`: an x86-only test (`=t`) that does not belong in this corpus | out of scope (separate gaps) |
| `blockaddress` + computed goto | 2 | `llc`: `Cannot select: BlockAddress<@execute, %base>`; and `920501-3` needs an indirect branch the backend cannot select (the ISA has `jump Rd`, unimplemented) | ours, bounded |
| return/frame address | 3 of 5 | `LLVM ERROR: TMS34010: unexpected custom lowering operation (return address)` / `(frame address)`. `20010122-1` checks level 1 and `20030323-1` walks to level 100; only `20030811-1`, `frame-address`, `pr17377` are level-0 | ours, bounded |
| dynamic alloca scaling | 1 | `dynamic alloca size scaling assertion` (`c-torture/20070824-1`) | ours, bounded |
| runtime aborts | 49–51 | compile and run, then abort with status `0x86` or a wrong result (i64, bitfield, varargs, vector, float, plain) | **triage only** |
| nested functions | 30 | clang: `error: function definition is not allowed here` | out of scope |
| VLA in struct | 9 | clang: `fields must have a constant size: 'variable length array in structure' extension will never be supported` | out of scope |
| dialect strictness | 8 | `-Wint-conversion`, `-Wparen`, K&R-style errors under the pinned language mode | out of scope |
| timeouts, region limits | 37 | loader budget or the 45 KiB/64 KiB image region | out of scope (environment) |
So M12 can flip **17 files** (11 + 2 + 3 + 1) plus at most three abort fixes, and
must produce one new artefact: the abort triage report.
## 2. Goals
1. Inline-asm `m`/`o`/`V` memory operands work for the addressing modes this
target can select, with unsupported shapes still loud and named.
2. `~{st}` is a nameable clobber, and using `ST` as a value operand stays
rejected.
3. Computed `goto` works: `blockaddress` lowers to a section-relative bit
address and jumps correctly.
4. `llvm.returnaddress(0)` and `llvm.frameaddress(0)` lower on this ABI; levels
above 0 stay a named error.
5. Dynamic allocas (VLAs and `alloca`) scale sizes in bits correctly.
6. **Abort triage:** the set is *discovered*, not asserted — every curated
`runtime-abort*` and runtime-wrong-result row is re-run uncurated at `-O0`
and `-O2`, its failure mode captured, and the results grouped into named
causes with evidence and a proposed M13 cost. At most three single-cause cheap fixes may
be taken inside M12; everything else is deferred with a recorded reason.
7. Each fixed class flips its files in the full suite, and the accounting is
re-recorded (pass count rises, skip count falls by the same amount).
8. All M0–M11 gates, the M11 end-to-end build and the two-tier harness stay
green.
## 3. Non-goals
- **Nested functions** and **VLA in struct**: frontend features clang refuses;
implementing them means LLVM frontend work outside this milestone's charter.
They stay curated with those reasons.
- **ABI shapes** (sret, aggregate/variadic/float arguments and returns): M13,
together with the aborts they probably overlap.
- **Dialect strictness** (the 8 `compile:` rows): the corpus is compiled in a
pinned language mode; relaxing it would change what the suite measures.
- **Timeouts and region limits**: environment, not compiler defects.
- **Performance work and the hardware run**: M14.
- **Hosted I/O**: M15, optional.
## 4. Anti-goals
- Un-curating a test without fixing it. A class is flipped only when its
reason is gone.
- Supporting memory operands by falling back to a register copy behind the
user's back. If a shape cannot be an address, it stays an error that names
the constraint and the operand shape.
- A blockaddress implementation that bakes in a load address or breaks the
pic-free model.
- Making `returnaddress`/`frameaddress` return plausible nonsense for levels
the ABI cannot express.
- A triage report that lists "aborts" as one bucket. Its whole value is named
causes.
## 5. Constraints
- LLVM/Clang stay pinned at 23.1.5; branch `m12` from `m11`; promote only after
a clean whole-branch review.
- No TI ABI change: the all-stack convention, argument slots, and the bit
pointer model stay as they are.
- Every gate stays green; the suite stays `0 fail / 0 crash`; the abort triage
may not turn a curated skip into a *failure* row.
- No gate expectation, checksum or recorded count moves except the suite rows
this milestone legitimately flips (and those are recorded individually).
- Build with `-j4` on this host (unbounded builds have been OOM-killed).
## 6. Approaches considered
### 6.1 Inline-asm memory operands
**A. Full addressing-mode support (chosen).** Teach `SelectInlineAsmMemoryOperands`
and `TMS34010DAGToDAGISel` to match the ISA's memory forms — `*An`,
`*An(disp)`, `*An+`, `*-An`, `*An(disp),N` — and let LLVM pick one for an `m`
operand. `o` (offsettable) and `V` (non-offsettable) map onto the same matcher
with their respective restrictions. Unmatchable shapes stay loud.
**B. Minimal support.** Accept only a plain `*An` and keep everything else
loud. Less work, but the 13 files use varied shapes and most would stay
skipped.
**C. Keep it loud.** Costs nothing and flips nothing; rejected because these
are ordinary C `asm` statements the corpus already contains.
**Why A.** The ISA has few, regular memory forms; the matcher is the natural
home for them, and the loud fallback keeps the residual honest.
### 6.2 Abort triage
**A. Full uncurated re-run (chosen).** Re-run all 58 with the same driver, at
both `-O0` and `-O2`, capture status and the first wrong marker or abort site,
then group. Costs one MAME pass but produces evidence for every file.
**B. Sample.** Cheap, but a plan built on a sample repeats last milestone's
guesswork; rejected.
**C. Fix-as-you-go.** Debug each abort inside M12. Rejected: unbounded, and the
milestone's point is to make M13 plannable.
## 7. Design
### 7.1 Inline-asm memory constraints
- `TMS34010TargetLowering::getConstraintType` already distinguishes `m`; add
`TMS34010TargetLowering::SelectInlineAsmMemoryOperand` (the hook M9 replaced
with a fatal error) that produces a memory operand the DAG can select.
- Add a `TMS34010DAGToDAGISel` matcher for the five memory forms, reusing the
existing addressing-mode selection used by loads/stores.
- `constraint 'o'` requires a non-post-increment, non-negative-displacement
form. `'V'` stays loud: `InlineAsm::ConstraintCode` has no `V`, and
`SelectionDAGBuilder` asserts on an unknown memory constraint before the
target hook runs, so honouring its "non-offsettable" restriction would need
a core LLVM enum change — outside this milestone's target-only charter.
- Tests: one `.c` per form at `-O0` and `-O2`, plus a negative for an
unmatchable operand, and a check that the emitted asm uses the expected
addressing form rather than a register copy.
### 7.2 `ST` clobber
- Add `"st"` to `TMS34010TargetInfo::getGCCRegNames()`; `ST` already exists in
the register info (`TMS34010RegisterInfo.td:46`).
- Keep `ST` out of the allocatable set and out of the inline-asm *operand*
classes; only the clobber path accepts it.
- Tests: `~{st}` accepted, no save/restore emitted for it (it is a status
register), and `asm("" : "=r"(x) : ...)` unchanged.
### 7.3 `blockaddress` and computed goto
- Lower `ISD::BlockAddress` in `TMS34010TargetLowering::LowerOperation` to the
target's address node for a label: a section-relative bit address with the
existing relocation machinery, no absolute load address.
- Add the ISA's indirect jump `jump Rd` (opcode `0x0160`, documented in the
vendor README) end to end: instruction definition, MC encoding, asm parser,
printer and disassembler, and `ISD::BRIND` lowering to it. Without this,
`goto *` cannot select even once the constant works.
- Tests: computed `goto` in C at `-O0`/`-O2` for both corpus shapes; an `llc`
lit test that the constant is a `.text`-relative bit address; MC tests for
the encoding, parser and disassembler; and a negative that an out-of-range
target stays loud.
### 7.4 Return and frame address
- The return address lives on the **system stack**, not at an `A13`-relative
slot: after the callee's FP/callee-save `MMTM` the word is at
`SP + NumSaved*32` (`NumSaved = 1 + callee-save-count`). The shipped
lowering captures it once in the prologue; the two capture-scratch pushes
put it at `SP + (NumSaved + 2)*32`, and the copy is stored in an `A13`
slot. Level 0 reads that stable frame slot, not an `SP`-relative load at
the use site (which can sink into the caller's saved-STK push window).
- `llvm.frameaddress(0)` is the current frame pointer (`A13`).
- Levels above 0: keep the loud error, but name the intrinsic and the level.
`20010122-1` (level 1) and `20030323-1` (levels 1–100) stay curated with a
precise "level > 0 unsupported" reason.
- Tests: the three level-0 corpus files, plus lit covering level 0 and the
loud non-zero case.
### 7.5 Dynamic alloca scaling
- Reproduce `c-torture/20070824-1`; the recorded failure is a size-scaling
assertion. Fix the bit-vs-byte scaling in the dynamic-alloca path so the
stack adjustment matches the pointer arithmetic (both are bit units).
- Test: the corpus file plus a lit case pinning the stack-adjust arithmetic for
a non-constant size.
### 7.6 Abort triage (deliverable, not a fix)
- A harness `scripts/tests/m12/abort-triage.sh` that re-runs each of the 58
abort rows through the standard driver at `-O0` and `-O2`, capturing status,
the completion magic, and the first differing marker/abort PC.
- Output: `docs/superpowers/research/2026-11-19-tms34010-abort-triage.md`, one
row per file with class → cause → evidence → estimated cost, plus a summary
by cause.
- Ruling: at most three fixes may be taken inside M12, each only if the triage
shows a single shared cause with a one-line fix; all others defer to M13. Any
taken fix is its own task with a recorded flip.
### 7.7 Suite accounting
Each class fix records the exact flipped rows in `full-suite.skip`'s removal
commit and in the docs. The final numbers are expected to be
**1,618 + N pass / 294 − N skip**, with N ≈ 20 (13 inline-asm + 2 blockaddress
+ 4 return/frame address + 1 dynamic alloca), plus any abort fixes.
## 8. Acceptance
1. The 10 memory-constraint rows pass (`stkalign` is re-reasoned, not
flipped); `~{st}` is accepted as a clobber;
unmatchable shapes and `V` still fail with a named error.
2. Both `blockaddress` rows pass with correct control flow at `-O0` and `-O2`,
including the new `jump Rd` encoding, parser and disassembler tests.
3. The three level-0 return/frame-address rows pass; levels above 0 stay a
named error.
4. The dynamic-alloca row passes.
5. The abort triage report exists, covers the harness-discovered set, groups it
by named cause, and proposes an M13 scope with costs.
6. The full suite is re-recorded with `0 fail / 0 crash`, pass/skip consistent,
and each flip individually justified.
7. All M0–M11 gates green, M11's `clang hello.c -o hello` still works, i64div
numbers unchanged, `HARDWARE: DEFERRED`.
## 9. Risks and mitigations
| Risk | Mitigation |
|---|---|
| Memory-operand matcher accepts a shape it selects wrongly | Each form has an asm-shape test; unmatchable shapes stay loud |
| `ST` becomes allocatable by accident | Register class untouched; test asserts it never appears as an operand class |
| Blockaddress bakes a load address | Lit test pins the section-relative form and a link-time check that `--text` relocation still works |
| `returnaddress` picks the wrong slot | The four corpus files run in MAME; a wrong slot aborts loudly |
| Abort triage turns a skip into a crash row | The triage re-runs out of tree and never edits the curated file unless a fix lands |
| Suite accounting drifts | Flips recorded per row; the report shows the arithmetic |
## 10. What is left to the builder
1. Which of the five memory forms `o`/`V` should accept (the ISA table decides;
document the mapping).
2. Whether `returnaddress` can rely on a fixed A13 displacement or needs the
frame-size recorded in the function.
3. Whether the dynamic-alloca failure is one bug or two (size and alignment).
4. The triage harness's exact failure-capture (marker diff vs abort PC).
5. Which three abort fixes, if any, meet the one-line bar.
## 11. Roadmap (renumbered)
| Milestone | Scope |
|---|---|
| **M12 (this)** | inline-asm memory constraints + `ST` clobber, `blockaddress`, return/frame address, dynamic alloca, abort triage |
| **M13** | ABI shapes (sret, aggregate/variadic/float args and returns) and the abort causes triaged here |
| **M14** | performance and the real VT1200 run |
| **M15** | hosted I/O (optional) |
| out of scope for good | nested functions, VLA in struct (frontend refusals), dialect strictness, timeouts and region limits |
## 12. Decisions log
| Decision | Choice | By |
|---|---|---|
| Split the conformance work | Feature/gap classes in M12, ABI + aborts in M13 | user |
| Nested functions | Permanently out of scope (clang frontend feature) | user |
| Return/frame address | Level 0 only; levels above 0 stay a named error | user |
| Computed goto | Add `jump Rd` + `BRIND` lowering so both rows flip | user |
| `V` constraint | Kept loud (needs a core LLVM enum change) | this doc |
| Inline-asm flips | 10 rows; `stkalign` is re-reasoned, and `ST` is a feature-only change | this doc |
| VLA in struct | Out of scope (clang: "will never be supported") | this doc |
| Memory operands | Full addressing-mode support with a loud fallback | this doc |
| Abort handling in M12 | Triage only, at most three one-line fixes | this doc |
+787
View File
@@ -0,0 +1,787 @@
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index ae3eecc60fc7..eef40fc1306d 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -787,6 +787,14 @@ def warn_drv_darwin_sdk_invalid_settings : Warning<
InGroup<DiagGroup<"darwin-sdk-settings">>;
def err_missing_sysroot : Error<"no such sysroot directory: '%0'">;
+def err_drv_tms34010_missing_sysroot : Error<
+ "TMS34010 sysroot not found: '%0'; run 'scripts/tms-sdk' to build and install it">;
+def err_drv_tms34010_missing_linker : Error<
+ "TMS34010 linker not found: '%0'; run 'scripts/tms-sdk' to install it">;
+def err_drv_tms34010_missing_python3 : Error<
+ "python3 not found on PATH; the TMS34010 linker requires it (install python3)">;
+def err_drv_tms34010_missing_artifact : Error<
+ "TMS34010 sysroot is incomplete: '%0' is missing; run 'scripts/tms-sdk' to install it">;
def err_drv_darwin_sdk_missing_arclite : Error<
"SDK does not contain 'libarclite' at the path '%0'; try increasing the minimum deployment target">;
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index f893d858d526..5ada0996811e 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -6981,6 +6981,14 @@ def _help_hidden : Flag<["--"], "help-hidden">,
HelpText<"Display help for hidden options">;
def _sysroot_EQ : Joined<["--"], "sysroot=">, Visibility<[ClangOption, FlangOption]>;
def _sysroot : Separate<["--"], "sysroot">, Alias<_sysroot_EQ>;
+def tms_sysroot_EQ : Joined<["--"], "tms-sysroot=">,
+ Visibility<[ClangOption, FlangOption]>,
+ HelpText<"Use the given directory as the TMS34010 sysroot (default: "
+ "<resource-dir>/tms34010-unknown-none)">;
+def tms_linker_EQ : Joined<["--"], "tms-linker=">,
+ Visibility<[ClangOption, FlangOption]>,
+ HelpText<"Use the given executable as the TMS34010 linker (default: "
+ "<sysroot>/bin/tms-link)">;
def no_xcselect : Flag<["--"], "no-xcselect">,
HelpText<"Disable xcselect SDK injection on macOS">;
diff --git a/clang/lib/Basic/Targets/TMS34010.cpp b/clang/lib/Basic/Targets/TMS34010.cpp
index ad27642ae9aa..37cf9243e848 100644
--- a/clang/lib/Basic/Targets/TMS34010.cpp
+++ b/clang/lib/Basic/Targets/TMS34010.cpp
@@ -76,6 +76,9 @@ ArrayRef<const char *> TMS34010TargetInfo::getGCCRegNames() const {
"a8", "a9", "a10", "a11", "a12", "a13", "a14", "a15",
"b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7",
"b8", "b9", "b10", "b11", "b12", "b13", "b14", "b15",
+ // The status register is nameable as a clobber only: ST is outside
+ // every register class, so it can never be chosen as an operand.
+ "st",
};
return Names;
}
diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt
index 506536cdc04f..71ce08e3e5b6 100644
--- a/clang/lib/Driver/CMakeLists.txt
+++ b/clang/lib/Driver/CMakeLists.txt
@@ -91,6 +91,7 @@ add_clang_library(clangDriver
ToolChains/SPIRVOpenMP.cpp
ToolChains/SYCL.cpp
ToolChains/TCE.cpp
+ ToolChains/TMS34010.cpp
ToolChains/UEFI.cpp
ToolChains/VEToolchain.cpp
ToolChains/WebAssembly.cpp
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index e606cdc4c1cf..8a36e6a29fae 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -48,6 +48,7 @@
#include "ToolChains/Serenity.h"
#include "ToolChains/Solaris.h"
#include "ToolChains/TCE.h"
+#include "ToolChains/TMS34010.h"
#include "ToolChains/UEFI.h"
#include "ToolChains/VEToolchain.h"
#include "ToolChains/WebAssembly.h"
@@ -7287,6 +7288,9 @@ const ToolChain &Driver::getToolChain(const ArgList &Args,
case llvm::Triple::msp430:
TC = std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
break;
+ case llvm::Triple::tms34010:
+ TC = std::make_unique<toolchains::TMS34010ToolChain>(*this, Target, Args);
+ break;
case llvm::Triple::riscv32:
case llvm::Triple::riscv64:
case llvm::Triple::riscv32be:
diff --git a/clang/lib/Driver/ToolChains/TMS34010.cpp b/clang/lib/Driver/ToolChains/TMS34010.cpp
new file mode 100644
index 000000000000..238913e830b0
--- /dev/null
+++ b/clang/lib/Driver/ToolChains/TMS34010.cpp
@@ -0,0 +1,264 @@
+//===--- TMS34010.cpp - TMS34010 ToolChain ----------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TMS34010.h"
+
+#include "clang/Driver/Compilation.h"
+#include "clang/Driver/Driver.h"
+#include "clang/Driver/InputInfo.h"
+#include "clang/Driver/Tool.h"
+#include "clang/Options/Options.h"
+#include "llvm/Option/ArgList.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/Path.h"
+#include "llvm/Support/Program.h"
+
+using namespace clang;
+using namespace clang::driver;
+using namespace clang::driver::toolchains;
+using namespace clang::driver::tools;
+using namespace llvm::opt;
+
+TMS34010ToolChain::TMS34010ToolChain(const Driver &D, const llvm::Triple &Triple,
+ const ArgList &Args)
+ : BareMetal(D, Triple, Args) {
+ // Sysroot search order: --tms-sysroot=DIR, then --sysroot/-isysroot, then the
+ // resource directory. Nothing here bakes a checkout path: the resource-dir
+ // fallback is derived from the clang binary, so the toolchain stays
+ // relocatable.
+ if (const Arg *A = Args.getLastArg(options::OPT_tms_sysroot_EQ))
+ SysRoot = A->getValue();
+ else if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ,
+ options::OPT_isysroot))
+ SysRoot = A->getValue();
+ else {
+ SmallString<128> P(D.ResourceDir);
+ llvm::sys::path::append(P, "tms34010-unknown-none");
+ SysRoot = std::string(P.str());
+ }
+
+ // Objects and libraries come from <sysroot>/lib.
+ SmallString<128> LibDir(SysRoot);
+ llvm::sys::path::append(LibDir, "lib");
+ getFilePaths().push_back(std::string(LibDir.str()));
+ getLibraryPaths().push_back(std::string(LibDir.str()));
+}
+
+void TMS34010ToolChain::addClangTargetOptions(
+ const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA,
+ Action::OffloadKind DeviceOffloadKind) const {
+ // The TMS34010 backend has no native 33-bit multiply, so IndVarSimplify's
+ // i33 exit-value rewrite would otherwise reach code generation and abort on
+ // an ordinary loop. Disable that rewrite, and compile freestanding with no
+ // builtins (there is no libc for this target yet).
+ CC1Args.push_back("-ffreestanding");
+ CC1Args.push_back("-fno-builtin");
+ CC1Args.push_back("-mllvm");
+ CC1Args.push_back("-replexitval=never");
+ // The legacy tms-clang path ran the -O0 pipeline without the `optnone`
+ // attribute (it passed -disable-O0-optnone), so its -O0 objects carry the
+ // mem2reg'd shape and no per-parameter spill slot. Match that so native
+ // `clang --target=tms34010 -O0 -c` stays byte-identical to the M9 path.
+ CC1Args.push_back("-disable-O0-optnone");
+
+ BareMetal::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
+}
+
+void TMS34010ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
+ ArgStringList &CC1Args) const {
+ if (DriverArgs.hasArg(options::OPT_nostdinc))
+ return;
+
+ // The target's headers live in <sysroot>/include; the builtin headers keep
+ // being found through -resource-dir, matching the M10 freestanding defaults.
+ if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) {
+ SmallString<128> IncDir(SysRoot);
+ llvm::sys::path::append(IncDir, "include");
+ addSystemInclude(DriverArgs, CC1Args, IncDir.str());
+ }
+}
+
+Tool *TMS34010ToolChain::buildLinker() const {
+ return new tools::tms34010::TMS34010Linker(*this);
+}
+
+void tms34010::TMS34010Linker::ConstructJob(
+ Compilation &C, const JobAction &JA, const InputInfo &Output,
+ const InputInfoList &Inputs, const ArgList &Args,
+ const char *LinkingOutput) const {
+ const auto &TC =
+ static_cast<const toolchains::TMS34010ToolChain &>(getToolChain());
+ const Driver &D = TC.getDriver();
+ const std::string &SysRoot = TC.getTMS34010SysRoot();
+
+ // Linker discovery: --tms-linker=PATH first, else <sysroot>/bin/tms-link.
+ const bool UseDefaultLinker = !Args.hasArg(options::OPT_tms_linker_EQ);
+ std::string Linker;
+ if (const Arg *A = Args.getLastArg(options::OPT_tms_linker_EQ)) {
+ Linker = A->getValue();
+ } else {
+ SmallString<128> DefaultLinker(SysRoot);
+ llvm::sys::path::append(DefaultLinker, "bin", "tms-link");
+ Linker = std::string(DefaultLinker.str());
+ }
+
+ // A missing sysroot, a missing linker or a missing python3 is a named
+ // diagnostic telling the user to run scripts/tms-sdk -- never a bare link
+ // error. The explicit --tms-linker path is trusted verbatim, so neither the
+ // linker-existence nor the python3 check applies to it.
+ if (!llvm::sys::fs::exists(SysRoot)) {
+ D.Diag(diag::err_drv_tms34010_missing_sysroot) << SysRoot;
+ return;
+ }
+ if (UseDefaultLinker && !llvm::sys::fs::exists(Linker)) {
+ D.Diag(diag::err_drv_tms34010_missing_linker) << Linker;
+ return;
+ }
+ // The installed tms-link is a Python program; name python3 if it is missing.
+ if (UseDefaultLinker && !llvm::sys::findProgramByName("python3")) {
+ D.Diag(diag::err_drv_tms34010_missing_python3);
+ return;
+ }
+
+ // Fixed link order: CRT, user objects, the three default libraries, then
+ // user -L/-l archives.
+ const bool WantStartFiles =
+ !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
+ const bool WantDefaultLibs =
+ !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
+
+ // A sysroot directory can exist while the artifacts the default link needs
+ // are absent (a partial install). Name the missing file instead of handing
+ // tms-link a bare name it will fail to open.
+ bool MissingArtifact = false;
+ auto CheckArtifact = [&](StringRef Name) {
+ SmallString<128> P(SysRoot);
+ llvm::sys::path::append(P, "lib", Name);
+ if (llvm::sys::fs::exists(P))
+ return;
+ D.Diag(diag::err_drv_tms34010_missing_artifact) << std::string(P.str());
+ MissingArtifact = true;
+ };
+ if (WantStartFiles)
+ CheckArtifact("crt0.o");
+ if (WantDefaultLibs) {
+ CheckArtifact("libtms.a");
+ CheckArtifact("flib.lib");
+ CheckArtifact("rts.lib");
+ }
+ if (MissingArtifact)
+ return;
+
+ ArgStringList CmdArgs;
+
+ CmdArgs.push_back("-o");
+ CmdArgs.push_back(Output.getFilename());
+
+ CmdArgs.push_back("--entry");
+ CmdArgs.push_back("_start");
+ CmdArgs.push_back("--text");
+ CmdArgs.push_back("018A0000");
+ CmdArgs.push_back("--bss");
+ CmdArgs.push_back("01A00000");
+ CmdArgs.push_back("--prog-len");
+ CmdArgs.push_back("40000h");
+ CmdArgs.push_back("--ram-len");
+ CmdArgs.push_back("80000h");
+
+ // -Wl,-Map suppresses the default --map; -Wl,-Map=<file> and the
+ // -Wl,-Map,<file> comma form select an explicit map file. tms-link spells
+ // its map option --map, so both forms become --map=<file> below.
+ auto WlValues = Args.getAllArgValues(options::OPT_Wl_COMMA);
+ bool HasExplicitMap = false;
+ for (const std::string &Value : WlValues) {
+ StringRef V(Value);
+ if (V == "-Map" || V.starts_with("-Map="))
+ HasExplicitMap = true;
+ }
+
+ // The map is this toolchain's debugging surface: default it next to the
+ // output unless the user asked for a -Wl,-Map* form.
+ if (!HasExplicitMap) {
+ std::string MapFile = std::string(Output.getFilename()) + ".map";
+ CmdArgs.push_back("--map");
+ CmdArgs.push_back(Args.MakeArgString(MapFile));
+ }
+
+ // -g keeps the DWARF in the linked image; the default stays stripped. -g0
+ // (and -ggdb0) request no debug info, so they must not add --keep-debug.
+ if (Arg *A = Args.getLastArg(options::OPT_g_Group))
+ if (!A->getOption().matches(options::OPT_g0) &&
+ !A->getOption().matches(options::OPT_ggdb0))
+ CmdArgs.push_back("--keep-debug");
+
+ // Pass the remaining -Wl, arguments through verbatim, translating the map
+ // requests. -Wl,-Map,<file> keeps the path in the following comma element.
+ for (size_t I = 0, E = WlValues.size(); I != E; ++I) {
+ StringRef V(WlValues[I]);
+ if (V == "-Map") {
+ // A bare -Wl,-Map has no path and produces no map (it still suppresses
+ // the default map, as above); a following element is the map path.
+ if (I + 1 != E) {
+ std::string MapArg = "--map=" + std::string(WlValues[++I]);
+ CmdArgs.push_back(Args.MakeArgString(MapArg));
+ }
+ continue;
+ }
+ if (V.starts_with("-Map=")) {
+ std::string MapArg = "--map=" + std::string(V.drop_front(5));
+ CmdArgs.push_back(Args.MakeArgString(MapArg));
+ continue;
+ }
+ CmdArgs.push_back(Args.MakeArgString(V));
+ }
+
+ // Fixed link order: CRT, user objects, the three default libraries, then
+ // user -L/-l archives.
+ if (WantStartFiles)
+ CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt0.o")));
+
+ for (const auto &II : Inputs) {
+ if (II.isFilename())
+ CmdArgs.push_back(II.getFilename());
+ }
+
+ if (WantDefaultLibs) {
+ CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("libtms.a")));
+ CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("flib.lib")));
+ CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("rts.lib")));
+ }
+
+ // Make the sysroot's own library directory reachable for -l lookups before
+ // any user -L paths.
+ SmallString<128> SysRootLib(SysRoot);
+ llvm::sys::path::append(SysRootLib, "lib");
+ CmdArgs.push_back("-L");
+ CmdArgs.push_back(Args.MakeArgString(SysRootLib.str()));
+
+ for (const std::string &LibPath : Args.getAllArgValues(options::OPT_L)) {
+ CmdArgs.push_back("-L");
+ CmdArgs.push_back(Args.MakeArgString(LibPath));
+ }
+ for (const std::string &Lib : Args.getAllArgValues(options::OPT_l)) {
+ // -l tms means "ensure libtms.a is linked". With the defaults it is already
+ // a positional input, so it is a no-op; with -nodefaultlibs/-nostdlib the
+ // user's -l tms is the only request, so resolve it to the archive so it is
+ // linked once per request (repeating -l tms links the archive again).
+ if (StringRef(Lib) == "tms") {
+ if (!WantDefaultLibs)
+ CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("libtms.a")));
+ continue;
+ }
+ CmdArgs.push_back("-l");
+ CmdArgs.push_back(Args.MakeArgString(Lib));
+ }
+
+ C.addCommand(std::make_unique<Command>(
+ JA, *this, ResponseFileSupport::None(),
+ Args.MakeArgString(Linker), CmdArgs, Inputs, Output));
+}
diff --git a/clang/lib/Driver/ToolChains/TMS34010.h b/clang/lib/Driver/ToolChains/TMS34010.h
new file mode 100644
index 000000000000..e69011479677
--- /dev/null
+++ b/clang/lib/Driver/ToolChains/TMS34010.h
@@ -0,0 +1,68 @@
+//===--- TMS34010.h - TMS34010 ToolChain ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TMS34010_H
+#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TMS34010_H
+
+#include "BareMetal.h"
+#include "clang/Driver/Tool.h"
+
+namespace clang {
+namespace driver {
+namespace toolchains {
+
+class LLVM_LIBRARY_VISIBILITY TMS34010ToolChain : public BareMetal {
+public:
+ TMS34010ToolChain(const Driver &D, const llvm::Triple &Triple,
+ const llvm::opt::ArgList &Args);
+
+ void
+ addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
+ llvm::opt::ArgStringList &CC1Args, BoundArch BA,
+ Action::OffloadKind DeviceOffloadKind) const override;
+
+ void
+ AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
+ llvm::opt::ArgStringList &CC1Args) const override;
+
+ /// The sysroot this target's headers, libraries and linker come from,
+ /// resolved from --tms-sysroot=, --sysroot/-isysroot, or the resource dir.
+ std::string getTMS34010SysRoot() const { return SysRoot; }
+
+protected:
+ Tool *buildLinker() const override;
+
+private:
+ std::string SysRoot;
+};
+
+} // namespace toolchains
+
+namespace tools {
+namespace tms34010 {
+
+class LLVM_LIBRARY_VISIBILITY TMS34010Linker final : public Tool {
+public:
+ TMS34010Linker(const ToolChain &TC)
+ : Tool("tms34010::Linker", "tms-link", TC) {}
+
+ bool isLinkJob() const override { return true; }
+ bool hasIntegratedCPP() const override { return false; }
+
+ void ConstructJob(Compilation &C, const JobAction &JA,
+ const InputInfo &Output, const InputInfoList &Inputs,
+ const llvm::opt::ArgList &TCArgs,
+ const char *LinkingOutput) const override;
+};
+
+} // namespace tms34010
+} // namespace tools
+} // namespace driver
+} // namespace clang
+
+#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_TMS34010_H
diff --git a/clang/test/CodeGen/TMS34010/bitaddr-chain-o2.c b/clang/test/CodeGen/TMS34010/bitaddr-chain-o2.c
new file mode 100644
index 000000000000..8d4a838ac157
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/bitaddr-chain-o2.c
@@ -0,0 +1,24 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -mllvm -replexitval=never -S -o - %s | FileCheck %s
+//
+// Source-level pointer arithmetic goes through the pre-optimizer barrier
+// (@__tms_bitptr) and is lowered back by tms34010LowerBitPtr. If that lowering
+// emitted the foldable `inttoptr(add(ptrtoint base, off))` form, the already-bit
+// offsets would fold to a plain ISD::ADD on `p:32` and DAGCombiner's
+// BaseIndexOffset aliasing would read them as *bytes*: the word store to p+32
+// bits and the byte store to p+40 bits would be misread as +32 and +40 bytes
+// and reported non-aliasing, and parallelizeChainedStores would hoist the byte
+// store ahead of the word store (the word store then overwrites the byte).
+//
+// The lowering emits llvm.tms34010.bitaddr instead, which lowers to a
+// TMS34010ISD::BITADDR node that BaseIndexOffset cannot decompose, so the byte
+// store keeps its program-order position after the word store.
+
+void f(int *p, int v, int w) { p[0] = v; p[1] = w; ((char *)p)[5] = 0x7f; }
+
+// The word store to p+32 bits (MOVE ..., *..., 1 after ADDI 32) must be
+// scheduled before the byte store to p+40 bits (MOVB after ADDI 40).
+// CHECK-LABEL: _f:
+// CHECK: ADDI 32, A{{[0-9]+}}
+// CHECK: MOVE A{{[0-9]+}}, *A{{[0-9]+}}, 1
+// CHECK: ADDI 40, A{{[0-9]+}}
+// CHECK: MOVB A{{[0-9]+}}, *A{{[0-9]+}}
diff --git a/clang/test/CodeGen/TMS34010/bitaddr-o0.c b/clang/test/CodeGen/TMS34010/bitaddr-o0.c
new file mode 100644
index 000000000000..e62cab807aa3
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/bitaddr-o0.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -S -o - %s | FileCheck %s
+//
+// The bit-address barrier hides each source GEP behind an opaque
+// @__tms_bitptr(i32 bitoff, ptr base) call before the optimizer, and -O0
+// lowers it straight back to the bit-addressed inttoptr(add) form, so a
+// byte-indexed GEP must reach codegen as an 8x bit offset.
+
+int load_i(int *p) { return p[1]; }
+short load_h(short *p) { return p[1]; }
+int load_b(char *p) { return p[4]; }
+
+// CHECK-LABEL: _load_i:
+// CHECK: ADDI 32, A{{[0-9]+}}
+// CHECK-NOT: ADDI 4, A
+// CHECK-LABEL: _load_h:
+// CHECK: ADDI 16, A{{[0-9]+}}
+// CHECK-LABEL: _load_b:
+// CHECK: ADDI 32, A{{[0-9]+}}
diff --git a/clang/test/CodeGen/TMS34010/bitaddr-o1.c b/clang/test/CodeGen/TMS34010/bitaddr-o1.c
new file mode 100644
index 000000000000..acefd9de2af6
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/bitaddr-o1.c
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O1 -S -o - %s | FileCheck %s
+//
+// The -O0 sibling (bitaddr-o0.c) pins the byte-indexed-GEP bit-address shape
+// on the no-optimizer path. -O1 takes the optimizer-last path instead: the
+// bit-address barrier hides each source GEP before the optimizer, the post-opt
+// scale rescales the byte GEPs the optimizer creates, and lowering undoes the
+// barrier. This test pins the same shape on that path, which is otherwise
+// covered only indirectly by the static-variadic guard test.
+
+int load_i(int *p) { return p[1]; }
+short load_h(short *p) { return p[1]; }
+int load_b(char *p) { return p[4]; }
+
+// CHECK-LABEL: _load_i:
+// CHECK: ADDI 32, A{{[0-9]+}}
+// CHECK-NOT: ADDI 4, A
+// CHECK-LABEL: _load_h:
+// CHECK: ADDI 16, A{{[0-9]+}}
+// CHECK-LABEL: _load_b:
+// CHECK: ADDI 32, A{{[0-9]+}}
diff --git a/clang/test/CodeGen/TMS34010/bitaddr-o2.c b/clang/test/CodeGen/TMS34010/bitaddr-o2.c
new file mode 100644
index 000000000000..39b0f38ce948
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/bitaddr-o2.c
@@ -0,0 +1,17 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -mllvm -replexitval=never -S -o - %s | FileCheck %s
+//
+// At -O2 the barrier hides source GEPs before the optimizer, the post-opt
+// scale rescales the byte GEPs the optimizer creates, lowering undoes the
+// barrier, and a final instcombine canonicalizes the result, so a byte-indexed
+// GEP must still reach codegen as an 8x bit offset. `-replexitval=never` is
+// the ToolChain default (Task 1); %clang_cc1 bypasses the driver, so it is
+// passed explicitly to keep the `sumto` loop below the i33 closed-form
+// rewrite.
+
+int load_i(int *p) { return p[1]; }
+int sumto(int n) { int s = 0; for (int i = 0; i <= n; i++) s += i; return s; }
+
+// CHECK-LABEL: _load_i:
+// CHECK: ADDI 32, A{{[0-9]+}}
+// CHECK-NOT: ADDI 4, A
+// CHECK-LABEL: _sumto:
diff --git a/clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c b/clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c
new file mode 100644
index 000000000000..fc6867b143b4
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/bitaddr-static-vararg.c
@@ -0,0 +1,6 @@
+// RUN: not %clang_cc1 -triple tms34010-unknown-none -O1 -emit-obj %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -triple tms34010-unknown-none -O2 -emit-obj %s -o /dev/null 2>&1 | FileCheck %s
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -emit-obj %s -o /dev/null
+// CHECK: static variadic definition 'sum' loses its '...' arguments when optimizing
+static int sum(int n, ...) { int *p = &n; return p[0] + p[1]; }
+int call(void) { return sum(1, 2); }
diff --git a/clang/test/CodeGen/TMS34010/float-const-o2.c b/clang/test/CodeGen/TMS34010/float-const-o2.c
new file mode 100644
index 000000000000..4f244591b61a
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/float-const-o2.c
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -mllvm -replexitval=never -S -o - %s | FileCheck %s
+//
+// A float literal stored to memory through a union (or returned by a helper
+// whose constant result IPSCCP propagates) must be materialised from a
+// GSP-initialised global. The early float-constant protection keeps the
+// constant a load before the optimizer can fold it through the union bitcast
+// to its IEEE bits; the AsmPrinter then emits the GSP words.
+
+typedef unsigned int u32;
+typedef union { float f; u32 u; } fu;
+extern volatile u32 markers[];
+
+static void mark_f(u32 n, float v) { fu x; x.f = v; markers[n] = x.u; }
+float fnegzero(void) { return -0.0f; }
+
+void run(void) {
+ mark_f(0, 7.0f); // GSP 41700000h, never IEEE 40E00000h
+ mark_f(1, fnegzero()); // GSP +0, never IEEE -0 (80000000h)
+}
+
+// 7.0f is GSP 41700000h and -0.0f canonicalises to +0 (all zeroes); the IEEE
+// bits (40E00000h / 80000000h) must never be stored anywhere.
+// CHECK-DAG: .long 41700000h
+// CHECK-DAG: .long 00000000h
+// CHECK-NOT: .long 40E00000h
+// CHECK-NOT: .long 80000000h
diff --git a/clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c b/clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c
new file mode 100644
index 000000000000..9a1512116c74
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/m12-inline-asm-mem.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -S -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O2 -S -o - %s | FileCheck %s
+//
+// M12: an `m` operand is a memory operand the backend can now address. The
+// asm template is empty, so the bar is that the selector finds a valid
+// TMS34010 address for the operand instead of the M9 named error; the
+// addressing form itself is covered by m12-inline-asm-mem-forms.ll.
+int load_via_asm(int *p) {
+ int x;
+ __asm__ volatile("" : "=r"(x) : "m"(*p) : "memory");
+ return x;
+}
+int store_via_asm(int *p, int v) {
+ __asm__ volatile("" : : "m"(*p), "r"(v) : "memory");
+ return v;
+}
+// CHECK-LABEL: _load_via_asm:
+// CHECK-NOT: error:
+// CHECK-LABEL: _store_via_asm:
diff --git a/clang/test/CodeGen/TMS34010/m12-inline-asm-st.c b/clang/test/CodeGen/TMS34010/m12-inline-asm-st.c
new file mode 100644
index 000000000000..ca1f041f709d
--- /dev/null
+++ b/clang/test/CodeGen/TMS34010/m12-inline-asm-st.c
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -triple tms34010-unknown-none -O0 -S -o - %s | FileCheck %s
+//
+// M12: `st` names the status register as a clobber. Before M12 clang rejected
+// the name ("unknown register name 'st' in asm") because getGCCRegNames()
+// listed only the A/B files. ST stays out of every register class and out of
+// the operand constraints, so this only makes the clobber nameable.
+int clobber_st(int x) {
+ __asm__ volatile("" : "+r"(x) : : "st");
+ return x;
+}
+// CHECK-LABEL: _clobber_st:
diff --git a/clang/test/Driver/TMS34010-link.c b/clang/test/Driver/TMS34010-link.c
new file mode 100644
index 000000000000..3b067d9eb3b6
--- /dev/null
+++ b/clang/test/Driver/TMS34010-link.c
@@ -0,0 +1,147 @@
+// Check that the TMS34010 driver discovers its sysroot and turns a link into a
+// real tms-link job, and that the link-reduction knobs, -g and -Wl, behave.
+//
+// The link cases below use a fake sysroot so the test is hermetic and does
+// not depend on `scripts/tms-sdk` having been run: the CRT and the three
+// libraries are empty placeholders under <sysroot>/lib, and the linker is the
+// touched placeholder under <sysroot>/bin.
+
+// RUN: rm -rf %t.sysroot && mkdir -p %t.sysroot/bin %t.sysroot/lib %t.sysroot/include
+// RUN: touch %t.sysroot/bin/tms-link %t.sysroot/lib/crt0.o %t.sysroot/lib/libtms.a %t.sysroot/lib/flib.lib %t.sysroot/lib/rts.lib
+
+// Default link: the sysroot linker, the fixed flags, the CRT, the object and
+// the three default libraries, plus the sysroot include path and a default map.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot %s -o %t.out 2>&1 | FileCheck %s --check-prefix=DEFAULT
+// DEFAULT: "-internal-isystem" "{{.*}}sysroot{{/|\\}}include"
+// DEFAULT: "{{.*}}tms-link"
+// DEFAULT-SAME: "-o" "{{.*}}.out"
+// DEFAULT-SAME: "--entry" "_start"
+// DEFAULT-SAME: "--text" "018A0000"
+// DEFAULT-SAME: "--bss" "01A00000"
+// DEFAULT-SAME: "--prog-len" "40000h"
+// DEFAULT-SAME: "--ram-len" "80000h"
+// DEFAULT-SAME: "--map" "{{.*}}.out.map"
+// DEFAULT-SAME: crt0.o
+// DEFAULT-SAME: libtms.a
+// DEFAULT-SAME: flib.lib
+// DEFAULT-SAME: rts.lib
+// DEFAULT-SAME: "-L" "{{.*}}sysroot{{/|\\}}lib"
+
+// -nostdlib drops the CRT and all three libraries.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -nostdlib %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NOSTDLIB
+// NOSTDLIB: "{{.*}}tms-link"
+// NOSTDLIB-NOT: crt0.o
+// NOSTDLIB-NOT: libtms.a
+// NOSTDLIB-NOT: flib.lib
+// NOSTDLIB-NOT: rts.lib
+
+// -nostartfiles drops only the CRT; the libraries remain.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -nostartfiles %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NOSTART
+// NOSTART: "{{.*}}tms-link"
+// NOSTART-NOT: crt0.o
+// NOSTART-SAME: libtms.a
+// NOSTART-SAME: flib.lib
+// NOSTART-SAME: rts.lib
+
+// -nodefaultlibs keeps the CRT but drops the three libraries.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -nodefaultlibs %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NODEFLTLIBS
+// NODEFLTLIBS: "{{.*}}tms-link"
+// NODEFLTLIBS-SAME: crt0.o
+// NODEFLTLIBS-NOT: libtms.a
+// NODEFLTLIBS-NOT: flib.lib
+// NODEFLTLIBS-NOT: rts.lib
+
+// With -nodefaultlibs, -l tms is the user's only way to ask for the archive;
+// it must resolve to libtms.a exactly once, with no flib/rts.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -nodefaultlibs -l tms %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NODEFL_LTMS
+// NODEFL_LTMS: "{{.*}}tms-link"
+// NODEFL_LTMS-SAME: crt0.o
+// NODEFL_LTMS-SAME: libtms.a
+// NODEFL_LTMS-NOT: libtms.a
+// NODEFL_LTMS-NOT: flib.lib
+// NODEFL_LTMS-NOT: rts.lib
+// NODEFL_LTMS-NOT: "-l" "tms"
+
+// -g adds --keep-debug.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -g %s -o %t.out 2>&1 | FileCheck %s --check-prefix=G
+// G: "{{.*}}tms-link"
+// G-SAME: "--keep-debug"
+
+// -g0 and -ggdb0 request no debug info, so no --keep-debug.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -g0 %s -o %t.out 2>&1 | FileCheck %s --check-prefix=G0
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -ggdb0 %s -o %t.out 2>&1 | FileCheck %s --check-prefix=G0
+// G0: "{{.*}}tms-link"
+// G0-NOT: "--keep-debug"
+
+// -Wl, arguments pass through verbatim.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -Wl,--prog-len=80000h %s -o %t.out 2>&1 | FileCheck %s --check-prefix=WL
+// WL: "{{.*}}tms-link"
+// WL-SAME: "--prog-len=80000h"
+
+// -Wl,-Map=<file> selects that map file and suppresses the default --map.
+// The NOT range starts at the linker token so a stray default map (which
+// would be emitted before the translated --map=) is caught too.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -Wl,-Map=foo.map %s -o %t.out 2>&1 | FileCheck %s --check-prefix=MAPEQ
+// MAPEQ: "{{.*}}tms-link"
+// MAPEQ-NOT: "--map" "{{.*}}.out.map"
+// MAPEQ: "--map=foo.map"
+// MAPEQ-NOT: "foo.map"
+
+// -Wl,-Map,<file> (the comma form) consumes the next element as the map path
+// instead of forwarding the filename as a linker input.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -Wl,-Map,foo.map %s -o %t.out 2>&1 | FileCheck %s --check-prefix=MAPCOMMA
+// MAPCOMMA: "{{.*}}tms-link"
+// MAPCOMMA-NOT: "--map" "{{.*}}.out.map"
+// MAPCOMMA: "--map=foo.map"
+// MAPCOMMA-NOT: "foo.map"
+
+// --tms-linker=PATH replaces the sysroot linker.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot --tms-linker=/tmp/x %s -o %t.out 2>&1 | FileCheck %s --check-prefix=LINKER
+// LINKER: "/tmp/x"
+// LINKER-SAME: "--entry" "_start"
+
+// -l tms is accepted and does not duplicate libtms.a.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -l tms %s -o %t.out 2>&1 | FileCheck %s --check-prefix=LTMS
+// LTMS: "{{.*}}tms-link"
+// LTMS-SAME: libtms.a
+// LTMS-NOT: "-l" "tms"
+
+// A nonexistent sysroot is a named diagnostic, not a link error.
+// RUN: not %clang -### --target=tms34010 --tms-sysroot=/nope %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NOSYSROOT
+// NOSYSROOT: error: TMS34010 sysroot not found
+// NOSYSROOT-SAME: run 'scripts/tms-sdk'
+// NOSYSROOT-NOT: "tms-link"
+
+// A sysroot without bin/tms-link is a named diagnostic, not a link error.
+// RUN: rm -rf %t.nolink && mkdir -p %t.nolink
+// RUN: not %clang -### --target=tms34010 --tms-sysroot=%t.nolink %s -o %t.out 2>&1 | FileCheck %s --check-prefix=NOLINKER
+// NOLINKER: error: TMS34010 linker not found
+// NOLINKER-SAME: run 'scripts/tms-sdk'
+// NOLINKER-NOT: "tms-link"
+
+// A sysroot directory that exists but lacks the artifacts the default link
+// needs names each missing file and points at scripts/tms-sdk, instead of
+// handing tms-link bare names.
+// RUN: rm -rf %t.partial && mkdir -p %t.partial/bin %t.partial/lib %t.partial/include
+// RUN: touch %t.partial/bin/tms-link
+// RUN: not %clang -### --target=tms34010 --tms-sysroot=%t.partial %s -o %t.out 2>&1 | FileCheck %s --check-prefix=PARTIAL
+// PARTIAL-DAG: error: TMS34010 sysroot is incomplete: '{{.*}}crt0.o' is missing
+// PARTIAL-DAG: error: TMS34010 sysroot is incomplete: '{{.*}}libtms.a' is missing
+// PARTIAL-DAG: error: TMS34010 sysroot is incomplete: '{{.*}}flib.lib' is missing
+// PARTIAL-DAG: error: TMS34010 sysroot is incomplete: '{{.*}}rts.lib' is missing
+// PARTIAL-DAG: run 'scripts/tms-sdk'
+
+// With -nostdlib nothing is needed from the sysroot's lib directory, so the
+// same partial sysroot still reaches the (placeholder) linker.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.partial -nostdlib %s -o %t.out 2>&1 | FileCheck %s --check-prefix=PARTIALNOSTDLIB
+// PARTIALNOSTDLIB: "{{.*}}tms-link"
+// PARTIALNOSTDLIB-NOT: sysroot is incomplete
+
+// Compile-only modes emit no link job.
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -c %s 2>&1 | FileCheck %s --check-prefix=NOLINK
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -S %s 2>&1 | FileCheck %s --check-prefix=NOLINK
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -E %s 2>&1 | FileCheck %s --check-prefix=NOLINK
+// RUN: %clang -### --target=tms34010 --tms-sysroot=%t.sysroot -S -emit-llvm %s 2>&1 | FileCheck %s --check-prefix=NOLINK
+// NOLINK-NOT: tms-link
+
+int f(int n) { return n + 1; }
diff --git a/clang/test/Driver/tms34010-defaults.c b/clang/test/Driver/tms34010-defaults.c
new file mode 100644
index 000000000000..568a4a0b3434
--- /dev/null
+++ b/clang/test/Driver/tms34010-defaults.c
@@ -0,0 +1,9 @@
+// RUN: %clang -### --target=tms34010 -c %s 2>&1 | FileCheck %s --check-prefix=FLAGS
+// RUN: %clang -### --target=tms34010 -c %s 2>&1 | FileCheck %s --check-prefix=NOSYS
+// FLAGS: "-cc1" {{.*}}-ffreestanding
+// FLAGS-SAME: -fno-builtin
+// FLAGS-SAME: "-mllvm" "-replexitval=never"
+// FLAGS-SAME: "-disable-O0-optnone"
+// NOSYS: "-internal-isystem" "{{.*}}tms34010-unknown-none{{/|\\}}include"
+// NOSYS-NOT: "-internal-isystem" "/usr/"
+int f(int n) { return n + 1; }
+134
View File
@@ -0,0 +1,134 @@
#!/bin/sh
# Fetch the pinned external conformance corpora into vendor/conformance.
#
# scripts/fetch-conformance.sh [DEST]
# scripts/fetch-conformance.sh --gcc-only [DEST]
# scripts/fetch-conformance.sh --c-testsuite-only [DEST]
#
# DEST defaults to vendor/conformance (ignored by git). Nothing in the
# tracked tree is written.
#
# Pins:
# GCC 16.2.0 https://ftp.gnu.org/gnu/gcc/gcc-16.2.0/gcc-16.2.0.tar.xz
# SHA-256 e6738e29597f733270731aa90600f37ffdc045079dfc27ec7e8192cc81085c3e
# (only gcc/testsuite/gcc.c-torture and COPYING* are extracted)
# c-testsuite 5c7275656d751de0e68b2d340a95b5681858ed07
# https://github.com/c-testsuite/c-testsuite
#
# The corpus licences are preserved in each extracted tree (COPYING*). The
# tests are test-only and are not part of the compiler or project
# distribution.
set -eu
ROOT=$(cd "$(dirname "$0")/.." && pwd)
GCC_VERSION=16.2.0
GCC_TOP=gcc-$GCC_VERSION
GCC_URL=https://ftp.gnu.org/gnu/gcc/$GCC_TOP/$GCC_TOP.tar.xz
GCC_SHA256=e6738e29597f733270731aa90600f37ffdc045079dfc27ec7e8192cc81085c3e
CTEST_REPO=https://github.com/c-testsuite/c-testsuite
CTEST_COMMIT=5c7275656d751de0e68b2d340a95b5681858ed07
DO_GCC=1
DO_CTEST=1
DEST=
while [ $# -gt 0 ]; do
case $1 in
--gcc-only) DO_CTEST=0; shift ;;
--c-testsuite-only) DO_GCC=0; shift ;;
-h|--help)
sed -n '2,/^set -eu/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'
exit 0
;;
-*) echo "fetch-conformance: unknown option: $1" >&2; exit 2 ;;
*)
[ -z "$DEST" ] || { echo "fetch-conformance: more than one DEST" >&2; exit 2; }
DEST=$1
shift
;;
esac
done
DEST=${DEST:-$ROOT/vendor/conformance}
mkdir -p "$DEST"
DEST=$(cd "$DEST" && pwd)
fail() {
echo "fetch-conformance: FAIL: $*" >&2
exit 1
}
download() {
url=$1
out=$2
if command -v curl >/dev/null 2>&1; then
curl -fL --retry 3 --connect-timeout 30 -o "$out.part" "$url"
elif command -v wget >/dev/null 2>&1; then
wget -O "$out.part" "$url"
else
fail "need curl or wget to download $url"
fi
mv "$out.part" "$out"
}
if [ "$DO_GCC" -eq 1 ]; then
TAR=$DEST/downloads/$GCC_TOP.tar.xz
mkdir -p "$DEST/downloads"
if [ ! -f "$TAR" ]; then
echo "== download $GCC_URL"
download "$GCC_URL" "$TAR"
fi
echo "== verify $GCC_TOP.tar.xz"
printf '%s %s\n' "$GCC_SHA256" "$TAR" | sha256sum -c - \
|| fail "SHA-256 mismatch for $TAR"
if [ ! -d "$DEST/$GCC_TOP/gcc/testsuite/gcc.c-torture/execute" ]; then
echo "== extract gcc.c-torture and COPYING*"
tar -xJf "$TAR" -C "$DEST" --wildcards \
"$GCC_TOP/gcc/testsuite/gcc.c-torture/*" \
"$GCC_TOP/COPYING*"
else
echo "== gcc.c-torture already extracted"
fi
[ -d "$DEST/$GCC_TOP/gcc/testsuite/gcc.c-torture/execute" ] \
|| fail "extraction produced no gcc.c-torture/execute"
ls "$DEST/$GCC_TOP"/COPYING* >/dev/null 2>&1 \
|| fail "extraction preserved no COPYING file"
fi
if [ "$DO_CTEST" -eq 1 ]; then
CTEST=$DEST/c-testsuite
if [ ! -d "$CTEST/.git" ]; then
echo "== clone $CTEST_REPO"
mkdir -p "$(dirname "$CTEST")"
git clone --filter=blob:none --no-checkout "$CTEST_REPO" "$CTEST"
fi
echo "== checkout c-testsuite $CTEST_COMMIT"
git -C "$CTEST" fetch --depth 1 origin "$CTEST_COMMIT" 2>/dev/null || true
git -C "$CTEST" checkout --detach "$CTEST_COMMIT"
REV=$(git -C "$CTEST" rev-parse HEAD)
[ "$REV" = "$CTEST_COMMIT" ] \
|| fail "c-testsuite is at $REV, want $CTEST_COMMIT"
[ -d "$CTEST/tests/single-exec" ] \
|| fail "c-testsuite checkout has no tests/single-exec"
if [ -f "$CTEST/COPYING" ]; then
:
elif [ -f "$CTEST/LICENSE" ]; then
:
else
fail "c-testsuite checkout preserved no COPYING/LICENSE"
fi
fi
{
printf 'gcc_version\t%s\n' "$GCC_VERSION"
printf 'gcc_url\t%s\n' "$GCC_URL"
printf 'gcc_sha256\t%s\n' "$GCC_SHA256"
printf 'c_testsuite_repo\t%s\n' "$CTEST_REPO"
printf 'c_testsuite_commit\t%s\n' "$CTEST_COMMIT"
} > "$DEST/PINS"
echo "== pinned conformance corpora at $DEST"
du -sh "$DEST" 2>/dev/null || true
+1 -1
View File
@@ -21,7 +21,7 @@
.globl _start
_start:
setf 32, 0, 1 ; FS1 = 32 for 32-bit MOVE
setf 16, 0, 0 ; FS0 = 16, for any i16 code
setf 16, 1, 0 ; FS0 = 16, for any i16 code
movi 20, a0
movi 22, a1
calla _add
+12 -5
View File
@@ -268,7 +268,7 @@ expect_seq "$TMP/keep.txt" \
'move[[:space:]]+a14,[[:space:]]*-\*sp,[[:space:]]*1' \
'move[[:space:]]+[^,]+,[[:space:]]*\*a14\+,[[:space:]]*1' \
'calla' \
'setf[[:space:]]+16,[[:space:]]*0,[[:space:]]*0' \
'setf[[:space:]]+16,[[:space:]]*1,[[:space:]]*0' \
'setf[[:space:]]+32,[[:space:]]*0,[[:space:]]*1' \
'move[[:space:]]+\*sp\(0x[0-9a-f]+\),[[:space:]]*a14,[[:space:]]*1' \
'rets[[:space:]]+2([[:space:]]*(;|$))'
@@ -291,8 +291,15 @@ check_stk() {
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
tolower($0) ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
{ low = tolower($0) }
low ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
low ~ /mmtm[[:space:]]+sp,/ {
line = low
sub(/^.*mmtm[[:space:]]+sp,[[:space:]]*/, "", line)
sub(/[[:space:]]*;.*$/, "", line)
n += split(line, regs, ",")
}
low ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
' "$TMP/func.txt")
[ -n "$_pushes" ] || fail "$_label has no SETFP (MOVE A14,A13)"
_operand=$(grep -Eio '\*sp\(0x[0-9a-f]+\)' "$TMP/func.txt" | head -1 \
@@ -301,8 +308,8 @@ check_stk() {
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes pushes need $_want bits"
echo " ok $_label: $_pushes pushes -> *SP($(printf '0x%x' "$_want")), A14, 1"
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes saved slots need $_want bits"
echo " ok $_label: $_pushes saved slots -> *SP($(printf '0x%x' "$_want")), A14, 1"
}
check_stk "_add2" "$ADD2"
check_stk "_first" "$FIRST"
+1 -1
View File
@@ -11,7 +11,7 @@
.globl _start
_start:
setf 32, 0, 1
setf 16, 0, 0
setf 16, 1, 0
movi _cstack, a14
move a14, a13
+73 -58
View File
@@ -7,11 +7,13 @@
# 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, JALT, JAGT, JAEQ, JAUC and LBB… labels (never .LBB)
# branch code: CMP plus relative JR/JR<cc> branches (absolute JA* only for a
# zero-displacement or out-of-range target) and LBB… labels (never .LBB)
# .data: 30 3A 3A 30 00 ("0::0")
# old-STK restore offsets: *SP((pushes+1)*32),A14
#
@@ -256,8 +258,8 @@ expect_at "_XOpenDisplay" "$XOPEN" "JAUC 3F9C2570" \
'jauc[[:space:]]+0x3f9c2570'
expect_at "_XCreateSimpleWindow" "$XCREATE" "JAUC 3FD41B90" \
'jauc[[:space:]]+0x3fd41b90'
expect_at "_XMapWindow" "$XMAP" "JAUC 3FD645B0" \
'jauc[[:space:]]+0x3fd645b0'
expect_at "_XMapWindow" "$XMAP" "JAUC 3FD64F60" \
'jauc[[:space:]]+0x3fd64f60'
expect_at "_XSync" "$XSYNC" "JAUC 3FD9F6B0" \
'jauc[[:space:]]+0x3fd9f6b0'
@@ -289,59 +291,44 @@ P4=$(count_between "$TMP/xhello.txt" "calla[[:space:]]+l${XMAP_L}" \
echo " ok argument pushes: XOpenDisplay=1 XCreateSimpleWindow=9 XMapWindow=2 XSync=2"
# Counting pushes is not enough: the nine words must reach the callee in the
# ABI order. build/m3/m3.lst records background 1, border 0, border width 2,
# height 200, width 400, y 100, then x 100 (x reuses y's register, so there are
# six MOVIs for the seven constants), followed by the root (A2) and display
# (A0) pushes. Assert the immediates and push registers as one sequence, so a
# swapped pair fails even though the count stays nine, and require the final
# push before CALLA to be the display register.
# ABI order. Parse the linked assembly the way the M4 dis34 gate does: record
# each MOVI's register/value pair, then map every push register to the last
# value loaded into it. The root (A2) and display (A0) are named explicitly.
# x reuses y's register, so there are six MOVIs for the seven constants. This
# fails a swapped immediate or register while keeping the exact nine-argument
# order 1,0,2,200,400,100,100,root,display and the display pushed last.
awk '
tolower($0) ~ /calla[[:space:]]+l'"$XOPEN_L"'/ { on = 1; next }
tolower($0) ~ /calla[[:space:]]+l'"$XCREATE_L"'/ { exit }
/^[[:space:]]*CALLA[[:space:]]+_XOpenDisplay/ { on = 1; next }
/^[[:space:]]*CALLA[[:space:]]+_XCreateSimpleWindow/ { exit }
!on { next }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*-\*sp,[[:space:]]*1/ { started = 1; next }
!started { next }
tolower($0) ~ /movi[[:space:]]+/ {
/^[[:space:]]*MOVI[[:space:]]/ {
line = $0
sub(/^[^:]*:[[:space:]]+movi[[:space:]]+/, "", line)
sub(/.*MOVI[[:space:]]+/, "", line)
sub(/[[:space:]]*;.*/, "", line)
sub(/[[:space:]]+/, " ", line)
split(line, p, /,[[:space:]]*/)
printf "IMM %s %s\n", tolower(p[1]), tolower(p[2])
gsub(/[[:space:]]/, "", p[1])
gsub(/[[:space:]]/, "", p[2])
val[p[2]] = p[1]
next
}
tolower($0) ~ /move[[:space:]]+a[0-9]+,[[:space:]]*\*a14\+,[[:space:]]*1/ {
/^[[:space:]]*MOVE[[:space:]]+A[0-9]+,[[:space:]]*\*A14\+,/ {
line = $0
sub(/^[^:]*:[[:space:]]+move[[:space:]]+/, "", line)
sub(/.*MOVE[[:space:]]+/, "", line)
sub(/,.*/, "", line)
printf "PUSH %s\n", tolower(line)
next
v = val[line]
if (line == "A2") v = "root"
if (line == "A0") v = "display"
print v
}
' "$TMP/xhello.txt" > "$TMP/xcreate.seq"
cat > "$TMP/xcreate.want" <<'EOF'
IMM 0x1 a1
PUSH a1
IMM 0x0 a1
PUSH a1
IMM 0x2 a3
PUSH a3
IMM 0xc8 a3
PUSH a3
IMM 0x190 a3
PUSH a3
IMM 0x64 a3
PUSH a3
PUSH a3
PUSH a2
PUSH a0
EOF
if ! cmp -s "$TMP/xcreate.want" "$TMP/xcreate.seq"; then
' "$ASM" > "$TMP/xcreate.vals"
printf '%s\n' 1 0 2 200 400 100 100 root display > "$TMP/xcreate.want"
if ! cmp -s "$TMP/xcreate.want" "$TMP/xcreate.vals"; then
{
echo "M3 dis34 round-trip: FAIL: XCreateSimpleWindow argument order"
echo " expected (background,border,border_width,height,width,y,x,root,display):"
sed 's/^/ /' "$TMP/xcreate.want"
echo " got:"
sed 's/^/ /' "$TMP/xcreate.seq"
sed 's/^/ /' "$TMP/xcreate.vals"
} >&2
exit 1
fi
@@ -353,7 +340,7 @@ awk '
/^_xhello:/ { on = 1; next }
on && /-- End function/ { exit }
on && /^[[:space:]]*CALLA/ { pending = 1; next }
on && pending && /SETF[[:space:]]+16,[[:space:]]*0,[[:space:]]*0/ { saw16 = 1; next }
on && pending && /SETF[[:space:]]+16,[[:space:]]*1,[[:space:]]*0/ { saw16 = 1; next }
on && pending && saw16 && /SETF[[:space:]]+32,[[:space:]]*0,[[:space:]]*1/ {
n++; pending = 0; saw16 = 0; next
}
@@ -362,7 +349,7 @@ awk '
SETF_COUNT=$(cat "$TMP/setf_count")
[ "$SETF_COUNT" -eq 4 ] \
|| fail "found $SETF_COUNT post-call SETF 16/32 pairs in _xhello, want 4"
echo " ok four post-call SETF 16,0,0 + SETF 32,0,1 pairs"
echo " ok four post-call SETF 16,1,0 + SETF 32,0,1 pairs"
# _xhello takes no arguments of its own (the nine-argument call is inside it),
# so it returns with RETS 0; the argument-taking branch functions use RETS 2.
@@ -376,6 +363,9 @@ for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
done
echo "== check the branch code"
# A compiled local branch uses the one-word relative JR/JR<cc> form when the
# displacement fits; far or zero-displacement branches keep JAUC/JA<cc>. The
# condition code must survive either encoding.
for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
addr=${pair%%:*}
label=${pair##*:}
@@ -384,11 +374,11 @@ for pair in "$SUMTO:_sumto" "$MAX2:_max2" "$LT:_lt"; do
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no CMP"
fi
if ! grep -Eiq '\bjauc\b' "$TMP/fn.txt"; then
if ! grep -Eiq '\bj[ra](uc|eq|ne|lt|le|gt|ge|lo|ls|hi|hs|p|n|v|nv|nn)\b' "$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$label has no JAUC"
fail "$label has no branch"
fi
echo " ok $label: CMP + JAUC"
echo " ok $label: CMP + branch"
done
for pair in "$XHELLO:_xhello"; do
addr=${pair%%:*}
@@ -406,14 +396,32 @@ for callee in _sumto _max2 _lt _layout_screens _layout_root; do
|| fail "_branch_test does not call $callee"
done
echo " ok _branch_test calls sumto, max2, lt, layout_screens, layout_root"
# Conditional branch opcodes emitted by this compiled image. JALE/JALO/JAHI
# coverage lives in the m3-loop/m3-unsigned/m3-cmpi lit tests; this image has
# the signed compare, loop-exit and smax branches.
for op in jalt jagt jaeq; do
grep -Eiq "^[0-9a-f]+:[[:space:]]+$op([[:space:]]|;|$)" "$TMP/dis34.txt" \
|| fail "no $op instruction in the linked .text"
echo " ok $op present"
done
# Conditional branch conditions, pinned per function: _sumto has the loop exit
# (signed LT) and the result check (EQ), _max2 is smax (GT) and _lt is signed
# LT. JALE/JALO/JAHI coverage lives in the m3-loop/m3-unsigned/m3-cmpi lit
# tests. The condition code must survive whichever encoding the relaxation
# selected.
pin_cond() {
_addr=$1
_label=$2
_cc=$3
func_body "$_addr" > "$TMP/fn.txt"
if ! grep -Eiq "^[0-9a-f]+:[[:space:]]+j[ra]${_cc}([[:space:]]|;|$)" \
"$TMP/fn.txt"; then
sed 's/^/ /' "$TMP/fn.txt" >&2
fail "$_label has no J*${_cc} branch"
fi
echo " ok $_label: J*${_cc} branch"
}
pin_cond "$SUMTO" _sumto lt
pin_cond "$SUMTO" _sumto eq
pin_cond "$MAX2" _max2 gt
pin_cond "$LT" _lt lt
# At least one branch must have taken the one-word relative form; otherwise the
# relaxation silently did nothing and the code-size claim is meaningless.
grep -Eqio "^[0-9a-f]+:[[:space:]]+jr(uc|eq|ne|lt|le|gt|ge|lo|ls|hi|hs|p|n|v|nv|nn)([[:space:]]|;|$)" \
"$TMP/dis34.txt" || fail "no JR branch in the linked .text"
echo " ok JR relative branches present"
# GSPA rejects dotted .L labels; the harness gives each TU an LBB prefix.
grep -q 'LBB' "$ASM" || fail "linked assembly has no LBB block labels"
@@ -428,8 +436,15 @@ check_stk() {
_addr=$2
func_body "$_addr" > "$TMP/func.txt"
_pushes=$(awk '
tolower($0) ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
tolower($0) ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
{ low = tolower($0) }
low ~ /move[[:space:]]+[a-z0-9]+,[[:space:]]*-\*sp,[[:space:]]*1/ { n++ }
low ~ /mmtm[[:space:]]+sp,/ {
line = low
sub(/^.*mmtm[[:space:]]+sp,[[:space:]]*/, "", line)
sub(/[[:space:]]*;.*$/, "", line)
n += split(line, regs, ",")
}
low ~ /move[[:space:]]+a14,[[:space:]]*a13/ { print n; exit }
' "$TMP/func.txt")
[ -n "$_pushes" ] || fail "$_label has no SETFP (MOVE A14,A13)"
_operand=$(grep -Eio '\*sp\(0x[0-9a-f]+\)' "$TMP/func.txt" | head -1 \
@@ -438,8 +453,8 @@ check_stk() {
_want=$(( (_pushes + 1) * 32 ))
_got=$((0x$_operand))
[ "$_got" -eq "$_want" ] \
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes pushes need $_want bits"
echo " ok $_label: $_pushes pushes -> *SP($(printf '0x%x' "$_want")), A14, 1"
|| fail "$_label restores A14 from *SP(0x$_operand) ($_got bits) but $_pushes saved slots need $_want bits"
echo " ok $_label: $_pushes saved slots -> *SP($(printf '0x%x' "$_want")), A14, 1"
}
check_stk "_sumto" "$SUMTO"
check_stk "_max2" "$MAX2"
+1 -1
View File
@@ -14,7 +14,7 @@
.text
.globl _start
_start:
setf 16, 0, 0
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
+19 -15
View File
@@ -18,11 +18,14 @@
# 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
# Overridable: TMS_CLANG TMS_LLC MAME DOSBOX DOSBOX_CONF
# SDK_IMG M3_WORK M3_COFF M3_SDK LOADER_AT LOADER_END
set -eu
@@ -31,8 +34,6 @@ 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}
@@ -56,7 +57,7 @@ fail() {
exit 1
}
for tool in "$TMS_CLANG" "$TMS_OPT" "$TMS_BITADDR" "$TMS_LLC"; do
for tool in "$TMS_CLANG" "$TMS_LLC"; do
[ -x "$tool" ] || fail "missing tool: $tool"
done
@@ -65,19 +66,22 @@ 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"
# then dies selecting umul_lohi. The TMS34010 ToolChain passes
# -mllvm -replexitval=never, so the ordinary tms-clang -O2 pipeline keeps the
# loop (the point of the M3 branch test) with no local opt wrapper.
echo "== compile and select"
export TMS_CLANG TMS_BITADDR
export TMS_CLANG
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"
# branch.c needs -fno-inline: at -O2 clang inlines sumto/max2/lt into
# branch_test and constant-folds sumto(10), so the disassembler round-trip
# would have no _sumto/_max2/_lt calls to check. -O0 would stop the inlining
# too, but it also changes the branch condition codes the round-trip pins
# (sumto LT/EQ, max2 GT); -fno-inline keeps the -O2 shapes and just leaves
# the calls in place.
extra=
[ "$name" = branch ] && extra=-fno-inline
TMS_CLANG_EXTRA_FLAGS=$extra "$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"
+7 -3
View File
@@ -3,8 +3,12 @@
# 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 is the
# evidence that these entries work. M4 extends the table for XImage/XEvent.
# 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]
#
@@ -55,7 +59,7 @@ check_sym() { # check_sym NAME EXPECTED_HEX
check_sym XOpenDisplay 0x3F9C2570
check_sym XCreateSimpleWindow 0x3FD41B90
check_sym XMapWindow 0x3FD645B0
check_sym XMapWindow 0x3FD64F60
check_sym XSync 0x3FD9F6B0
echo "m3 validate-syms: PASS (four v2.2 Xlib entries in ROM, aligned, prologues valid)"
+5
View File
@@ -1,5 +1,10 @@
#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) {
+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
+489
View File
@@ -0,0 +1,489 @@
#!/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 and any M4_NATIVE_LIBS/M4_NATIVE_RTS
# archives with tools/tms-link instead of GSPLNK
# (default: gsplnk, which remains the oracle).
# Requires M4_NATIVE=1.
# M4_OS2=1 assemble/link with the 1990 r5.01 OS/2 tools
# under 2ine+qemu-i386 instead of DOSBox (run
# scripts/m8/setup-os2.sh first; the 1987
# GSPA/GSPLNK oracle is still the default)
# M4_OS2_LX=/path ../../2ine-tms34010/build-qemu/lx_loader
# M4_OS2_SDK=/path extracted r5.01 tree (bin/ and lib/)
# 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}
OS2=${M4_OS2:-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"
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"
}
# Optional host-side 1990 OS/2 r5.01 assembler/linker path (2ine + qemu-i386).
if [ "$OS2" = 1 ]; then
. "$ROOT/scripts/m8/os2-toolchain.sh"
os2_init
fi
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
# Resolve the library names to SDK paths for tms-link. GSPLNK keeps
# consuming the -l lines in M4.CMD; the order is identical.
NATIVE_LIB_PATHS=
for lib in $NATIVE_LIBS; do
dos=$(printf '%s' "$lib" | tr '[:lower:]' '[:upper:]')
if [ -f "$lib" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $lib"
elif [ -f "$SDK/$dos" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$dos"
elif [ -f "$SDK/$lib" ]; then
NATIVE_LIB_PATHS="$NATIVE_LIB_PATHS $SDK/$lib"
else
fail "$lib not extracted into $SDK"
fi
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 [ "$OS2" = 1 ]; then
os2_gspa M4
if [ -f "$SDK/M4EXT.ASM" ]; then
os2_gspa M4EXT
fi
# tms-link is a host tool and runs below; the asm/GSPLNK path links here.
if [ "$NATIVE" != 1 ] || [ "$LINKER" != tms-link ]; then
os2_gsplnk
fi
elif [ "$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 $NATIVE_LIB_PATHS \
|| fail "tms-link failed"
# Keep the pre-coff-check image so parity gates can compare tms-link's
# raw output; the repaired $COFF below remains the loader image.
cp "$SDK/M4.OUT" "$WORK/M4.RAW.OUT"
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" | tr 'a-f' 'A-F')
[ "$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|M8 LIB): ' "$WORK/mame.log" | tail -1 || true)
[ -n "$MARKERS" ] || { tail -30 "$WORK/mame.log" >&2; fail "MAME produced no M4/M7/M8 LIB 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|^M8 LIB MAME: PASS' "$WORK/mame.log" \
|| { tail -30 "$WORK/mame.log" >&2; fail "marker check failed"; }
case "$MARKERS" in
M7:*) echo "M7 MAME: PASS" ;;
M8\ LIB:*) echo "M8 LIB 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
}
+91
View File
@@ -0,0 +1,91 @@
#!/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.
#
# M5_NATIVE_LINKER=tms-link runs the same native builds through tools/tms-link
# (the termtris run also exercises the rts.lib archive path); the default is
# GSPLNK, which remains the oracle.
#
# Overridable: TMS_CLANG TMS_OPT TMS_BITADDR TMS_LLC LLVM_BIN M5_NATIVE_LINKER
# 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}
LINKER=${M5_NATIVE_LINKER:-gsplnk}
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_LINKER="$LINKER" \
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_LINKER="$LINKER" \
M4_SKIP_MAME=1 \
M4_SOURCES="$SRC/vt1200/main.c $SRC/game.c $SRC/vt1200/scoredb.c $SRC/vt1200/x11.c $SRC/vt1200/compat.c $SRC/vt1200/xgfix.c" \
M4_EXTRA_INCLUDES="-I $SRC -I $SRC/vt1200 -I $TERMTRIS_DIR/include" \
M4_ENTRY="$SRC/vt1200/entry.asm" \
M4_EXTRA_ASM="$SRC/vt1200/cinit.asm" \
M4_CLANG_OPT=-O2 \
M4_LLC_OPT=-O0 \
M4_NATIVE_RTS=1 \
M4_NATIVE_PROG_LEN=40000h \
M4_NATIVE_RAM_LEN=40000h \
M4_WORK="$WORK" \
M4_COFF="$WORK/termtris.coff" \
M4_SDK="${TERMTRIS_SDK:-$WORK/sdk}" \
"$DIR/run.sh"
# play_keys.sh reads the linker map by name; run.sh writes m4.map.
cp "$WORK/m4.map" "$WORK/termtris.map"
;;
*)
fail "unknown mode '$MODE' (want xshow or termtris)"
;;
esac
+6
View File
@@ -0,0 +1,6 @@
/* Long private name, TU a: identical in private-long-b.c so the old naming
* scheme would truncate the 8-hex module token at GSPA's 31-character limit
* and emit the same label in both translation units. */
static const char this_is_a_very_long_private_name[] = "same";
char *a(void) { return (char *)this_is_a_very_long_private_name; }
+6
View File
@@ -0,0 +1,6 @@
/* Long private name, TU b: deliberately identical to private-long-a.c. The
* capped base plus the name hash and module token must keep the two labels
* distinct within GSPA's 31-character identifier limit. */
static const char this_is_a_very_long_private_name[] = "same";
char *b(void) { return (char *)this_is_a_very_long_private_name; }
+85
View File
@@ -0,0 +1,85 @@
/*
* abi-oracle.c -- the 1987 TI C compiler ABI oracle for M6 task 1.
*
* The 1987 GSP C compiler is on the 1987-11-06 "Simulator-C Tools-ASM Tools"
* image (::/C2). Run it under DOSBox with the module name (no extension):
*
* gspcpp oracle.c
* gspcc oracle.c
* gspcg oracle.c
*
* ORACLE.ASM then shows the exact stack sequences reproduced in
* build/llvm-clean/TMS34010.md ("M6 state"):
* - _dadd/_dcall: GSP double argument order and the caller-allocated
* hidden return slot (the callee writes saved_STK-64/saved_STK-32);
* - _fadd: a float return uses the single word at saved_STK-32 (the K&R
* compiler promotes the parameters, so it calls FD$ADD + FD$DTOF);
* - _mkpair/_callpair: a 64-bit struct return uses the same hidden slot
* and the caller releases it with ADDI -64,STK;
* - _d2i/_i2d: the FD$DTOI/FD$ITOD conversion entries.
*
* The 1987 compiler is K&R-only; long long did not exist, so i64 has no
* external oracle. M6 i64 memory is little-endian (LSW at the lower
* address, per spec §4.1); the argument/hidden-slot order is MSW-first and
* is documented
* in TMS34010.md and pinned by scripts/m6/spike-probe.asm.
*/
double dadd(a, b)
double a;
double b;
{
return a + b;
}
double dcall(a, b)
double a;
double b;
{
double r;
r = dadd(a, b);
return r;
}
long d2i(a)
double a;
{
return (long)a;
}
double i2d(a)
long a;
{
return (double)a;
}
float fadd(a, b)
float a;
float b;
{
return a + b;
}
struct pair {
long a;
long b;
};
struct pair mkpair(a, b)
long a;
long b;
{
struct pair p;
p.a = a;
p.b = b;
return p;
}
long callpair(a, b)
long a;
long b;
{
struct pair p;
p = mkpair(a, b);
return p.a + p.b;
}
+91
View File
@@ -0,0 +1,91 @@
-- aggregate-check.lua -- read the M6 aggregate marker words and compare them
-- with the expected ABI/layout values.
--
-- AGGREGATE_MARKERS is the bit address of _aggregate_markers from the linker
-- map. Each marker is one 32-bit word at base + n*0x20 bits. The raw-object
-- markers pin the byte layout (little-endian, fields in ascending order) and
-- the guards prove an aggregate copy does not overrun the object.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("AGGREGATE_MARKERS"), 16)
local N = 49
local frames = 0
local checked = false
local expect = {
[0] = 0x11223344, [1] = 0x00005566, -- mk_six fields
[2] = 0x11223344, [3] = 0x00005566, -- raw six object word/half
[4] = 0x600D600D, -- guard after a 6-byte copy
[5] = 0xAABBCCDD, [6] = 0x0000005A, -- mk_five fields (5-byte object)
[7] = 0xAABBCCDD, [8] = 0x0000005A, -- raw five object word/byte
[9] = 0x000000A5, -- guard after a 5-byte copy
[10] = 0x00000010, [11] = 0x00000011, -- mk_big fields
[12] = 0x00000012, [13] = 0x00000013,
[14] = 0x00000014,
[15] = 0x00000010, [16] = 0x00000011, -- raw big object words
[17] = 0x00000012, [18] = 0x00000013,
[19] = 0x00000014,
[20] = 0xAAAA5555, [21] = 0x12345678, -- mk_pair (the 1987 _mkpair)
[22] = 0x00000100, [23] = 0x00000009, -- mk_outer nested fields
[24] = 0x00000003,
[25] = 0xDEADBEEF, [26] = 0xDEADBEEF, -- mk_uni field and raw word
[27] = 0x3366EF96, -- sum_six(six, 100)
[28] = 0x00000024, -- sum_big(big)
[29] = 0x12345678, -- sum_uni(uni)
[30] = 0x000000CF, -- c_usesix(50)
[31] = 0x00000018, -- c_usebig(10)
[32] = 0x00000405, -- c_useouter(0x200)
[33] = 0x0BADF00D, -- c_useuni(...)
[34] = 0x0000000B, -- c_sumpair({5,6})
[35] = 0x00000030, -- c_sumsix({0x10,0x20})
[36] = 0x112233C2, -- c_sumuni(l + c[5])
[37] = 0x000000D2, -- c_usemixed(100)
[38] = 0x00000064, -- mixed raw a
[39] = 0x00000064, -- mixed raw i64 LSW (little-endian)
[40] = 0x00000000, -- mixed raw i64 MSW
[41] = 0x00000000, -- mixed raw double LSW (GSP 1.5)
[42] = 0x400C0000, -- mixed raw double MSW
[43] = 0x40D00000, -- mixed raw float (GSP 2.5)
[44] = 0x00000007, -- mixed raw char
[45] = 0x000B1405, -- c_mkbits fields a=5 b=20 c=-5
[46] = 0xFFFFFFFB, -- signed int c:4 sign-extends
[47] = 0x00000BA5, -- raw packed bitfield word
[48] = 0x5A5A5A5A, -- marker after aggregate_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 aggregate:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 AGGREGATE MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 aggregate: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 AGGREGATE MAME: FAIL")
end
end
end, "aggregate-check")
+28
View File
@@ -0,0 +1,28 @@
; aggregate-entry.asm -- M6 aggregate gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver aggregate_run() and writes a post-return marker. aggregate.sh
; concatenates the llc output for m6-aggregate.ll and the compiled driver
; after this file, so _aggregate_run and the aggregate functions are in the
; same assembly.
;
; The marker array is in .bss (linked at the ram origin); aggregate-check.lua
; reads its address from the linker map and checks 49 words (markers 0..48,
; the last one written after aggregate_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _aggregate_run
movi 5A5A5A5Ah, a0
movi _aggregate_markers+1536, a2 ; marker 48, the post-return word
move a0, *a2, 1
rets
.globl _aggregate_markers
.bss _aggregate_markers, 1568, 16 ; 49 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+351
View File
@@ -0,0 +1,351 @@
/* M6 aggregate gate driver.
*
* Calls the hand-written ABI functions in m6-aggregate.ll through the TI
* aggregate rules and writes result words to the marker array defined by the
* entry assembly. The .ll callees are *not* compiled by Clang, so the driver
* pins the caller side against independently written lowering; the C
* functions below then exercise the compiler's own callee side (and its
* caller side calling itself).
*
* The ABI under test (1987 `_mkbig`/`_callbig`):
* - the caller reserves an alignTo(size, 2)-byte slot at the top of its
* frame before saving STK, pushes the arguments, calls;
* - the callee copies the object bytes to saved_STK-size (the object sits
* at the top of the rounded slot) and ends with LOADSTK + RETS 2;
* - the caller copies the bytes out and releases the slot;
* - struct/union arguments are still byval copies in the argument area;
* - no sret pointer argument and no A8 aggregate return.
*
* Marker word n lives at aggregate_markers[n], i.e. 0x20 bits above the
* previous one; scripts/m6/aggregate-check.lua reads them by bit address from
* the linker map.
*/
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef unsigned long long u64;
struct six {
int a;
short b;
};
struct five {
int a;
char b;
};
/* A packed bitfield struct returned by value: the Task 5 (bitfields) / Task 6
* (aggregate return) seam. The 12 field bits fit one 16-bit word, so the
* hidden slot is 2 bytes and the callee stores the packed bits directly. */
struct bits {
unsigned int a : 3;
unsigned int b : 5;
int c : 4;
};
struct big {
long a, b, c, d, e;
};
struct pair {
long a, b;
};
struct inner {
long a;
short b;
};
struct outer {
struct inner i;
long c;
};
union uni {
long l;
char c[6];
};
struct mixed {
long a;
long long b;
double d;
float f;
char c;
};
struct six_guard {
struct six s;
unsigned int guard;
};
struct five_guard {
struct five f;
unsigned char guard;
};
/* Layout contract: TI packs records, so a 5-byte object is possible and the
* 6-byte slot rounds it up by one byte. */
_Static_assert(sizeof(struct six) == 6, "six");
_Static_assert(__builtin_offsetof(struct six, b) == 4, "six.b");
_Static_assert(sizeof(struct bits) == 2, "bits");
_Static_assert(sizeof(struct five) == 5, "five");
_Static_assert(__builtin_offsetof(struct five, b) == 4, "five.b");
_Static_assert(sizeof(struct big) == 20, "big");
_Static_assert(sizeof(struct pair) == 8, "pair");
_Static_assert(sizeof(struct inner) == 6, "inner");
_Static_assert(sizeof(struct outer) == 10, "outer");
_Static_assert(__builtin_offsetof(struct outer, c) == 6, "outer.c");
_Static_assert(sizeof(union uni) == 6, "uni");
_Static_assert(sizeof(struct mixed) == 25, "mixed");
_Static_assert(__builtin_offsetof(struct mixed, b) == 4, "mixed.b");
_Static_assert(__builtin_offsetof(struct mixed, d) == 12, "mixed.d");
_Static_assert(__builtin_offsetof(struct mixed, f) == 20, "mixed.f");
_Static_assert(__builtin_offsetof(struct mixed, c) == 24, "mixed.c");
extern volatile u32 aggregate_markers[];
/* Callees defined in m6-aggregate.ll. */
extern struct six mk_six(int, int);
extern struct five mk_five(int, int);
extern struct big mk_big(int);
extern struct pair mk_pair(int, int);
extern struct outer mk_outer(int);
extern union uni mk_uni(int);
extern int sum_six(struct six, int);
extern int sum_big(struct big);
extern int sum_uni(union uni);
/* Keep raw object copies in .bss so the exact bytes can be inspected. */
static volatile struct six six_raw;
static volatile struct five five_raw;
static volatile struct big big_raw;
static volatile union uni uni_raw;
static volatile struct mixed mixed_raw;
static volatile struct six_guard six_guard_slot;
static volatile struct five_guard five_guard_slot;
static volatile struct bits bits_raw;
static void mark(u32 n, u32 v) { aggregate_markers[n] = v; }
/* --- C-side aggregate callees (the compiler's callee lowering) ----------- */
static __attribute__((noinline)) struct six c_mksix(int a, int b)
{
struct six s;
s.a = a;
s.b = (short)b;
return s;
}
static __attribute__((noinline)) int c_usesix(int x)
{
struct six s = c_mksix(x, 7);
return s.a * 3 + s.b + x;
}
/* The bitfield-struct return: fields come from x so the callee cannot fold
* the result, and the caller reads them back through the returned object.
* c uses the low bits only: a (x >> 8) & mask source would exercise an
* unrelated generic load-narrowing path on this bit-addressed target. */
static __attribute__((noinline)) struct bits c_mkbits(int x)
{
struct bits v;
v.a = x & 7;
v.b = (x >> 3) & 31;
v.c = -(x & 7);
return v;
}
static __attribute__((noinline)) struct big c_mkbig(int x)
{
struct big b;
b.a = x;
b.b = x + 1;
b.c = x + 2;
b.d = x + 3;
b.e = x + 4;
return b;
}
static __attribute__((noinline)) int c_usebig(int x)
{
struct big b = c_mkbig(x);
return b.a + b.e;
}
static __attribute__((noinline)) struct outer c_mkouter(int x)
{
struct outer o;
o.i.a = x;
o.i.b = 2;
o.c = x + 3;
return o;
}
static __attribute__((noinline)) int c_useouter(int x)
{
struct outer o = c_mkouter(x);
return o.i.a + o.i.b + o.c;
}
static __attribute__((noinline)) union uni c_mkuni(int x)
{
union uni u;
u.l = x;
return u;
}
static __attribute__((noinline)) int c_useuni(int x)
{
union uni u = c_mkuni(x);
return u.l;
}
static __attribute__((noinline)) struct mixed c_mkmixed(int x)
{
struct mixed m;
m.a = x;
m.b = x;
m.d = 1.5;
m.f = 2.5f;
m.c = 7;
return m;
}
static __attribute__((noinline)) int c_usemixed(int x)
{
struct mixed m = c_mkmixed(x);
return (long)m.a + (long)m.b + (long)m.d + (long)m.f + (long)m.c;
}
static __attribute__((noinline)) int c_sumpair(struct pair p) { return p.a + p.b; }
static __attribute__((noinline)) int c_sumsix(struct six s) { return s.a + s.b; }
static __attribute__((noinline)) int c_sumuni(union uni u) { return u.l + u.c[5]; }
void aggregate_run(void)
{
struct six s6;
struct five f5;
struct big b5;
struct pair p2;
struct outer o;
union uni u;
volatile u32 *w;
volatile u8 *pb;
/* The .ll 6-byte struct return and its raw memory image. */
s6 = mk_six(0x11223344, 0x5566);
mark(0, (u32)s6.a);
mark(1, (u16)s6.b);
six_raw = s6;
w = (volatile u32 *)&six_raw;
mark(2, w[0]);
pb = (volatile u8 *)&six_raw;
mark(3, pb[4] | ((u32)pb[5] << 8));
/* A 6-byte object must not overwrite the next object. */
six_guard_slot.guard = 0x600D600D;
six_guard_slot.s = mk_six(0x11223344, 0x5566);
mark(4, six_guard_slot.guard);
/* The 5-byte object in a 6-byte slot; the guard proves the copy is exact
* (the slot's pad byte is not written into the caller's object). */
f5 = mk_five(0xAABBCCDD, 0x5A);
mark(5, (u32)f5.a);
mark(6, (u8)f5.b);
five_raw = f5;
w = (volatile u32 *)&five_raw;
mark(7, w[0]);
pb = (volatile u8 *)&five_raw;
mark(8, pb[4]);
five_guard_slot.guard = 0xA5;
five_guard_slot.f = mk_five(0x01020304, 0x7E);
mark(9, five_guard_slot.guard);
/* The 5-word / 160-bit case. */
b5 = mk_big(0x10);
mark(10, (u32)b5.a);
mark(11, (u32)b5.b);
mark(12, (u32)b5.c);
mark(13, (u32)b5.d);
mark(14, (u32)b5.e);
big_raw = b5;
w = (volatile u32 *)&big_raw;
mark(15, w[0]);
mark(16, w[1]);
mark(17, w[2]);
mark(18, w[3]);
mark(19, w[4]);
/* The 2-word case (1987 `_mkpair`). */
p2 = mk_pair(0xAAAA5555, 0x12345678);
mark(20, (u32)p2.a);
mark(21, (u32)p2.b);
/* Nested struct: flattened fields at 0, 4 and 6. */
o = mk_outer(0x100);
mark(22, (u32)o.i.a);
mark(23, (u32)o.i.b);
mark(24, (u32)o.c);
/* Union return and its raw low word. */
u = mk_uni(0xDEADBEEF);
mark(25, (u32)u.l);
uni_raw = u;
w = (volatile u32 *)&uni_raw;
mark(26, w[0]);
/* Struct/union by value as arguments: the callee receives a private copy
* in the argument area (the driver is the caller here). */
mark(27, (u32)sum_six(s6, 100));
mark(28, (u32)sum_big(b5));
mark(29, (u32)sum_uni(mk_uni(0x12345678)));
/* C-defined callees (the compiler's own callee lowering), called from C. */
mark(30, (u32)c_usesix(50));
mark(31, (u32)c_usebig(10));
mark(32, (u32)c_useouter(0x200));
mark(33, (u32)c_useuni(0x0BADF00D));
p2.a = 5;
p2.b = 6;
mark(34, (u32)c_sumpair(p2));
s6.a = 0x10;
s6.b = 0x20;
mark(35, (u32)c_sumsix(s6));
u.l = 0x11223344;
u.c[5] = 0x7E;
mark(36, (u32)c_sumuni(u));
/* The aggregate can mix i64, double and float members. */
mark(37, (u32)c_usemixed(100));
mixed_raw = c_mkmixed(100);
w = (volatile u32 *)&mixed_raw;
mark(38, w[0]);
mark(39, w[1]);
mark(40, w[2]);
mark(41, w[3]);
mark(42, w[4]);
mark(43, w[5]);
pb = (volatile u8 *)&mixed_raw;
mark(44, pb[24]);
/* Packed bitfield struct returned by value (Task 5/6 seam): fields, the
* signed field and the raw packed word. c_mkbits(0x1A5) is a=5, b=20,
* c=-5 in one 16-bit word. */
{
struct bits v = c_mkbits(0x1A5);
volatile u8 *bb;
mark(45, (u32)v.a | ((u32)v.b << 8) |
((u32)(v.c & 0xF) << 16));
mark(46, (u32)v.c);
bits_raw = v;
bb = (volatile u8 *)&bits_raw;
mark(47, (u32)bb[0] | ((u32)bb[1] << 8));
}
}
+116
View File
@@ -0,0 +1,116 @@
-- bitfield-check.lua -- read the M6 bitfield marker words and compare them
-- with the oracle's expected values.
--
-- BITFIELD_MARKERS is the bit address of _bitfield_markers from the linker
-- map; each marker is one 32-bit word at base + n*0x20 bits. The struct
-- case is the Task 5 oracle: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32,
-- and the raw word0/byte4 markers pin the actual storage bytes, not just the
-- compiled read-back.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("BITFIELD_MARKERS"), 16)
local N = 62
local frames = 0
local checked = false
local expect = {
[0] = 5, -- struct s.a (bits 0..2)
[1] = 21, -- struct s.b (bits 3..7)
[2] = 0xFFFFFFFD, -- struct s.c = -3, signed 4-bit
[3] = 0x000ABCDE, -- struct s.d (bits 12..31)
[4] = 9, -- struct s.e (bits 32..35)
[5] = 0xABCDEDAD, -- raw word0 = a|b<<3|c<<8|d<<12
[6] = 0x09, -- raw byte4 low nibble = e
[7] = 7, -- c = +7
[8] = 0xFFFFFFF8, -- c = -8 (the 4-bit minimum)
[9] = 0x000FEDCB, -- cross.x
[10] = 0x00012345, -- cross.y at bit 20, crossing bit 32
[11] = 0x345FEDCB, -- raw word0: x | (y low 12) << 20
[12] = 0x12, -- raw byte4: y high 8 bits
[13] = 3, -- zw.a
[14] = 17, -- zw.b after the ignored :0 (bit 3)
[15] = 0x8B, -- raw byte = 3 | 17 << 3
[16] = 0xFFFFFFFF, -- one.s = -1 (signed 1-bit)
[17] = 1, -- one.u
[18] = 0x03, -- raw byte: s in bit 0, u in bit 1
[19] = 0, -- one.s = 0
[20] = 1, -- one.u = 1
[21] = 0x02, -- raw byte
[22] = 0xFFFFFFFF, -- one.s = -1
[23] = 0, -- one.u = 0
[24] = 0x01, -- raw byte
[25] = 0xDEADBEEF, -- word.w (full 32-bit field)
[26] = 1, -- word.v at bit 32
[27] = 0xDEADBEEF, -- raw word0
[28] = 0x01, -- raw byte4
[29] = 0x01234567, -- edge.p (28 bits)
[30] = 0xA5, -- edge.q at bit 28, crossing bit 32
[31] = 0x0C, -- edge.r at bit 36
[32] = 0x51234567, -- raw word0: p | (q low nibble) << 28
[33] = 0xCA, -- raw byte4: q high nibble | r << 4
[34] = 0xFFFFFFFD, -- sx.a = -3 (signed 3-bit)
[35] = 2, -- sx.b
[36] = 0xFFFFFF38, -- sx.c = -200 (signed 9-bit)
[37] = 0xFFFE0000, -- sx.d = -131072 (signed 18-bit)
[38] = 0x80002715, -- raw word0 of the packed signed fields
[39] = 0xFA0A1F00, -- sy.e = -100000000 (signed 30-bit)
[40] = 0xFFFFFFEC, -- sy.f = -20 (signed 6-bit, crosses bit 32)
[41] = 0x3A0A1F00, -- raw word0
[42] = 0x0B, -- raw byte4: f high nibble
[43] = 1, -- g2.a through a pointer
[44] = 30, -- g2.b
[45] = 0xFFFFFFFE, -- g2.c = -2
[46] = 0x00054321, -- g2.d
[47] = 15, -- g2.e
[48] = 0x54321EF1, -- g2 raw word0
[49] = 0x0F, -- g2 raw byte4
[50] = 6, -- lz.a (leading :0 ignored)
[51] = 9, -- lz.b at bit 3
[52] = 0x4E, -- raw byte = 6 | 9 << 3
[53] = 0x12345678, -- l64.f = 0x12345678 (bit 33)
[54] = 0x00000000, -- l64 raw word0 (pad)
[55] = 0x2468ACF0, -- l64 raw word1 (pad[32] | f<<1)
[56] = 0x89ABCDEF, -- q64.q low word
[57] = 0x89ABCDEF, -- q64 raw word0 (LSW)
[58] = 0x01234567, -- q64 raw word1 (MSW)
[59] = 0x12345678, -- copy_l64 read-back after an aggregate copy
[60] = 0x2468ACF0, -- copied l64 raw MSW
[61] = 0x5A5A5A5A, -- marker after bitfield_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 bitfield:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 BITFIELD MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 bitfield: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 BITFIELD MAME: FAIL")
end
end
end, "bitfield-check")
+27
View File
@@ -0,0 +1,27 @@
; bitfield-entry.asm -- M6 bitfield gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver bitfield_run() and writes a post-return marker. bitfield.sh
; concatenates the compiled driver after this file, so _bitfield_run and its
; helpers are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); bitfield-check.lua
; reads its address from the linker map and checks 62 words (markers 0..61,
; the last one written after bitfield_run returns). Marker n is 0x20 bits
; above marker n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _bitfield_run
movi 5A5A5A5Ah, a0
movi _bitfield_markers+1952, a2 ; marker 61, the post-return word
move a0, *a2, 1
rets
.globl _bitfield_markers
.bss _bitfield_markers, 2048, 16 ; 62 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+255
View File
@@ -0,0 +1,255 @@
/* M6 bitfield gate driver.
*
* Every struct below is the 1987 GSP C compiler's packed bitfield layout:
* bitfields are allocated LSB-first at the next free bit, with no padding
* between adjacent fields and across the 32-bit word boundary; an unnamed
* `:0` bitfield is ignored (the oracle's `b` after `a:3; :0` is at bit 3).
* Clang's record layout for the target must agree; the _Static_asserts check
* the byte-expressible part (sizeof/alignof) and the runtime markers check
* the bit offsets by setting each field to a known value, reading it back and
* checking the raw storage bytes.
*
* The structs are volatile so the accesses survive -O2; the marker array is
* volatile too. Marker word n lives at bitfield_markers[n], i.e. 0x20 bits
* above the previous one; scripts/m6/bitfield-check.lua reads them from the
* linker map.
*
* Raw storage is read little-endian (the target's data layout is `e`): byte 0
* holds struct bits 0..7. The 1987 oracle's `g` is `.bss _g,36,16`, and the
* object allocator rounds that to 48 bits; the M6 .bss emitter rounds every
* object to a 16-bit unit, so a standalone object matches. Arrays, nested
* members and pointer arithmetic on a struct whose content is not a whole
* byte are the documented divergence:
* TI strides by the 36-bit content, Clang by the byte-rounded 5-byte sizeof.
*/
typedef unsigned int u32;
/* The oracle struct from the Task 5 notes (BITS.C). */
struct s {
unsigned a:3;
unsigned b:5;
int c:4;
unsigned d:20;
unsigned e:4;
};
struct cross { unsigned x:20; unsigned y:20; };
struct zw { unsigned a:3; unsigned :0; unsigned b:5; };
struct one { int s:1; unsigned u:1; };
struct word { unsigned w:32; unsigned v:1; };
struct edge { unsigned p:28; unsigned q:8; unsigned r:4; };
struct sx { int a:3; unsigned b:2; int c:9; int d:18; };
struct sy { int e:30; int f:6; };
struct lz { unsigned :0; unsigned a:3; unsigned b:5; };
/* A 31-bit field at bit 33 needs an i64 container (LSB-first). */
struct l64 { unsigned long long pad:33; unsigned f:31; };
struct q64 { unsigned long long q:57; };
volatile struct s g;
volatile struct s g2;
volatile struct cross cg;
volatile struct zw zg;
volatile struct one og;
volatile struct word wg;
volatile struct edge eg;
volatile struct sx sx;
volatile struct sy sy;
volatile struct lz lz;
volatile struct l64 l64g;
volatile struct l64 l64h;
volatile struct q64 q64g;
extern volatile u32 bitfield_markers[];
/* The oracle's sizeof values: 36 bits -> 5 bytes, 40 -> 5, 8 -> 1, 2 -> 1,
* 33 -> 5. TI reports the byte-rounded size; Clang must agree. */
_Static_assert(sizeof(struct s) == 5, "oracle sizeof(struct s)");
_Static_assert(sizeof(struct cross) == 5, "cross is a whole 40-bit word pair");
_Static_assert(sizeof(struct zw) == 1, "the :0 is ignored; a+b is 8 bits");
_Static_assert(sizeof(struct one) == 1, "two 1-bit fields fit one byte");
_Static_assert(sizeof(struct word) == 5, "32+1 bits round to 5 bytes");
_Static_assert(sizeof(struct edge) == 5, "28+8+4 bits = 40");
_Static_assert(sizeof(struct sx) == 4, "3+2+9+18 bits = 32");
_Static_assert(sizeof(struct sy) == 5, "30+6 bits = 36, rounded to 5 bytes");
_Static_assert(sizeof(struct lz) == 1, "leading :0 is ignored");
_Static_assert(sizeof(struct l64) == 8, "33+31 bits = 64");
_Static_assert(sizeof(struct q64) == 8, "57 bits round to 8 bytes");
_Static_assert(_Alignof(struct s) == 1, "packed record alignment is 1 byte");
static u32 raw_byte(volatile void *p, int i)
{
return ((volatile unsigned char *)p)[i];
}
static u32 raw_word0(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[0] | ((u32)b[1] << 8) | ((u32)b[2] << 16) |
((u32)b[3] << 24);
}
static u32 raw_word1(volatile void *p)
{
volatile unsigned char *b = (volatile unsigned char *)p;
return (u32)b[4] | ((u32)b[5] << 8) | ((u32)b[6] << 16) |
((u32)b[7] << 24);
}
static void set_l64(unsigned f) { l64g.f = f; }
static unsigned get_l64(void) { return l64g.f; }
static void set_q64(unsigned long long q) { q64g.q = q; }
static unsigned long long get_q64(void) { return q64g.q; }
/* An aggregate copy: at -O2 the optimizer may forward the i64 copy
* into the field read, so the memory order must match the IR. */
static unsigned copy_l64(struct l64 *dst, struct l64 *src)
{
*dst = *src;
return dst->f;
}
void bitfield_run(void)
{
volatile struct s *gp = &g2;
/* The oracle struct: a:3@0, b:5@3, c:4@8 (signed), d:20@12, e:4@32.
* Expected bytes: AD ED CD AB 09 (word0 ABCDEDADh, then e in byte 4). */
g.a = 5;
g.b = 21;
g.c = -3;
g.d = 0xABCDE;
g.e = 9;
bitfield_markers[0] = g.a;
bitfield_markers[1] = g.b;
bitfield_markers[2] = (u32)g.c;
bitfield_markers[3] = g.d;
bitfield_markers[4] = g.e;
bitfield_markers[5] = raw_word0((volatile void *)&g);
bitfield_markers[6] = raw_byte((volatile void *)&g, 4);
/* Signed nibble boundaries: +7 and the minimum -8 must sign-extend. */
g.c = 7;
bitfield_markers[7] = (u32)g.c;
g.c = -8;
bitfield_markers[8] = (u32)g.c;
/* struct cross: y:20 at bit 20 crosses bit 32.
* word0 345FEDCBh, byte4 12h. */
cg.x = 0xFEDCB;
cg.y = 0x12345;
bitfield_markers[9] = cg.x;
bitfield_markers[10] = cg.y;
bitfield_markers[11] = raw_word0((volatile void *)&cg);
bitfield_markers[12] = raw_byte((volatile void *)&cg, 4);
/* struct zw: a:3, unnamed :0 ignored, b:5 at bit 3.
* byte 8Bh (a=3 in bits 0..2, b=17 in bits 3..7). */
zg.a = 3;
zg.b = 17;
bitfield_markers[13] = zg.a;
bitfield_markers[14] = zg.b;
bitfield_markers[15] = raw_byte((volatile void *)&zg, 0);
/* struct one: the signed 1-bit field is the SEXT1 case (SLL 31/SRA 31).
* A 1-bit signed field holds 0 or -1: s=-1,u=1 -> byte 3; s=0,u=1 ->
* byte 2; s=-1,u=0 -> byte 1. */
og.s = -1;
og.u = 1;
bitfield_markers[16] = (u32)og.s;
bitfield_markers[17] = og.u;
bitfield_markers[18] = raw_byte((volatile void *)&og, 0);
og.s = 0;
og.u = 1;
bitfield_markers[19] = (u32)og.s;
bitfield_markers[20] = og.u;
bitfield_markers[21] = raw_byte((volatile void *)&og, 0);
og.s = -1;
og.u = 0;
bitfield_markers[22] = (u32)og.s;
bitfield_markers[23] = og.u;
bitfield_markers[24] = raw_byte((volatile void *)&og, 0);
/* struct word: w:32 at bit 0 (a full-word field) and v:1 at bit 32. */
wg.w = 0xDEADBEEF;
wg.v = 1;
bitfield_markers[25] = wg.w;
bitfield_markers[26] = wg.v;
bitfield_markers[27] = raw_word0((volatile void *)&wg);
bitfield_markers[28] = raw_byte((volatile void *)&wg, 4);
/* struct edge: q:8 at bit 28 crosses bit 32 (low nibble in word0 bits
* 28..31, high nibble in byte4 bits 0..3); r:4 at bit 36.
* word0 51234567h, byte4 CAh. */
eg.p = 0x1234567;
eg.q = 0xA5;
eg.r = 0xC;
bitfield_markers[29] = eg.p;
bitfield_markers[30] = eg.q;
bitfield_markers[31] = eg.r;
bitfield_markers[32] = raw_word0((volatile void *)&eg);
bitfield_markers[33] = raw_byte((volatile void *)&eg, 4);
/* Signed fields at odd offsets inside one 32-bit word:
* a:3@0, b:2@3, c:9@5, d:18@14; word0 80002715h. */
sx.a = -3;
sx.b = 2;
sx.c = -200;
sx.d = -131072;
bitfield_markers[34] = (u32)sx.a;
bitfield_markers[35] = sx.b;
bitfield_markers[36] = (u32)sx.c;
bitfield_markers[37] = (u32)sx.d;
bitfield_markers[38] = raw_word0((volatile void *)&sx);
/* A signed field crossing the word boundary: e:30@0, f:6@30.
* e=-100000000 (-100000000 & 3FFFFFFF = 3A0A1F00h), f=-20 (2Ch: low
* two bits 0 in word0 bits 30..31, high nibble Bh in byte4 bits 0..3). */
sy.e = -100000000;
sy.f = -20;
bitfield_markers[39] = (u32)sy.e;
bitfield_markers[40] = (u32)sy.f;
bitfield_markers[41] = raw_word0((volatile void *)&sy);
bitfield_markers[42] = raw_byte((volatile void *)&sy, 4);
/* The same oracle struct through a pointer, so the access path is a
* GEP/load/store rather than a fixed global address.
* word0 54321EF1h, byte4 0Fh. */
gp->a = 1;
gp->b = 30;
gp->c = -2;
gp->d = 0x54321;
gp->e = 15;
bitfield_markers[43] = gp->a;
bitfield_markers[44] = gp->b;
bitfield_markers[45] = (u32)gp->c;
bitfield_markers[46] = gp->d;
bitfield_markers[47] = gp->e;
bitfield_markers[48] = raw_word0((volatile void *)&g2);
bitfield_markers[49] = raw_byte((volatile void *)&g2, 4);
/* A leading unnamed :0 is ignored too: a:3@0, b:5@3, byte 4Eh. */
lz.a = 6;
lz.b = 9;
bitfield_markers[50] = lz.a;
bitfield_markers[51] = lz.b;
bitfield_markers[52] = raw_byte((volatile void *)&lz, 0);
/* 64-bit containers: LSW at the lower address. f@33, 31 bits;
* raw word0 = pad[0..31], raw word1 = pad[32] | f << 1. */
set_l64(0x12345678u);
bitfield_markers[53] = get_l64();
bitfield_markers[54] = raw_word0((volatile void *)&l64g);
bitfield_markers[55] = raw_word1((volatile void *)&l64g);
/* 57-bit field: LSW = q[0..31], MSW = q[32..56]. */
set_q64(0x0123456789ABCDEFull);
bitfield_markers[56] = (u32)get_q64();
bitfield_markers[57] = raw_word0((volatile void *)&q64g);
bitfield_markers[58] = raw_word1((volatile void *)&q64g);
/* Aggregate copy: GVN may forward the i64 copy into the field read at
* -O2, so the memory order must match the IR. (A constant-initialized
* i64 aggregate still hits the pre-existing M2 .data limitation at -O0.) */
bitfield_markers[59] = copy_l64(&l64h, &l64g);
bitfield_markers[60] = raw_word1((volatile void *)&l64h);
}
+183
View File
@@ -0,0 +1,183 @@
#!/bin/sh
# Extract and validate the 1990-11 TMS340 Family SDK floating-point/runtime
# libraries for the M6 ABI work.
#
# scripts/m6/flib-extract.sh
#
# The 1990 r5.01 Code Generation Tools are OS/2 1.x NE binaries and do not run
# under DOSBox, but their TI-COFF libraries are ordinary ar archives. The 1987
# GSPA 2.00/GSPLNK 2.00 tools assemble and link them unchanged, `$` symbols
# included.
#
# Outputs (all under build/m6-sdk, which is git-ignored):
# flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src
# flib-members/ rts-members/ extracted archive members
# flib-symbols.txt exact external definitions
#
# Overridable: M6_SDK_OUT
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
OUT=${M6_SDK_OUT:-$ROOT/build/m6-sdk}
ZIPDIR="$ROOT/vendor/vt1200/tools/tms34010-sdk/1990-11 TMS340 Family SDK"
ZIP1="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (1 of 2) r5.01 rev2564062-1641.zip"
ZIP2="$ZIPDIR/1990-11-19 TMS340 Family Code Generation Tools (2 of 2) r5.01 rev2564062-1641.zip"
fail() {
echo "m6 flib-extract: FAIL: $*" >&2
exit 1
}
command -v unzip >/dev/null 2>&1 || fail "unzip is required"
command -v ar >/dev/null 2>&1 || fail "ar is required"
mkdir -p "$OUT"
if [ ! -f "$OUT/flib.lib" ] || [ ! -f "$OUT/rts.lib" ]; then
[ -f "$ZIP2" ] || fail "1990 SDK archive not found: $ZIP2"
unzip -o -q "$ZIP2" -d "$OUT"
# The tool archives are not needed to link (the 1987 tools are used), but
# extracting them records the exact 1990 release the libraries came from.
if [ -f "$ZIP1" ]; then
unzip -o -q "$ZIP1" -d "$OUT"
fi
fi
for f in flib.lib flibc.lib flibi.lib rts.lib flib.src rts.src; do
[ -f "$OUT/$f" ] || fail "missing $OUT/$f after extraction"
done
extract_members() {
lib=$1
dir=$OUT/$2
rm -rf "$dir"
mkdir -p "$dir"
(cd "$dir" && ar x "$OUT/$lib")
chmod -R u+rw "$dir"
}
extract_members flib.lib flib-members
extract_members flibc.lib flibc-members
extract_members flibi.lib flibi-members
extract_members rts.lib rts-members
python3 - "$ROOT" "$OUT" <<'PY'
import os
import struct
import sys
root, out = sys.argv[1], sys.argv[2]
sys.path.insert(0, os.path.join(root, "vendor", "vt1200", "dwt", "loader"))
import coff
def symname(c, sym):
"""Return a TI-COFF symbol name, resolving the long-name string table."""
d = c["data"]
raw = d[c["symptr"] + sym["index"] * 18:][:8]
if raw[:4] == b"\0\0\0\0":
off = struct.unpack_from("<I", raw, 4)[0]
base = c["symptr"] + c["nsyms"] * 18
end = d.index(b"\0", base + off)
return d[base + off:end].decode("latin1")
return raw.rstrip(b"\0").decode("latin1")
lines = [
"# 1990-11 TMS340 Family SDK r5.01 external symbol definitions",
"# generated by scripts/m6/flib-extract.sh; do not edit",
"#",
"# flib.lib is the GSP-format floating-point library used by the TI C",
"# compiler by default. flibc.lib/flibi.lib are identified as the",
"# 34082/IEEE variants from member-code inspection (see the variant",
"# section at the end); the 1990 compiler was not run. M6 links flib.lib.",
"",
]
for lib, members in (("flib.lib", "flib-members"), ("rts.lib", "rts-members")):
lines.append("== %s" % lib)
d = os.path.join(out, members)
for fn in sorted(os.listdir(d)):
c = coff.parse(os.path.join(d, fn))
ext = [symname(c, s) for s in c["symbols"]
if s["sclass"] == 2 and s["secno"] > 0]
if ext:
lines.append("%-14s %s" % (fn, " ".join(ext)))
lines.append("")
def text_bits(c):
for s in c["sections"]:
if s["name"] == ".text":
return s["size"]
return 0
lines.append("== variant inspection (not linked by M6)")
for lib, members in (("flib.lib", "flib-members"),
("flibc.lib", "flibc-members"),
("flibi.lib", "flibi-members")):
parts = []
for fn in ("fs_add.obj", "fd_add.obj"):
c = coff.parse(os.path.join(out, members, fn))
parts.append("%s .text %d bits" % (fn, text_bits(c)))
lines.append("%-11s %s" % (lib, "; ".join(parts)))
lines.extend([
"# flibc/flibi are identified as the 34082/IEEE variants from member-code",
"# inspection (their members begin with the 34082 path and are larger) and",
"# release naming, not by running the OS/2-only 1990 compiler. M6 links",
"# flib.lib only.",
"",
])
text = "\n".join(lines) + "\n"
with open(os.path.join(out, "flib-symbols.txt"), "w") as f:
f.write(text)
sys.stdout.write(text)
PY
# The exact entries M6 tasks 2/3/6 depend on. If a name is missing the ABI
# contract in TMS34010.md/README.md is stale, so fail loudly.
for sym in \
'FS$ADD' 'FS$SUB' 'FS$SUB_R' 'FS$MUL' 'FS$DIV' 'FS$DIV_R' 'FS$NEG' \
'FS$EQ' 'FS$NE' 'FS$LT' 'FS$LE' 'FS$GT' 'FS$GE' 'FS$ZERO' 'FS$INC' \
'FS$INCR' 'FS$DEC' 'FS$DECR' \
'FD$ADD' 'FD$SUB' 'FD$SUB_R' 'FD$MUL' 'FD$DIV' 'FD$DIV_R' 'FD$NEG' \
'FD$EQ' 'FD$NE' 'FD$LT' 'FD$LE' 'FD$GT' 'FD$GE' 'FD$ZERO' 'FD$INC' \
'FD$INCR' 'FD$DEC' 'FD$DECR' \
'FD$DTOF' 'FD$FTOD' 'FD$FTOI' 'FD$FTOU' 'FD$DTOI' 'FD$DTOU' \
'FD$ITOF' 'FD$ITOD' 'FD$UTOF' 'FD$UTOD'
do
grep -Fq " $sym" "$OUT/flib-symbols.txt" \
|| fail "expected flib symbol $sym is missing"
done
# rts.lib is the C runtime, not a 64-bit arithmetic source: M6 task 2 must use
# target sequences, not invented helpers. Record that fact as a checked one.
if grep -Eiq '(^| )(__ll|_ll|llmul|lldiv|lladd|llsub|\$ll|\$i64|__i64)' "$OUT/flib-symbols.txt"; then
fail "unexpected 64-bit helper in flib/rts symbol list; re-check the ABI note"
fi
cat > "$OUT/m6-abi.txt" <<EOF
flib ABI (from flib.src and the 1987 C compiler output):
* arithmetic: operands are pushed on A14, first operand first, second last;
the result is pushed on A14 (one word for FS\$, two for FD\$);
* compares: both operands are popped from A14; the boolean is in A8
(1 true, 0 false); nothing is pushed;
* conversions: FD\$FTOI/FTOU and FD\$DTOI/DTOU pop the float/double from A14
and return the integer in A8; FD\$ITOF/UTOF and FD\$ITOD/UTOD take the
integer in A8 and push one float / two double words on A14;
FD\$FTOD pops a float and pushes two double words, FD\$DTOF pops a double
and pushes one float word;
* flib routines end in RETS (not RETS 2): pop the pushed result (if any),
then restore the caller A14 from the old-STK word saved on the system
stack;
* flib.lib uses the GSP floating format: 1.5 = 40600000h (float) and
00000000h/400C0000h (double, LSW at the lower address);
* float arguments are one 32-bit slot (ANSI/FS\$ rule; the 1987 K&R oracle
promotes float parameters to double, so it does not pin this slot).
link line:
GSPLNK -l flib.lib -l rts.lib (scripts/m6/link.cmd)
symbol list: $OUT/flib-symbols.txt
EOF
cat "$OUT/m6-abi.txt"
+139
View File
@@ -0,0 +1,139 @@
# 1990-11 TMS340 Family SDK r5.01 external symbol definitions
# generated by scripts/m6/flib-extract.sh; do not edit
#
# flib.lib is the GSP-format floating-point library used by the TI C
# compiler by default. flibc.lib/flibi.lib are identified as the
# 34082/IEEE variants from member-code inspection (see the variant
# section at the end); the 1990 compiler was not run. M6 links flib.lib.
== flib.lib
fc_dtof.obj FD$DTOF
fc_dtoi.obj FD$DTOI
fc_dtou.obj FD$DTOU
fc_ftod.obj FD$FTOD
fc_ftoi.obj FD$FTOI
fc_ftou.obj FD$FTOU
fc_itod.obj FD$ITOD
fc_itof.obj FD$ITOF
fc_utod.obj FD$UTOD
fc_utof.obj FD$UTOF
fd_add.obj FD$ADD FD$SUB_R FD$SUB
fd_cmp.obj FD$GE FD$LE FD$GT FD$LT
fd_decr.obj FD$DECR FD$DEC
fd_div.obj FD$DIV_R FD$DIV
fd_eq.obj FD$EQ
fd_error.obj _fp_error
fd_incr.obj FD$INCR FD$INC
fd_mul.obj FD$MUL
fd_ne.obj FD$NE
fd_neg.obj FD$NEG
fd_zero.obj FD$ZERO
fs_add.obj FS$SUB_R FS$ADD FS$SUB
fs_decr.obj FS$DECR FS$DEC
fs_div.obj FS$DIV FS$DIV_R
fs_eq.obj FS$EQ
fs_ge.obj FS$GE
fs_gt.obj FS$GT
fs_incr.obj FS$INC FS$INCR
fs_le.obj FS$LE
fs_lt.obj FS$LT
fs_mul.obj FS$MUL
fs_ne.obj FS$NE
fs_neg.obj FS$NEG
fs_zero.obj FS$ZERO
== rts.lib
abs.obj _labs _abs
asctime.obj _asctime
asin.obj _acos _asin
atan.obj _atan2 _atan
atof.obj _atof
atoi.obj _atoi _atol
boot.obj _c_int00 __present82
bsearch.obj _bsearch
check82.obj _check82
clock.obj _clock
ctime.obj _ctime
ctype.obj __ctypes_
difftime.obj _difftime
div.obj _div _ldiv
dtos.obj _dtos
ecvt.obj _ecvt
errno.obj _errno
exit.obj _abort _exit _atexit
exp.obj _exp
fabs.obj _fabs
fconvert.obj _fconvert
fcvt.obj _fcvt
floor.obj _ceil _floor
fmod.obj _fmod
frexp.obj _frexp
gmtime.obj _gmtime
isalnum.obj _isalnum
isalpha.obj _isalpha
isascii.obj _isascii
iscntrl.obj _iscntrl
isdigit.obj _isdigit
isgraph.obj _isgraph
islower.obj _islower
isprint.obj _isprint
ispunct.obj _ispunct
isspace.obj _isspace
isupper.obj _isupper
isxdigit.obj _isxdigit
ldexp.obj _ldexp
localtim.obj _localtime
log.obj _log _log10
ltoa.obj _ltoa
memchr.obj _memchr
memcmp.obj _memcmp
memmov.obj _memmove _memcpy
memory.obj _minit _malloc _realloc _free _calloc
memset.obj _memset
mktime.obj _mktime
modf.obj _modf
pow.obj _pow
qsort.obj _qsort
rand.obj _srand _rand
scheck.obj s$check
setjmp.obj _longjmp __setjmp _setjmp
sin.obj _cos _sin
sinh.obj _sinh _cosh
sqrt.obj _sqrt
strcat.obj _strcat
strchr.obj _strchr
strcmp.obj _strcmp
strcoll.obj _strcoll
strcpy.obj _strcpy
strcspn.obj _strcspn
strerror.obj _strerror
strftime.obj _strftime
strlen.obj _strlen
strncat.obj _strncat
strncmp.obj _strncmp
strncpy.obj _strncpy
strpbrk.obj _strpbrk
strrchr.obj _strrchr
strspn.obj _strspn
strstr.obj _strstr
strtod.obj _strtod
strtok.obj _strtok
strtol.obj _strtol
strtoul.obj _strtoul
strxfrm.obj _strxfrm
tan.obj _tan
tanh.obj _tanh
time.obj _time
toascii.obj _toascii
tolower.obj _tolower
toupper.obj _toupper
== variant inspection (not linked by M6)
flib.lib fs_add.obj .text 2384 bits; fd_add.obj .text 3728 bits
flibc.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
flibi.lib fs_add.obj .text 3328 bits; fd_add.obj .text 4864 bits
# flibc/flibi are identified as the 34082/IEEE variants from member-code
# inspection (their members begin with the 34082 path and are larger) and
# release naming, not by running the OS/2-only 1990 compiler. M6 links
# flib.lib only.
+114
View File
@@ -0,0 +1,114 @@
-- float-check.lua -- read the M6 float/double marker words and compare them
-- with the expected GSP bit patterns.
--
-- FLOAT_MARKERS is the bit address of _float_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. Doubles are pairs: LSW
-- first (the lower address), MSW second, which is also the GSP memory order.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("FLOAT_MARKERS"), 16)
local N = 80
local frames = 0
local checked = false
local expect = {
[0] = 0x41400000, -- fadd(1.5,2.5) = 4.0
[1] = 0x40400000, -- fsub(2.5,1.5) = 1.0
[2] = 0xC0400000, -- fsub(1.5,2.5) = -1.0
[3] = 0x41C00000, -- fmul(4.0,2.0) = 8.0
[4] = 0x40C00000, -- fdiv(4.0,2.0) = 2.0
[5] = 0xC0600000, -- fneg(1.5) = -1.5
[6] = 0x41400000, -- C body float_add(1.5,2.5)
[7] = 0x40600000, -- C float_ret() = 1.5
[8] = 0x00000000, [9] = 0x40280000, -- dadd(1.5,2.5) = 4.0
[10] = 0x00000000, [11] = 0x40080000, -- dsub(2.5,1.5) = 1.0
[12] = 0x00000000, [13] = 0xC0080000, -- dsub(1.5,2.5) = -1.0
[14] = 0x00000000, [15] = 0x40380000, -- dmul(4.0,2.0) = 8.0
[16] = 0x00000000, [17] = 0x40180000, -- ddiv(4.0,2.0) = 2.0
[18] = 0x00000000, [19] = 0xC00C0000, -- dneg(1.5) = -1.5
[20] = 0x00000000, [21] = 0x40280000, -- C double_add(1.5,2.5) = 4.0
[22] = 0x00000000, [23] = 0x401A0000, -- C double_ret() = 2.5
[24] = 1, -- fcmpeq(1.5,1.5)
[25] = 0, -- fcmpeq(1.5,2.5)
[26] = 1, -- fcmplt(1.5,2.5)
[27] = 0, -- fcmplt(2.5,1.5)
[28] = 1, -- fcmple(2.5,2.5)
[29] = 1, -- fcmpgt(2.5,1.5)
[30] = 0, -- fcmpge(1.5,2.5)
[31] = 1, -- fcmpne(1.5,2.5)
[32] = 0, -- fcmpne(1.5,1.5)
[33] = 1, -- dcmplt(1.5,2.5)
[34] = 0, -- dcmplt(2.5,1.5)
[35] = 1, -- dcmpeq(2.5,2.5)
[36] = 2, -- ftoi(2.5)
[37] = 0xFFFFFFFF, -- ftoi(-1.5) = -1
[38] = 3, -- ftou(3.9)
[39] = 2, -- dtoi(2.5)
[40] = 3, -- dtou(3.9)
[41] = 0x41700000, -- itof(7) = 7.0
[42] = 0x41700000, -- utof(7) = 7.0
[43] = 0xC0E00000, -- itof(-3) = -3.0
[44] = 0x00000000, [45] = 0x402E0000, -- itod(7) = 7.0
[46] = 0x00000000, [47] = 0x402E0000, -- utod(7) = 7.0
[48] = 0x00000000, [49] = 0x400C0000, -- ftod(1.5f) = 1.5
[50] = 0x40D00000, -- dtof(2.5) = 2.5
[51] = 0x41700000, -- constant 7.0f
[52] = 0xC0E00000, -- constant -3.0f
[53] = 0x00000000, [54] = 0x402E0000, -- constant 7.0
[55] = 0x00000000, [56] = 0xC01C0000, -- constant -3.0
[57] = 1, -- fcmpge(2.5,2.5)
[58] = 0, -- fcmpgt(1.5,1.5)
[59] = 0xFFFFFFFF, -- dtoi(-1.5) = -1
[60] = 0, -- fcmple(2.5,1.5)
[61] = 0, -- dcmpeq(1.5,2.5)
[62] = 11, -- fb_lt(1.5,2.5) true path
[63] = 22, -- fb_lt(2.5,1.5) false path
[64] = 33, -- db_lt(1.5,2.5) true path
[65] = 44, -- db_lt(2.5,1.5) false path
[66] = 3, -- fcount_lt(1.5,4.0): 1.5,2.5,3.5
[67] = 0x00000000, [68] = 0x400C0000, -- dsel_i(1,1.5,2.5) = 1.5
[69] = 0x00000000, [70] = 0x401A0000, -- dsel_i(0,1.5,2.5) = 2.5
[71] = 0x00000000, [72] = 0x40280000, -- dsel_f(<,4.0,8.0) = 4.0
[73] = 0x00000000, [74] = 0x40380000, -- dsel_f(>,4.0,8.0) = 8.0
[75] = 0x00000000, -- fnegzero(): GSP canonicalises -0.0
[76] = 0x00000000, -- fposzero()
[77] = 0x00000000, [78] = 0x00000000, -- dnegzero(): two zero words
[79] = 0x5A5A5A5A, -- marker after float_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 float:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 FLOAT MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 float: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 FLOAT MAME: FAIL")
end
end
end, "float-check")
+27
View File
@@ -0,0 +1,27 @@
; float-entry.asm -- M6 float/double gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver float_run() and writes a post-return marker. float.sh concatenates
; the llc output for m6-float.ll and the compiled driver after this file, so
; _float_run and the float/double functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); float-check.lua reads
; its address from the linker map and checks 80 words (markers 0..79, the last
; one written after float_run returns). Marker n is 0x20 bits above marker
; n-1, matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _float_run
movi 5A5A5A5Ah, a0
movi _float_markers+2528, a2 ; marker 79, the post-return word
move a0, *a2, 1
rets
.globl _float_markers
.bss _float_markers, 2560, 16 ; 80 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+241
View File
@@ -0,0 +1,241 @@
/* M6 float/double gate driver.
*
* Calls the compiled float/double functions in m6-float.ll through the M6
* flib ABI and writes the expected GSP result words to the marker array
* defined by the entry assembly. Compiling this driver also exercises the
* compiler's caller side (hidden float/double return slot, stack argument
* pushes, LSW-first doubles) and the callee side of its own C functions
* (float_add, double_add, float_ret, double_ret).
*
* Values are written as raw GSP words, not converted: a float union member
* and an array of two 32-bit words for a GSP double (u[0] = LSW, u[1] = MSW).
*
* Marker word n lives at float_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/float-check.lua reads them by bit address from the linker
* map.
*/
typedef unsigned int u32;
typedef union {
float f;
u32 u;
} fu;
typedef union {
double d;
u32 u[2];
} du;
extern volatile u32 float_markers[];
/* Callees defined in m6-float.ll. */
extern float fadd(float, float);
extern float fsub(float, float);
extern float fmul(float, float);
extern float fdiv(float, float);
extern float fneg(float);
extern double dadd(double, double);
extern double dsub(double, double);
extern double dmul(double, double);
extern double ddiv(double, double);
extern double dneg(double);
extern int fcmpeq(float, float);
extern int fcmplt(float, float);
extern int fcmple(float, float);
extern int fcmpgt(float, float);
extern int fcmpge(float, float);
extern int fcmpne(float, float);
extern int dcmplt(double, double);
extern int dcmpeq(double, double);
extern int ftoi(float);
extern int ftou(float);
extern int dtoi(double);
extern int dtou(double);
extern float itof(int);
extern float utof(u32);
extern double itod(int);
extern double utod(u32);
extern double ftod(float);
extern float dtof(double);
/* Control flow on floating-point comparisons. These are the shapes that were
* missing: `if (a < b)` on float/double and `?:` on a double. */
static int fb_lt(float a, float b)
{
if (a < b)
return 11;
return 22;
}
static int db_lt(double a, double b)
{
if (a < b)
return 33;
return 44;
}
/* A while loop whose condition is a float compare and whose body is float
* arithmetic: a(float) = 1.5, b(float) = 4.0 iterates 1.5, 2.5, 3.5 and stops
* at 4.5, so it counts 3. */
static int fcount_lt(float a, float b)
{
int n = 0;
while (a < b) {
a = a + 1.0f;
n++;
}
return n;
}
/* An f64 select with an integer condition. */
static double dsel_i(int c, double x, double y)
{
return c ? x : y;
}
/* An f64 select with a floating-point condition. */
static double dsel_f(double a, double b, double x, double y)
{
return (a < b) ? x : y;
}
/* GSP has no signed zero: -0.0 must lower to the same all-zero words as +0.0,
* exactly as GSPA prints `.float -0.0`. These markers pin that. */
static float fnegzero(void)
{
return -0.0f;
}
static float fposzero(void)
{
return 0.0f;
}
static double dnegzero(void)
{
return -0.0;
}
static void mark_f(u32 n, float v)
{
fu x;
x.f = v;
float_markers[n] = x.u;
}
static void mark_d(u32 n, double v)
{
du x;
x.d = v;
float_markers[n] = x.u[0]; /* LSW: the lower address in GSP order */
float_markers[n + 1] = x.u[1]; /* MSW */
}
/* C-side callees: the compiler must emit the flib calls for these bodies. */
float float_add(float a, float b)
{
return a + b;
}
double double_add(double a, double b)
{
return a + b;
}
float float_ret(void)
{
return 1.5f;
}
double double_ret(void)
{
return 2.5;
}
void float_run(void)
{
/* Single-precision arithmetic, including the reversed subtraction order
* and a negative result. */
mark_f(0, fadd(1.5f, 2.5f)); /* 4.0 */
mark_f(1, fsub(2.5f, 1.5f)); /* 1.0 */
mark_f(2, fsub(1.5f, 2.5f)); /* -1.0 */
mark_f(3, fmul(4.0f, 2.0f)); /* 8.0 */
mark_f(4, fdiv(4.0f, 2.0f)); /* 2.0 */
mark_f(5, fneg(1.5f)); /* -1.5 */
mark_f(6, float_add(1.5f, 2.5f)); /* C body */
mark_f(7, float_ret()); /* C no-argument hidden return */
/* Double-precision arithmetic, LSW then MSW. */
mark_d(8, dadd(1.5, 2.5)); /* 4.0 */
mark_d(10, dsub(2.5, 1.5)); /* 1.0 */
mark_d(12, dsub(1.5, 2.5)); /* -1.0 */
mark_d(14, dmul(4.0, 2.0)); /* 8.0 */
mark_d(16, ddiv(4.0, 2.0)); /* 2.0 */
mark_d(18, dneg(1.5)); /* -1.5 */
mark_d(20, double_add(1.5, 2.5)); /* C body */
mark_d(22, double_ret()); /* C no-argument hidden return */
/* Float compares: true and false cases. */
float_markers[24] = (u32)fcmpeq(1.5f, 1.5f);
float_markers[25] = (u32)fcmpeq(1.5f, 2.5f);
float_markers[26] = (u32)fcmplt(1.5f, 2.5f);
float_markers[27] = (u32)fcmplt(2.5f, 1.5f);
float_markers[28] = (u32)fcmple(2.5f, 2.5f);
float_markers[29] = (u32)fcmpgt(2.5f, 1.5f);
float_markers[30] = (u32)fcmpge(1.5f, 2.5f);
float_markers[31] = (u32)fcmpne(1.5f, 2.5f);
float_markers[32] = (u32)fcmpne(1.5f, 1.5f);
/* Double compares. */
float_markers[33] = (u32)dcmplt(1.5, 2.5);
float_markers[34] = (u32)dcmplt(2.5, 1.5);
float_markers[35] = (u32)dcmpeq(2.5, 2.5);
/* float/double -> integer: truncation toward zero. */
float_markers[36] = (u32)ftoi(2.5f); /* 2 */
float_markers[37] = (u32)ftoi(-1.5f); /* -1 */
float_markers[38] = (u32)ftou(3.9f); /* 3 */
float_markers[39] = (u32)dtoi(2.5); /* 2 */
float_markers[40] = (u32)dtou(3.9); /* 3 */
/* integer -> float/double. */
mark_f(41, itof(7)); /* 7.0 */
mark_f(42, utof(7)); /* 7.0 */
mark_f(43, itof(-3)); /* -3.0 */
mark_d(44, itod(7)); /* 7.0 */
mark_d(46, utod(7)); /* 7.0 */
mark_d(48, ftod(1.5f)); /* 1.5 */
mark_f(50, dtof(2.5)); /* 2.5 */
/* Constants materialised from the GSP pool, including a negative one. */
mark_f(51, 7.0f);
mark_f(52, -3.0f);
mark_d(53, 7.0);
mark_d(55, -3.0);
float_markers[57] = (u32)fcmpge(2.5f, 2.5f); /* 1 */
float_markers[58] = (u32)fcmpgt(1.5f, 1.5f); /* 0 */
float_markers[59] = (u32)dtoi(-1.5); /* -1 */
float_markers[60] = (u32)fcmple(2.5f, 1.5f); /* 0 */
float_markers[61] = (u32)dcmpeq(1.5, 2.5); /* 0 */
/* Control flow on float/double comparisons: the true and false path of a
* float and a double branch, and a float-compared while loop. */
float_markers[62] = (u32)fb_lt(1.5f, 2.5f); /* true: 11 */
float_markers[63] = (u32)fb_lt(2.5f, 1.5f); /* false: 22 */
float_markers[64] = (u32)db_lt(1.5, 2.5); /* true: 33 */
float_markers[65] = (u32)db_lt(2.5, 1.5); /* false: 44 */
float_markers[66] = (u32)fcount_lt(1.5f, 4.0f); /* 3 iterations */
/* ?: on a double, with an integer and a floating-point condition. */
mark_d(67, dsel_i(1, 1.5, 2.5)); /* 1.5 */
mark_d(69, dsel_i(0, 1.5, 2.5)); /* 2.5 */
mark_d(71, dsel_f(1.5, 2.5, 4.0, 8.0)); /* 4.0 */
mark_d(73, dsel_f(2.5, 1.5, 4.0, 8.0)); /* 8.0 */
/* Signed zero: both spellings lower to all-zero GSP words. */
mark_f(75, fnegzero()); /* 0 */
mark_f(76, fposzero()); /* 0 */
mark_d(77, dnegzero()); /* 0 / 0 */
}
+81
View File
@@ -0,0 +1,81 @@
-- i64-check.lua -- read the M6 i64 marker words and compare them with the
-- expected ABI/arithmetic values.
--
-- I64_MARKERS is the bit address of _i64_markers from the linker map. Each
-- marker is one 32-bit word at base + n*0x20 bits. The values are pairs:
-- MSW first, LSW second, so the word order is checked as well as the result.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("I64_MARKERS"), 16)
local N = 57
local frames = 0
local checked = false
local expect = {
[0] = 0x2345678A, [1] = 0x00000001, -- addll(carry)
[2] = 0x00000000, [3] = 0xACF13568, -- addll(12345678h,9ABCDEF0h)
[4] = 0xFEDCBA98, [5] = 0x00000005, -- subll borrow
[6] = 0x0000000A, [7] = 0x00000008, -- mull cross terms
[8] = 0xFFFFFFFF, [9] = 0xFFFFFFF1, -- (-3)*5
[10] = 0x00010004, [11] = 0xC016906B, -- divll / 1234h
[12] = 0x00000000, [13] = 0x00000334, -- remll / 1234h
[14] = 0x00000000, [15] = 0x10000000, -- divll by a >32-bit divisor
[16] = 0x00000000, [17] = 0x0ABCDEF0, -- remll by a >32-bit divisor
[18] = 0xFFFFFFDE, [19] = 0xBD0CFDB7, -- sdivll(-1e12, 7)
[20] = 0xFFFFFFFF, [21] = 0xFFFFFFFF, -- sremll(-1e12, 7) == -1
[22] = 0xFFFFFFFF, [23] = 0xFFFFFFEF, -- sdivll(123, -7) == -17
[24] = 0x00000000, [25] = 0x00000004, -- sremll(123, -7) == 4
[26] = 0x00000100, [27] = 0x00000000, -- 1 << 40
[28] = 0x00000000, [29] = 0x00000001, -- 8000000000000000h >> 63
[30] = 0xFFFFFFFF, [31] = 0xFFFFFFFC, -- -16 >> 2
[32] = 1, [33] = 0, -- cmplt(-1,1), cmplt(1,-1)
[34] = 1, [35] = 0, -- cmpeq both halves
[36] = 0x00000006, [37] = 0x00000004, -- i64_slot LSW/MSW word order
[38] = 0x00000004, [39] = 0x00000006, -- i64 load round-trip
[40] = 0x0F0F0000, [41] = 0x0F0F0000, -- and
[42] = 0xFFFF0F0F, [43] = 0xFFFF0F0F, -- or
[44] = 0xF0F00F0F, [45] = 0xF0F00F0F, -- xor
[46] = 0x11223344, [47] = 0x55667788, -- zero-argument i64 return
[48] = 0x11223344, [49] = 0x55667788, -- shll(x, 0)
[50] = 0x55667788, [51] = 0x00000000, -- shll(x, 32)
[52] = 0x00000000, [53] = 0x11223344, -- srl(x, 32)
[54] = 0xFFFFFFFF, [55] = 0x80000000, -- sra(8000..., 32)
[56] = 0x5A5A5A5A, -- marker after i64_run returns
}
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 i64:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
if bad == 0 then
print("M6 I64 MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 i64: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 I64 MAME: FAIL")
end
end
end, "i64-check")
+27
View File
@@ -0,0 +1,27 @@
; i64-entry.asm -- M6 i64 gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver i64_run() and writes a post-return marker. i64.sh concatenates the
; llc output for m6-i64.ll and the compiled driver after this file, so
; _i64_run and the i64 functions are in the same assembly.
;
; The marker array is in .bss (linked at the ram origin); i64-check.lua reads
; its address from the linker map and checks 57 words (markers 0..56, the last
; one written after i64_run returns). Marker n is 0x20 bits above marker n-1,
; matching one 32-bit value per marker slot.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _i64_run
movi 5A5A5A5Ah, a0
movi _i64_markers+1792, a2 ; marker 56, the post-return word
move a0, *a2, 1
rets
.globl _i64_markers
.bss _i64_markers, 2048, 16 ; 57 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+127
View File
@@ -0,0 +1,127 @@
/* M6 i64 gate driver.
*
* Calls the compiled `long long` functions in m6-i64.ll through the M6 ABI and
* writes the expected result words to the marker array defined by the entry
* assembly. Compiling this driver also exercises the compiler's *caller*
* side of the hidden-return slot and the two-slot i64 argument pushes; the
* callee side (argument reads, ADD/ADDC, MPYS/MPYU, the division loop, RETS 2)
* comes from the same llc output the lit test checks.
*
* Marker word n lives at i64_markers[n], i.e. 0x20 bits above the previous
* one; scripts/m6/i64-check.lua reads them by bit address from the linker map.
*/
typedef unsigned int u32;
typedef unsigned long long u64;
typedef long long s64;
extern u64 addll(u64, u64);
extern u64 subll(u64, u64);
extern u64 mull(u64, u64);
extern u64 divll(u64, u64);
extern u64 remll(u64, u64);
extern s64 sdivll(s64, s64);
extern s64 sremll(s64, s64);
extern u64 andll(u64, u64);
extern u64 orll(u64, u64);
extern u64 xorll(u64, u64);
extern u64 shll(u64, u32);
extern u64 srl(u64, u32);
extern s64 sra(s64, u32);
extern u32 cmplt(s64, s64);
extern u32 cmpeq(u64, u64);
extern u64 ret64(void);
extern volatile u32 i64_markers[];
/* Every value is written as MSW first, LSW second, so the marker pair pins
* the word order as well as the numeric result. */
static void mark64(u32 n, u64 v)
{
i64_markers[n] = (u32)(v >> 32);
i64_markers[n + 1] = (u32)v;
}
/* i64 memory order: little-endian, LSW at the lower address. */
volatile u64 i64_slot;
void i64_run(void)
{
u64 r;
/* addll(12345678FFFFFFFEh, 1111111100000003h) = 2345678A00000001h.
* This is the Task 1 probe value; the low-word carry must reach the
* high word. */
mark64(0, addll(0x12345678FFFFFFFEull, 0x1111111100000003ull));
/* The literal brief case addll(12345678h, 9ABCDEF0h) = ACF13568h. */
mark64(2, addll(0x12345678ull, 0x9ABCDEF0ull));
/* subll(1111111100000003h, 12345678FFFFFFFEh) = FEDCBA9800000005h:
* the borrow crosses from the low into the high word. */
mark64(4, subll(0x1111111100000003ull, 0x12345678FFFFFFFEull));
/* mull(0000000100000002h, 0000000300000004h) = 0000000A00000008h:
* both cross terms are needed. */
mark64(6, mull(0x0000000100000002ull, 0x0000000300000004ull));
/* (-3) * 5 = -15 = FFFFFFFFFFFFFFF1h. */
mark64(8, mull(0xFFFFFFFFFFFFFFFDull, 5ull));
/* 123456789ABCDEF0h / 1234h = 10004C016906Bh, remainder 334h. */
mark64(10, divll(0x123456789ABCDEF0ull, 0x1234ull));
mark64(12, remll(0x123456789ABCDEF0ull, 0x1234ull));
/* A divisor above 32 bits forces the full 64x64 path:
* 123456789ABCDEF0h / 123456789h = 100000000h, remainder ABCDEF0h. */
mark64(14, divll(0x123456789ABCDEF0ull, 0x123456789ull));
mark64(16, remll(0x123456789ABCDEF0ull, 0x123456789ull));
/* Signed division truncates toward zero: -1000000000000 / 7 =
* -142857142857 = FFFFFFDEBD0CFDB7h, remainder -1. */
mark64(18, (u64)sdivll(-1000000000000ll, 7ll));
mark64(20, (u64)sremll(-1000000000000ll, 7ll));
/* 123 / -7 = -17 = FFFFFFFFh/FFFFFFEFh, remainder 4. */
mark64(22, (u64)sdivll(123ll, -7ll));
mark64(24, (u64)sremll(123ll, -7ll));
/* Variable-amount shifts: 1 << 40 = 10000000000h. */
mark64(26, shll(1ull, 40));
/* 8000000000000000h >> 63 = 1. */
mark64(28, srl(0x8000000000000000ull, 63));
/* -16 >> 2 = -4 = FFFFFFFFFFFFFFFCh (arithmetic). */
mark64(30, (u64)sra(-16ll, 2));
/* Compares: signed high-half ordering and equality across both halves. */
i64_markers[32] = cmplt(-1ll, 1ll);
i64_markers[33] = cmplt(1ll, -1ll);
i64_markers[34] = cmpeq(0x123456789ABCDEF0ull, 0x123456789ABCDEF0ull);
i64_markers[35] = cmpeq(0x123456789ABCDEF1ull, 0x123456789ABCDEF0ull);
/* i64 store then load through a volatile object, plus a direct word
* read: little-endian memory puts the LSW at the lower address. */
i64_slot = addll(0x0000000100000002ull, 0x0000000300000004ull);
{
volatile u32 *w = (volatile u32 *)&i64_slot;
i64_markers[36] = w[0];
i64_markers[37] = w[1];
}
r = i64_slot;
mark64(38, r);
/* Word-wise logic: and/or/xor of both halves. */
mark64(40, andll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(42, orll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
mark64(44, xorll(0xFFFF0000FFFF0000ull, 0x0F0F0F0F0F0F0F0Full));
/* A zero-argument i64 return: the caller still saves STK for the hidden
* slot and the callee must LOADSTK + RETS 2 with no argument area. */
mark64(46, ret64());
/* Variable-shift edges: 0, 32, and the arithmetic sign fill. */
mark64(48, shll(0x1122334455667788ull, 0));
mark64(50, shll(0x1122334455667788ull, 32));
mark64(52, srl(0x1122334455667788ull, 32));
mark64(54, (u64)sra(0x8000000000000000ull, 32));
}
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 8000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+139
View File
@@ -0,0 +1,139 @@
-- runtime-check.lua -- read the M6 runtime gate marker words and the shim's
-- printf output block, and compare them with the expected values.
--
-- RUNTIME_MARKERS is the bit address of _runtime_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. The shim's CONF
-- output block is fixed: length at 01B00020h, bytes at 01B10000h (one byte per
-- 8 bits). The checker compares the whole output byte-for-byte, including the
-- newlines, so the format implementation is the runtime oracle.
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "3400")
local BASE = tonumber(os.getenv("RUNTIME_MARKERS"), 16)
local LEN_ADDR = 0x01B00020
local OUT = 0x01B10000
local CAP = 16384
local N = 13 -- markers 0..12 are written by the driver
local SENT = 15 -- marker 15 is written after runtime_run returns
local frames = 0
local checked = false
local expect = {
[0] = 31, -- printf("%d %s %f %lld\n", ...) length
[1] = 9, -- sprintf("%d|%s|%.1f", 7, "abc", 2.5) length
[2] = 19, -- sprintf("%lld", 1234567890123456789) length
[3] = 300, -- sprintf truncation: full length, not the stored one
[4] = 255, -- strlen after truncation (SPRINTF_CAP-1)
[5] = 1, -- the truncated buffer is NUL-terminated
[6] = 4, -- (int)(1.5 + 2.5), flib FD$ADD + FD$DTOI
[7] = 3, -- (int)(1.5 * 2.5), flib FD$MUL + FD$DTOI
[8] = 1, -- memcpy result equals the source
[9] = 1, -- overlapping memmove forward ("aabcdef")
[10] = 1, -- overlapping memmove backward ("3456567")
[11] = 17, -- printf("S[%s] (%d)\n", ...) length
[12] = 1, -- rts.lib _isascii('A') nonzero, (0xC8) zero
}
local lines = {
"-42 hi 3.250000 -1234567890123",
"[ 42][-0042][7 ][+5][ 5][ff][0xff][10][010][ abc]",
"c=[ A][B ][C]",
"9223372036854775807 -9223372036854775808 " ..
"18446744073709551615 0 -1 4294967295 " ..
"[-0000000000000000005]",
"int=[-123456789][123456789abcdef0][110642547423257157360][00042][42 ]",
"-3.250000 -3.25 3 1.3 3.25 3.25 +3.250000",
"0.000000|00003.25|0.00| 3.25| 3.250000|3.|3.250000",
"cap=2147483520.000000",
"prec=[010][][][][][][0][0][ ]",
"round=10.000000 ncap=-2147483520.000000",
"S[7|abc|2.5] (9)",
"T(300,255,1)",
"mem=abcdefg abcdefg",
"mov=aabcdef",
"mov2=3456567",
"rts=1",
"flib 4.000000 3.750000",
}
local want_out = table.concat(lines, "\n") .. "\n"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
local function escape(s)
return (s:gsub("\n", "\\n"))
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
got[SENT] = prog:read_u32(BASE + SENT * 0x20)
if got[SENT] ~= 0x5A5A5A5A then
bad = bad + 1
end
io.write(string.format("M6 runtime:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write(string.format(" %08X\n", got[SENT]))
local len = prog:read_u32(LEN_ADDR)
if len > CAP then
print(string.format("M6 runtime: output length %d > cap %d",
len, CAP))
bad = bad + 1
len = 0
end
local out = read_string(prog, OUT, len)
print(string.format("M6 runtime out(%d): '%s'", len, escape(out)))
if out ~= want_out then
local diff = 1
while diff <= #out and diff <= #want_out and
out:sub(diff, diff) == want_out:sub(diff, diff) do
diff = diff + 1
end
print(string.format(
"M6 runtime: output differs at byte %d: got '%s' want '%s'",
diff, escape(out:sub(diff, diff + 20)),
escape(want_out:sub(diff, diff + 20))))
bad = bad + 1
end
if bad == 0 then
print("M6 RUNTIME MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 runtime: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
if got[SENT] ~= 0x5A5A5A5A then
print(string.format(
"M6 runtime: sentinel got %08X want 5A5A5A5A",
got[SENT]))
end
print("M6 RUNTIME MAME: FAIL")
end
end
end, "runtime-check")
+47
View File
@@ -0,0 +1,47 @@
; runtime-entry.asm -- M6 runtime gate entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the gate stack, calls the C
; driver runtime_run() and writes a post-return marker. runtime.sh
; concatenates the compiled driver and the shared conformance shim after this
; file, so _runtime_run, printf/sprintf and the string/memory functions share
; one assembly.
;
; The marker array is in .bss (linked at the ram origin); runtime-check.lua
; reads its address from the linker map and checks 13 words (0..12 written by
; the driver), 15 after runtime_run returns, and leaves 13..14 zero/unchecked.
; Marker n is 0x20 bits above marker n-1.
;
; The shim's printf output goes to its own CONF_* block above the linked RAM
; region (length at 01B00020h, bytes at 01B10000h); the checker compares those
; bytes with the expected text.
;
; GSPA requires `.ref` for an external symbol used by CALLA. The AsmPrinter
; emits it for the flib `$` ExternalSymbols but not for an ordinary C
; declaration (a GlobalAddress), so declare the rts.lib entry here.
.ref _isascii
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
; Clear the shim's stream lengths. This entry does not otherwise touch
; the result block, and the shim's shadows cannot repair a cell it never
; writes (an empty stream), so clear both cells here.
movi 01B00020h, a1
sub a0, a0
move a0, *a1, 1
movi 01B00060h, a1
move a0, *a1, 1
movi _cstack, a14
move a14, a13
calla _runtime_run
movi 5A5A5A5Ah, a0
movi _runtime_markers+480, a2 ; marker 15, the post-return word
move a0, *a2, 1
rets
.globl _runtime_markers
.bss _runtime_markers, 512, 16 ; 16 marker words (0x20 bits each)
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+18
View File
@@ -0,0 +1,18 @@
-a
-o M6.OUT
-m M6.MAP
-e _start
M6.OBJ
-l flib.lib
-l rts.lib
MEMORY
{
prog: origin = 018A0000h, length = 40000h
ram: origin = 01A00000h, length = 80000h
}
SECTIONS
{
.text: {} > prog
.data: {} > prog
.bss: {} > ram
}
+142
View File
@@ -0,0 +1,142 @@
/* M6 runtime gate driver.
*
* Exercises the linked M6 runtime surface through the shared shim:
* - printf("%d %s %f %lld", ...) with a negative int, a string, a GSP double
* with a fraction, and a negative 64-bit value;
* - the M5 integer formats/flags/width/alternate forms;
* - i64/unsigned-i64 boundaries, %ld/%lu and a zero-padded %lld;
* - %f sign/space/plus/zero/width/precision, star width/precision, and the
* documented half-up rounding of %.0f / %.1f;
* - sprintf return values (C: the full untruncated length), NUL
* termination, and safe truncation at the shim's SPRINTF_CAP;
* - memcpy and memmove, including an overlapping backward copy;
* - a double add and multiply that must call flib.lib (FD$ADD/FD$MUL) and be
* converted back to an int by the compiler's fptosi path (FD$DTOI).
*
* The shim writes printf output to the CONF_* block (0x01B00020 length,
* 0x01B10000 bytes); runtime-check.lua compares those bytes exactly with the
* expected text. Marker word n is runtime_markers[n], 0x20 bits apart, in the
* .bss array defined by runtime-entry.asm.
*/
typedef unsigned int u32;
extern volatile u32 runtime_markers[];
extern int printf(const char *fmt, ...);
extern int sprintf(char *buf, const char *fmt, ...);
extern void *memcpy(void *dst, const void *src, unsigned int n);
extern void *memmove(void *dst, const void *src, unsigned int n);
extern int memcmp(const void *a, const void *b, unsigned int n);
extern unsigned int strlen(const char *s);
/* A real rts.lib scalar entry (isascii.obj; no data/.cinit dependency). The
* 1990 `_div`/`_ldiv` wrappers also live in rts.lib but return div_t/ldiv_t
* with the 1990 sret form, not M6's 1987 hidden slot, so calling them would
* not be valid M6 ABI evidence. */
extern int rts_isascii(int c) __asm__("isascii");
void runtime_run(void)
{
char sbuf[256]; /* the shim's sprintf cap (SPRINTF_CAP) */
char lng[301];
char m1[8] = "abcdefg";
char m2[8];
char m3[8] = "1234567";
volatile double a = 1.5; /* volatile: keep FD$ADD/FD$MUL at -O2 */
volatile double b = 2.5;
double d, e;
int i, n;
/* 1. The required mixed conversion: int, string, GSP double, i64. */
runtime_markers[0] = (u32)printf("%d %s %f %lld\n",
-42, "hi", 3.25,
-1234567890123LL);
/* 2. M5 flags/width/alternate plus the new %s precision and width. */
printf("[%5d][%05d][%-5d][%+d][% d][%x][%#x][%o][%#o][%8.3s]\n",
42, -42, 7, 5, 5, 255, 255, 8, 8, "abcdef");
/* 2b. %c honours width/left; a bare %c is unchanged. */
printf("c=[%3c][%-3c][%c]\n", 'A', 'B', 'C');
/* 3. i64/unsigned-i64 boundaries, 32-bit long, zero-padded i64. */
printf("%lld %lld %llu %llu %lld %lu [%020lld]\n",
9223372036854775807LL, (-9223372036854775807LL - 1),
0xFFFFFFFFFFFFFFFFULL, 0ULL, -1LL, 0xFFFFFFFFUL, -5LL);
/* 3b. %ld, 64-bit hex/octal, integer precision and a negative `*`
* width (left-justify with the magnitude of the width). */
printf("int=[%ld][%llx][%llo][%.5d][%*d]\n",
-123456789L, 0x123456789ABCDEF0ULL,
0x123456789ABCDEF0ULL, 42, -6, 42);
/* 4. %f sign/flags/width/precision; %.0f and %.1f round half-up. */
printf("%f %.2f %.0f %.1f %10.2f %-10.2f %+f\n",
-3.25, -3.25, 2.5, 1.25, 3.25, 3.25, 3.25);
/* 5. Zero, zero-padded, star width/precision, space and '#' flags;
* %.9f proves the documented 6-digit precision cap. */
printf("%f|%08.2f|%.2f|%*.*f|% f|%#.0f|%.9f\n",
0.0, 3.25, -0.0, 7, 2, 3.25, 3.25, 2.5, 3.25);
/* 5b. The documented i32-range cap: an out-of-range magnitude is clamped
* instead of taking FD$DTOI's error path. */
printf("cap=%f\n", 3000000000.0);
/* 5c. C precision edge cases: the octal '#' must not add a second
* leading zero when precision already supplies one, and zero with
* precision 0 produces no digits (except `%#.0o`/`%#o`, which keep
* one). */
printf("prec=[%#.3o][%.0d][%.0i][%.0u][%.0x][%.0X][%#.0o][%#o][%5.0d]\n",
8, 0, 0, 0, 0, 0, 0, 0, 0);
/* 5d. Rounding carry through the fraction into the integer part
* (9.9999999 -> 10.000000) and the negative magnitude clamp. */
printf("round=%f ncap=%f\n", 9.9999999, -3000000000.0);
/* sprintf into the caller buffer and print it; the return is the
* C number of characters written (no NUL). */
n = sprintf(sbuf, "%d|%s|%.1f", 7, "abc", 2.5);
runtime_markers[1] = (u32)n;
runtime_markers[11] = (u32)printf("S[%s] (%d)\n", sbuf, n);
/* sprintf return value at the 64-bit boundary (19 digits). */
runtime_markers[2] = (u32)sprintf(sbuf, "%lld",
1234567890123456789LL);
/* sprintf truncation: 300 characters into the 256-byte shim cap. */
for (i = 0; i < 300; i++)
lng[i] = 'a';
lng[300] = 0;
n = sprintf(sbuf, "%s", lng);
runtime_markers[3] = (u32)n;
runtime_markers[4] = strlen(sbuf);
runtime_markers[5] = (u32)(sbuf[255] == 0);
printf("T(%d,%u,%d)\n", n, strlen(sbuf), sbuf[255] == 0);
/* memcpy; then memmove in both directions (overlapping ranges). */
memcpy(m2, m1, 8);
runtime_markers[8] = (u32)(memcmp(m2, m1, 8) == 0);
printf("mem=%s %s\n", m2, m1);
memmove(m1 + 1, m1, 6);
runtime_markers[9] = (u32)(memcmp(m1, "aabcdef", 8) == 0);
printf("mov=%s\n", m1);
memmove(m3, m3 + 2, 4);
runtime_markers[10] = (u32)(memcmp(m3, "3456567", 8) == 0);
printf("mov2=%s\n", m3);
/* rts.lib is linked for real: _isascii is a scalar entry with the TI ABI
* (the 1990 _div/_ldiv wrappers are sret-form and are not called). */
i = (rts_isascii('A') != 0) && (rts_isascii(0xC8) == 0);
runtime_markers[12] = (u32)i;
printf("rts=%d\n", i);
/* flib.lib double arithmetic, formatted back through %f. The volatile
* operands keep the add/multiply from folding at -O2, so both levels
* link and call the real FD$ entries. */
d = a + b;
e = a * b;
runtime_markers[6] = (u32)(int)d;
runtime_markers[7] = (u32)(int)e;
printf("flib %f %f\n", d, e);
}
+70
View File
@@ -0,0 +1,70 @@
-- spike-check.lua -- load the M6 ABI-spike COFF with dwt/loader/loader.lua and
-- read the marker words written by scripts/m6/spike-probe.asm and
-- spike-entry.asm.
--
-- M4_LOADER_LUA path to vendor/vt1200/dwt/loader/loader.lua
-- LOADER_END loader inspection/exit frame
--
-- Markers (0x20 bits apart) are the M4 marker convention:
-- 018A8000 FS$ADD float 4.0 (GSP) == 41400000h
-- 018A8020 FD$ADD double 4.0 MSW (GSP) == 40280000h
-- 018A8040 FD$ADD double 4.0 LSW == 00000000h
-- 018A8060 _m6_dadd hidden-return MSW == 40280000h
-- 018A8080 _m6_dadd hidden-return LSW == 00000000h
-- 018A80A0 i64 sum high word == 2345678Ah
-- 018A80C0 i64 sum low word == 00000001h
-- 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
-- 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
-- 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
-- 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
-- 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
-- 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
dofile(os.getenv("M4_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2700")
local frames = 0
local checked = false
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local m = {}
for i = 0, 12 do
m[i] = prog:read_u32(0x018A8000 + i * 0x20)
end
print(string.format(
"M6: fs_add=%08X fd_add=%08X/%08X dadd=%08X/%08X i64=%08X/%08X fsub=%08X feq=%d ftoi=%d itof=%08X fadd=%08X ret=%08X",
m[0], m[1], m[2], m[3], m[4], m[5], m[6],
m[7], m[8], m[9], m[10], m[11], m[12]))
local want = {
0x41400000, -- FS$ADD 1.5 + 2.5
0x40280000, -- FD$ADD 4.0 MSW
0x00000000, -- FD$ADD 4.0 LSW
0x40280000, -- hidden-return 4.0 MSW
0x00000000, -- hidden-return 4.0 LSW
0x2345678A, -- i64 sum high
0x00000001, -- i64 sum low
0x40400000, -- FS$SUB(2.5,1.5) = 1.0
0x00000001, -- FS$EQ(1.5,1.5) = true in A8
0x00000001, -- FD$FTOI(1.5) = 1 in A8
0x40400000, -- FD$ITOF(1) = float 1.0 pushed on A14
0x41400000, -- _m6_fadd hidden-return 4.0
0x5A5A5A5A, -- _start after _m6_probe returns
}
local ok = true
for i = 0, 12 do
if m[i] ~= want[i + 1] then
ok = false
end
end
if ok then
print("M6 MAME: PASS")
else
print("M6 MAME: FAIL (want fs_add=41400000 fd_add=40280000/00000000 dadd=40280000/00000000 i64=2345678A/00000001 fsub=40400000 feq=1 ftoi=1 itof=40400000 fadd=41400000 ret=5A5A5A5A)")
end
end
end, "m6-check")
+25
View File
@@ -0,0 +1,25 @@
; spike-entry.asm -- M6 ABI spike entry, linked at bit 018A0000.
;
; Sets the TI C field sizes, points STK/FP at the spike stack and calls the
; hand-written probe. The probe is assembly because the compiler does not
; support float/i64 calls until tasks 2/3.
;
; scripts/m6/spike-probe.asm the FS$/FD$ and i64 stack probes
; scripts/m6/spike-check.lua the MAME marker check
; scripts/tests/m6/spike.sh assemble, link with flib.lib/rts.lib, run
;
; FS0 is 16 and FS1 is 32 with the field-extension bit set, exactly as the M2
; ABI requires. A13 is FP and A14 is STK. spike.sh concatenates
; spike-probe.asm after this file, so _m6_probe is defined in the same assembly.
.text
.globl _start
_start:
setf 16, 1, 0
setf 32, 0, 1
movi _cstack, a14
move a14, a13
calla _m6_probe
move a8, @018A8180h, 1 ; marker after the probe returns
rets
.bss _cstack, 32768, 16 ; 32768 bits = 4096 bytes
+274
View File
@@ -0,0 +1,274 @@
; spike-probe.asm -- M6 float/double/i64 stack-ABI probe.
;
; The M6 compiler does not lower float/double or i64 calls yet (tasks 2/3), so
; this probe is hand-written assembly that exercises the TI C stack ABI and
; the 1990 SDK flib.lib entry points directly:
;
; 1. FS$ADD(1.5, 2.5) single-precision float, GSP format
; 2. FD$ADD(1.5, 2.5) double precision, GSP format
; 3. _m6_dadd(1.5, 2.5) a C-ABI double function with a caller-allocated
; hidden 8-byte return slot; it calls FD$ADD
; 4. _m6_i64_add two 32-bit argument words per i64 argument and a
; caller-allocated hidden 8-byte return slot
; 5. FS$SUB(2.5, 1.5) pins the arithmetic push order (2.5 first)
; 6. FS$EQ(1.5, 1.5) compare result in A8, not on A14
; 7. FD$FTOI/FD$ITOF integer conversion in A8 / float push on A14
; 8. _m6_fadd(1.5,2.5) a C-ABI float function with a one-word hidden slot
; 9. a marker after _m6_probe returns, so a broken A14 restore/RETS fails
;
; Results are written at the M4 marker addresses (0x20 bits apart) for
; scripts/m6/spike-check.lua:
;
; 018A8000 FS$ADD float 4.0 == 41400000h (GSP)
; 018A8020 FD$ADD double 4.0 most-significant word == 40280000h (GSP)
; 018A8040 FD$ADD double 4.0 least-significant word == 00000000h
; 018A8060 _m6_dadd hidden-return MSW == 40280000h
; 018A8080 _m6_dadd hidden-return LSW == 00000000h
; 018A80A0 i64 sum high word == 2345678Ah
; 018A80C0 i64 sum low word == 00000001h
; 018A80E0 FS$SUB(2.5,1.5) float 1.0 == 40400000h
; 018A8100 FS$EQ(1.5,1.5) boolean in A8 == 00000001h
; 018A8120 FD$FTOI(1.5) integer in A8 == 00000001h
; 018A8140 FD$ITOF(1) float 1.0 pushed on A14 == 40400000h
; 018A8160 _m6_fadd hidden-return float 4.0 == 41400000h
; 018A8180 _start marker after _m6_probe returns == 5A5A5A5Ah
;
; 1990 flib.lib is the GSP-format library (flibc.lib/flibi.lib are the
; 34082/IEEE variants by member inspection, not linked here). A GSP double is
; stored least-significant word first:
; the lower stack address holds the mantissa word, the higher address holds the
; sign/exponent word. The M6 i64 stack-slot order is MSW-first, so its
; most-significant word is at the lower address.
FP .set A13
STK .set A14
.ref FS$ADD
.ref FS$SUB
.ref FS$EQ
.ref FD$ADD
.ref FD$FTOI
.ref FD$ITOF
.text
.globl _m6_probe
_m6_probe:
setf 16, 1, 0
setf 32, 0, 1
move a14, -*sp, 1 ; preserve the probe's entry STK
move a13, -*sp, 1 ; preserve the probe's entry FP
; ---------------------------------------------------------------------------
; 1. FS$ADD: 1.5 + 2.5 == 4.0 (one 32-bit slot per float, GSP format)
; ---------------------------------------------------------------------------
move a14, -*sp, 1 ; flib uses RETS, not RETS 2
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
movi 040D00000h, a0 ; 2.5
move a0, *a14+, 1
calla FS$ADD
move -*a14, a8, 1 ; result 4.0
move *sp+, a14, 1 ; restore STK
move a8, @018A8000h, 1
; ---------------------------------------------------------------------------
; 2. FD$ADD: 1.5 + 2.5 == 4.0 (two 32-bit slots per double, GSP format).
; GSP puts the least-significant (mantissa) word at the lower address, so
; push it first; the sign/exponent word is the top of the operand.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
clr a0 ; 1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; 1.5 MSW
move a0, *a14+, 1
clr a0 ; 2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; 2.5 MSW
move a0, *a14+, 1
calla FD$ADD
move -*a14, a0, 1 ; result MSW (top)
move -*a14, a1, 1 ; result LSW
move *sp+, a14, 1
move a0, @018A8020h, 1
move a1, @018A8040h, 1
; ---------------------------------------------------------------------------
; 3. _m6_dadd(1.5, 2.5): the caller reserves the 8-byte return slot at the top
; of its frame, then saves STK, then pushes the arguments. The callee
; writes the result at saved_STK-64 (LSW) and saved_STK-32 (MSW).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated return slot
move a14, -*sp, 1 ; save STK for the callee
clr a0 ; b=2.5 LSW
move a0, *a14+, 1
movi 0401A0000h, a0 ; b=2.5 MSW
move a0, *a14+, 1
clr a0 ; a=1.5 LSW
move a0, *a14+, 1
movi 0400C0000h, a0 ; a=1.5 MSW
move a0, *a14+, 1
calla _m6_dadd
move -*a14, a0, 1 ; result MSW (saved_STK-32)
move -*a14, a1, 1 ; result LSW (saved_STK-64)
move a0, @018A8060h, 1
move a1, @018A8080h, 1
; ---------------------------------------------------------------------------
; 4. _m6_i64_add(12345678FFFFFFFEh, 1111111100000003h) == 2345678A00000001h.
; Each i64 argument is two 32-bit slots, most-significant word first; the
; return is the 8-byte caller-allocated slot (MSW at saved_STK-64, LSW at
; saved_STK-32).
; ---------------------------------------------------------------------------
addi 64, a14 ; caller-allocated i64 return slot
move a14, -*sp, 1
movi 011111111h, a0 ; b high
move a0, *a14+, 1
movi 3, a0 ; b low
move a0, *a14+, 1
movi 012345678h, a0 ; a high
move a0, *a14+, 1
movi 0FFFFFFFEh, a0 ; a low
move a0, *a14+, 1
calla _m6_i64_add
move -*a14, a0, 1 ; result low (saved_STK-32)
move -*a14, a1, 1 ; result high (saved_STK-64)
move a1, @018A80A0h, 1
move a0, @018A80C0h, 1
; ---------------------------------------------------------------------------
; 5. FS$SUB(2.5, 1.5) == 1.0. The first operand is pushed first; the library
; pops the second (top) and subtracts it from the first. Reversing the
; push order would yield -1.0 (C0400000h), so this pins the order.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040D00000h, a0 ; 2.5 (first)
move a0, *a14+, 1
movi 040600000h, a0 ; 1.5 (second)
move a0, *a14+, 1
calla FS$SUB
move -*a14, a0, 1 ; result 1.0
move *sp+, a14, 1
move a0, @018A80E0h, 1
; ---------------------------------------------------------------------------
; 6. FS$EQ(1.5, 1.5) -> A8=1. A compare pops both operands and does not push
; a result; the boolean is in A8.
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
move a0, *a14+, 1
calla FS$EQ
move *sp+, a14, 1 ; compare popped both; no result push
move a8, @018A8100h, 1 ; boolean true
; ---------------------------------------------------------------------------
; 7. FD$FTOI(1.5) -> A8=1 (float input on A14, integer result in A8), then
; FD$ITOF(1) -> float 1.0 pushed on A14 (integer input in A8).
; ---------------------------------------------------------------------------
move a14, -*sp, 1
movi 040600000h, a0 ; 1.5
move a0, *a14+, 1
calla FD$FTOI
move *sp+, a14, 1 ; input popped; no result push
move a8, @018A8120h, 1 ; integer 1
move a14, -*sp, 1 ; A8 still holds 1
calla FD$ITOF
move -*a14, a0, 1 ; result float 1.0 = 40400000h
move *sp+, a14, 1
move a0, @018A8140h, 1
; ---------------------------------------------------------------------------
; 8. _m6_fadd(1.5, 2.5): the caller reserves a one-word return slot
; (ADDI 32,STK), the callee writes it at saved_STK-32 and RETS 2.
; ---------------------------------------------------------------------------
addi 32, a14 ; caller-allocated float return slot
move a14, -*sp, 1
movi 040D00000h, a0 ; b=2.5
move a0, *a14+, 1
movi 040600000h, a0 ; a=1.5
move a0, *a14+, 1
calla _m6_fadd
move -*a14, a0, 1 ; result 4.0 (saved_STK-32)
move a0, @018A8160h, 1
; ---------------------------------------------------------------------------
; 9. Return a known A8 after all A14 save/restore pairs. spike-entry.asm
; stores it after CALLA _m6_probe, so a broken restore or RETS cannot pass.
; ---------------------------------------------------------------------------
movi 05A5A5A5Ah, a8
move *sp+, a13, 1 ; restore entry FP
move *sp+, a14, 1 ; restore entry STK
rets
; ---------------------------------------------------------------------------
; _m6_dadd: double dadd(double a, double b) with the TI C hidden-return rule.
; a at FP(-64)=LSW, FP(-32)=MSW; b at FP(-128)=LSW, FP(-96)=MSW
; result at saved_STK-64=LSW, saved_STK-32=MSW
; ---------------------------------------------------------------------------
.globl _m6_dadd
_m6_dadd:
mmtm sp, a0, a1, a2
move a13, -*sp, 1
move a14, a13
move *a13(-64), *a14+, 1 ; a LSW
move *a13(-32), *a14+, 1 ; a MSW
move *a13(-128), *a14+, 1 ; b LSW
move *a13(-96), *a14+, 1 ; b MSW
calla FD$ADD
move -*a14, a2, 1 ; result MSW
move -*a14, a1, 1 ; result LSW
move *sp(160), a14, 1 ; caller's saved STK (3 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; LSW at saved_STK-64
move a2, *a0, 1 ; MSW at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2
rets 2
; ---------------------------------------------------------------------------
; _m6_fadd: float fadd(float a, float b) with the TI C hidden-return rule.
; One 32-bit slot per float: a at FP(-32), b at FP(-64).
; result at saved_STK-32.
; ---------------------------------------------------------------------------
.globl _m6_fadd
_m6_fadd:
mmtm sp, a0, a1
move a13, -*sp, 1
move a14, a13
move *a13(-32), *a14+, 1 ; a
move *a13(-64), *a14+, 1 ; b
calla FS$ADD
move -*a14, a1, 1 ; result
move *sp(128), a14, 1 ; caller's saved STK (2 regs+FP+PC)
move a14, a0
subi 32, a0
move a1, *a0, 1 ; result at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1
rets 2
; ---------------------------------------------------------------------------
; _m6_i64_add: long long add(long long a, long long b), hidden 8-byte return.
; a high at FP(-64), a low at FP(-32); b high at FP(-128), b low at FP(-96).
; The caller pushes b high, b low, a high, a low, so the pop order is
; a low, a high, b low, b high.
; ---------------------------------------------------------------------------
.globl _m6_i64_add
_m6_i64_add:
mmtm sp, a0, a1, a2, a3
move a13, -*sp, 1
move a14, a13
move -*a14, a2, 1 ; a low
move -*a14, a1, 1 ; a high
move -*a14, a0, 1 ; b low
move -*a14, a3, 1 ; b high
add a0, a2 ; low = a low + b low, sets carry
addc a3, a1 ; high = a high + b high + carry
move *sp(192), a14, 1 ; caller's saved STK (4 regs+FP+PC)
move a14, a0
subi 64, a0
move a1, *a0+, 1 ; high at saved_STK-64
move a2, *a0, 1 ; low at saved_STK-32
move *sp+, a13, 1
mmfm sp, a0, a1, a2, a3
rets 2
+87
View File
@@ -0,0 +1,87 @@
-- varargs-check.lua -- read the M6 varargs marker words and the formatted
-- output buffer, and compare them with the expected values.
--
-- VARARGS_MARKERS is the bit address of _varargs_markers from the linker map;
-- each marker is one 32-bit word at base + n*0x20 bits. VARARGS_OUT is the
-- bit address of the C driver's `char varargs_out[64]`; the checker reads the
-- bytes of the expected string (TMS34010 memory is byte-addressed at the low
-- end of a bit address, one byte per 8 bits).
--
-- The marker read runs one frame before loader.lua's inspection/exit frame.
dofile(os.getenv("M2_LOADER_LUA"))
local ENDF = tonumber(os.getenv("LOADER_END") or "2900")
local BASE = tonumber(os.getenv("VARARGS_MARKERS"), 16)
local OUT = tonumber(os.getenv("VARARGS_OUT"), 16)
local N = 15
local frames = 0
local checked = false
local expect = {
[0] = 100, -- vsum(4, 10, 20, 30, 40): int walk
[1] = 42, -- vlong(0, 42): long is one slot
[2] = 1, -- vptr(0, 0x12345678): char * is one slot
[3] = 2, -- vdbl(0, 2.5): GSP double, MSW at the top
[4] = 0x9ABCDEF0, -- vll(0, 123456789ABCDEF0h): i64 LSW at the top
[5] = 257, -- mixed_di(0, 2.5, 7): double then int
[6] = 0x5566BD76, -- mixed_llp(0, 1122334455667788h, CAFEh)
[7] = 13, -- vcopy(0, 4, 5, 6): va_copy independence
[8] = 24, -- vforward(3, 7, 8, 9): forwarded va_list
[9] = 11, -- vnoargs(11): no fixed argument
[10] = 77, -- vlastd(1.5, 77): double last fixed argument
[11] = 4, -- myfmt("n=%d", -7) length
[12] = 19, -- myfmt("v=%d s=%s d=%f", ...) length
[13] = 2, -- call_vf32(): one-slot f32 va_arg
[14] = 0x5A5A5A5A, -- marker after varargs_run returns
}
local want_out = "v=42 s=hello d=3.25"
local function read_string(space, addr, len)
local s = {}
for i = 0, len - 1 do
s[#s + 1] = string.char(space:read_u8(addr + i * 8))
end
return table.concat(s)
end
emu.register_frame_done(function()
frames = frames + 1
if frames == ENDF - 1 and not checked then
checked = true
local prog = manager.machine.devices[':maincpu'].spaces['program']
local got = {}
local bad = 0
for i = 0, N - 1 do
got[i] = prog:read_u32(BASE + i * 0x20)
if got[i] ~= expect[i] then
bad = bad + 1
end
end
io.write(string.format("M6 varargs:"))
for i = 0, N - 1 do
io.write(string.format(" %08X", got[i]))
end
io.write("\n")
local out = read_string(prog, OUT, #want_out)
print(string.format("M6 varargs out: '%s'", out))
if out ~= want_out then
print(string.format("M6 varargs: output got '%s' want '%s'",
out, want_out))
bad = bad + 1
end
if bad == 0 then
print("M6 VARARGS MAME: PASS")
else
for i = 0, N - 1 do
if got[i] ~= expect[i] then
print(string.format(
"M6 varargs: marker %d got %08X want %08X",
i, got[i], expect[i]))
end
end
print("M6 VARARGS MAME: FAIL")
end
end
end, "varargs-check")
Loaded 100 of 323 files, more files were not shown because too many files have changed in this diff. Show more