Execution Plan for LLVM AOT Backend Integration
First deliverable: On Linux x86-64, compile a real YaoXiang source program into an ELF executable. Run it on a comparable system without LLVM or the YaoXiang VM; it must both compute the correct results and identify the source-code location when an error occurs. Producing LLVM IR text alone does not count as completion.
Status: pending review; not scheduled. RFC-018 has accepted the direction of LLVM ahead-of-time compilation (AOT); tracking issue #134 is the entry point for this work. This document proposes a delivery sequence; it does not register or start implementation tasks. RFC-039 separates backend selection from compiler refactoring: a prototype need not wait for the entire refactoring to finish, and production code generation must not take over P7's SSA work.
Where It Fits
The following table records facts that must be revalidated when work begins. Source links are pinned to the same Git revision; they are not a requirement for the future directory layout.
| Existing boundary | Constraints on the implementation |
|---|---|
| Driver phase table: single-file programs are monomorphized after IR generation; multi-file programs first merge their IR and then handle whole-program instantiation requests. | Capture the final ModuleIR after compilation succeeds and its obligations have been discharged. The project uses its existing multi-file orchestration and does not introduce a separate parsing or type-checking pipeline. Do not invoke LLVM when the frontend fails. |
The default output of the build command is .42; the bytecode generator consumes module IR; Executor consumes bytecode and executes it. | Branch bytecode and LLVM from the same module IR. LLVM neither infers types from .42 nor implements the bytecode execution interface. |
Slot generation uses Int(64) to fill temporary slots; the IR validator interprets the current jump by flattened instruction index. In the modulo snapshot, the same slot first holds a string and later holds an integer. | A slot number does not identify a single-assignment value, and the padding type is not proof of a type. Passing verify_loose does not mean that arbitrary functions can be translated. The existing snapshot normalizer is used only for printing; it is not a compilation pass that eliminates stack instructions. |
| The module IR already carries the initialization sequence, entry point, source files, FFI bindings, release instructions, and spawn execution plan; the runtime interface uses Rust task closures. | Shared semantics remain determined by the original module. The native backend is responsible only for representation, calling conventions, and emission; neither Rust closures nor the VM's RuntimeValue are the native program's binary interface (ABI). |
Select the output artifact at the L1 orchestration layer and manage Inkwell, LLVM modules, optimization, and object files inside L4's backends::llvm. L2/L3 introduce no LLVM types; L4 does not look back into the AST or type checker. Do not invent a generic backend trait in advance. The first batch does not include JIT, cross-platform cross-compilation, default backend switching, or performance promises.
What to Confirm Before Starting
| Decision point | Recommended approach and cost | Alternative and boundaries |
|---|---|---|
| Public entry point | Explicitly select LLVM in the existing build command, for example yx build demo.yx --backend llvm (proposed syntax; currently unavailable). Preserve the VM behavior and default .42 output of yx run; return a clear error when a backend that has not been enabled is requested. The cost is maintaining an additional output format. | Changing the default directly could eliminate the need for an option, but existing scripts would receive a different format and require a new toolchain. This is a breaking change, which this plan does not undertake. |
| Toolchain and first platform | Adopt Inkwell as specified by RFC-018, initially selecting x86_64-unknown-linux-gnu. Enable the optional Cargo feature on native hosts only; pin and validate a compatible combination of Inkwell, its LLVM bindings, and the system LLVM. The existing Linux CI can be reused, but this does not establish support for other ABIs. | Rolling out multiple targets at once can expose platform differences earlier, but the first error may be difficult to attribute to language translation, the runtime, or the platform ABI. Validate each target separately afterward. |
| Relationship with P7 | First validate the toolchain on a decidable subset; production control-flow translation waits for the shared types and SSA. The cost is that the prototype explicitly rejects some legal programs. | Waiting until all of P7 is complete before starting avoids temporary adaptations, but delays discovery of linking and release risks until the supported scope expands. Do not choose to recreate the entire type and SSA systems inside the LLVM backend: that would create a second set of semantics. |
Maintainers should first confirm the scope of the first batch, the CLI contract, and cross-task prerequisites, and then register the work under the RFC-018 tracking item. The batch names below describe only dependency relationships; they do not indicate that the batches have been approved or completed.
Review Before Registering the First Batch of Tasks
Run the following read-only commands at the repository root. The first two locate the actual compilation split point and IR validation entry points; the last two check the build arguments and test budget supported by the batch tool. If the phase table or validation contract has changed, update the task prerequisites first rather than copying this page's baseline revision.
git grep -n -e 'const SINGLE_FILE_STAGES' -e 'const MULTI_FILE_STAGES' -- src/driver/program.rs
git grep -n -e 'pub fn verify_loose' -e 'pub fn verify_ssa' -- src/middle/ir/verify.rs
python scripts/dev/scratch.py build --help
python scripts/dev/testsuite.py planImplementation Order and Deliverables
Dependency chain: toolchain → native sample; once both the native sample and shared SSA are ready, proceed to production code generation. From there, first settle the lifetimes of native values and resources, then connect FFI and spawn. For each batch, the implementer delivers the artifacts and reproduction steps, and an independent validator reviews the go/no-go criteria. Differential corpus testing begins with the first executable rather than being deferred until release.
1. Pin the Build Environment and Isolate LLVM Dependencies
- Implementation: The build owner selects compatible versions and locks the dependencies. Record the host, target triple, LLVM version, system linker driver, and the locations and acquisition methods for the target runtime libraries. Use LLVM's
TargetMachineto set the module's target triple andDataLayout; do not derive object layout from the sizes of host Rust types. - Deliverables: Two reproducible build channels. The channel without LLVM builds the default CLI, VM, and Wasm Playground; the channel with LLVM builds the optional backend. The existing CI uses
--all-features; those jobs explicitly provision the pinned LLVM and do not remove the feature merely to pass. - Release criteria: An environment without LLVM can complete the default build; an environment with LLVM can validate a module, emit an object file, link, and run. Also verify the failure modes for a missing linker and an LLVM major-version mismatch, making it possible to distinguish environment errors from source-program errors. The batch build tool currently builds only the default engine; first register and approve explicit feature support, then verify the optional build according to the measurement procedure, and do not create a separate build command that bypasses the batch tool.
2. Deliver the First Real Source Program Without Waiting for P7
- Input: Have the existing Driver compile a single-file script. Accept only data flows whose types can be determined from constants, known function signatures, and straight-line instructions. Support
Int,Bool, direct calls, returns, top-level initialization, and the minimal assertion entry point needed to observe results. Do not promise general standard-library support. - Generation: First use
verify_looseto rule out structural errors, then check the type justification for each instruction in this subset. Declare functions first, then translate function bodies and module initialization. For scripts, invoke only the initialization sequence; do not look upmainagain by name. Run LLVM module verification, object-file emission, and linking in sequence. Deliver the final artifact only after linking succeeds; on failure, do not overwrite the last successful artifact. - Positive and negative examples: Have the script pass arguments to an arithmetic function, then compare the return value through the existing
std.assert.assertcontract. It exits normally when the expected value is correct; after deliberately changing the expected value to an incorrect one, both the VM and the native program must report E6005 at the same source line. Resolve assertion symbols through existing export bindings; do not special-case the compiler based on the sample filename. Do not temporarily redefine a source program's function return value as the process exit code. - Stop condition: If the input contains an unknown type, an unproven indirect call, or an unsupported reachable instruction, the build must fail explicitly and identify the source. Do not emit a partial artifact or fall back to the VM. If a region cannot be proven unreachable, do not skip it either. A prototype failure is a capability boundary; it does not change whether the same program is valid on the VM.
- Release criteria: Produce VM, native O0, and native O2 results from the same source. Run the native artifact in an environment containing only the target system's base libraries; it must not include LLVM, a compiler, or a bytecode interpreter. Hand-assembling an LLVM module, checking only for exit code 0, or merely saving a
.llfile cannot replace this validation.
3. Integrate with the Production Shared IR and Extend to Control Flow and Multi-File Programs
Prerequisites are determined by artifacts, not dates. Check against the SSA design and the P7 work plan: the compiler's actual output must provide per-value types, distinguish writable storage from single-assignment temporaries, and represent predecessor and merge values; verify_ssa must pass on production IR containing branches and loops. When zero-quantifier parameters or proof fields are involved, also check the corresponding erasure contract; do not assume that all original generic forms have been erased. If any condition is missing, retain only the scope of batch 2 and do not broaden the support declaration.
- Create basic blocks first, then translate instructions and fill in the predecessor inputs for
phi. Map SSA values directly to LLVM values, and use storage for addressable mutable locals. For stack instructions that remain reachable, check the stack depth and element types along the control flow before eliminating them; reject inconsistent predecessors, and do not allow invalid IR into the optimizer. - Declare call targets according to their signatures after monomorphization. The project uses the qualified names, global slots, and initialization order provided by the orchestrator. Bin first performs initialization and then calls the specified entry point; Script does not implicitly call
main, even if it defines one. Errors in dependent module initialization use that module's file identity, rather than always being attributed to the entry file. - Use the same source to validate both branches, a loop back-edge, a direct cross-module generic call, import initialization order, and exactly one explicit call to
mainfrom a script. Use one erroneous input to verify the diagnostic file and line. Once the production path covers the prototype, remove the prototype-specific adaptations; do not retain two sets of instruction translators.
4. Link the Native Runtime, Then Add FFI and Spawn
| Delivery slice | Implementation boundary | Acceptance example |
|---|---|---|
| Values, closures, and resources | Statically link the required runtime through a narrow C ABI. Define the byte length and ownership of strings, container layouts, closure environments, and the component responsible for releasing them. Consume IR operations such as Drop, RcNew, and ArcNew; do not redo ownership analysis in the backend. Basis: Ownership Design. | After a closure leaves its defining scope, it can still read captured values; a moved value is not dropped twice; resources on normal return, early return, and ? propagation are each released exactly once in the prescribed order. |
| Foreign function interface (FFI) | Consume bindings and determined signatures, distinguishing standard-library handlers from external C symbols. Convert parameters and return values according to the target ABI; do not treat Rust enum or closure layouts as C layouts. Basis: FFI Core Mechanism. | Compile a C test library with a genuine signature using the same target toolchain, and pass values back and forth between YaoXiang and C. Cover null pointers, string boundaries, and missing symbols; merely verifying that a simple call does not crash is insufficient. |
| Spawn | Consume the ExecutionPlan carried by Spawn and SpawnFromList, and pass each task's entry point, environment, and dependencies to the scheduler. Sequential code does not start the scheduler. Basis: Runtime Architecture, Concurrency Semantics. | Tasks with dependencies consume results in order, conflicting resources are never accessed concurrently, and task failures propagate to the caller. For tasks without dependencies, verify only the allowed outcomes; do not treat one observed thread-scheduling order as the semantics. |
Each slice starts from the IR produced by the upstream producer. If required layout, type, or release facts are missing, first open a work item in the layer that owns that fact; do not fill in the interface using a guessed layout. The runtime ABI is treated as an internal interface at this stage, with no promise of third-party compatibility for users who link it themselves.
How to Determine Equivalence Between the Two Backends
The validation owner compares VM / native O0 / native O2 at the same revision, target, and input. Reuse the three expectation categories from the corpus probe: normal behavior, compile errors, and runtime errors. Record compilation exit status and runtime exit status separately, to avoid miscounting “did not compile” as “failed to run as expected.” Do not skip any corpus item that is already supported.
| Errors to guard against | Input and criterion |
|---|---|
| Integer semantics turn into LLVM defaults | Use function arguments to force runtime computation: -7 % 3 == 2, 7 % -3 == -2; division by zero reports E6001, adding one to the largest signed integer reports E6007, and dividing the smallest value by -1 follows the overflow diagnostic path. Do not emit sdiv without protection or treat bare srem as mathematical modulo. Ready-made comparisons: Modulo, Division by Zero, Overflow. |
| Optimizations change behavior | Compare the observable values and error paths of O0 and O2 with those of the VM. When expanding floating-point support, add NaN, signed zero, and mixed numeric operations; do not enable fast-math assumptions that would change these results. Passing the LLVM verifier only establishes structural validity. |
| Normalization masks ordering or location errors | Compare exit codes, output, and the code, file, and line of structured diagnostics; do not compare translated text, machine code, or the text of an entire LLVM IR. The existing probe sorts standard output line by line; use ordered event records or final-state assertions for ordered side effects such as initialization and destruction. |
| Mistakenly treating “unsupported” as “passed” | For each scope expansion, record the supported corpus, expected-success count, expected-error count, unsupported features, and the implementation batch corresponding to each. If the backend rejects an already supported item, that is a regression; it must not be removed from the set merely to turn the gate green. Programs already rejected by the frontend must produce no file on either build path. |
Follow the snapshot, corpus, and resource-budget rules in the equivalence criteria and implementer's manual. Prove that key probes are effective through controlled mutation; for example, replace mathematical modulo with a truncating remainder, and the negative-operand case must fail. When adding a native path, do not update the VM baseline merely because the AOT result differs. If the language specification conflicts with the VM, record a minimal source program and correct the dispatch according to the intended semantics; do not let the backend adjudicate language semantics by itself.
Release and Rollback
- Label prototypes, limited previews, and full support separately. A prototype proves only a single-platform path. A preview lists the supported scope and explicitly rejected items in the release notes. Before fully supporting a target, reconcile each item against RFC-018's commitments, including standard-library dependencies, reflection metadata, and runtime modes claimed as supported; an undelivered item does not count as complete.
- Accept each target separately. After the Linux ELF passes, validate the COFF format for Windows x64 MSVC and the Mach-O format for macOS separately. Actually compile, link, and run each target on the corresponding system; inspect the architecture, dynamic-library dependencies, and FFI calling conventions. Validate
x86_64-pc-windows-msvcfor Windows; recordx86_64-apple-darwinandaarch64-apple-darwinfor macOS separately. Track compilation time, artifact size, startup time, and runtime time separately; make no speedup claims without measured values. - Actions on failure. Roll back unreleased slices by batch; do not release a platform that has not passed the gate, and retain the default VM build. A released explicit option must continue to produce clear diagnostics and must not silently fall back to bytecode. Changing the default artifact, changing the results of existing successful programs, exposing a public ABI, or changing a promised ABI each require separate review.
- Handoff evidence. For each batch, link the relevant commit or PR, publicly reproducible source code, toolchain versions, target triple, commands, and expected and actual results. An independent validator reruns the positive and negative examples before the supported scope is expanded. Approval of the documentation does not mean that the schedule or release has been approved.
