Introduction
Architectura (archsem) is a standalone, IR-agnostic instruction-semantics framework. It captures what machine instructions and bytecode operations do—as typed, verified data where possible, and as generic Rust where necessary—decoupled from any single target intermediate representation, decompiler, emulator, or binary-analysis framework.
Instead of hardcoding instruction semantics into LLVM IR, a custom SSA graph, or an emulator loop, Architectura defines a single neutral trait—IrEmitter—and expresses instruction behavior in terms of pure data micro-op programs (SemProgram) authored in the Asem domain-specific language (semantics/).
┌─▶ archsem-ir (RtlEmitter / Function CFG / SSA) ─▶ archsem-simplify / archsem-symex
│
Machine / Bytecode ─────┼─▶ archsem-llvm (LlvmEmitter) ──────────────────▶ LLVM IR
(Decoder + SemProgram) │
├─▶ archsem-ref (ReferenceEmitter) ──────────────▶ Bounded Concrete Oracle
│
└─▶ archsem-record (ActionRecorder) ─────────────▶ Serializable Action Stream
Design Philosophy
-
Semantics as Verified Data (
SemProgram) Most instruction semantics live as pure, staticSemProgramtables of typedMicroOpinstructions operating over a finite value-slot array. An interpreter (run/run_checked) executes aSemProgramagainst anyIrEmitter, calling the exact same primitive methods a hand-written handler would—after running the canonical semantic verifier at the trust boundary. -
Control Flow Is Returned, Never Emitted (
ControlEffect/SemanticControl) AnIrEmitterhas nobr,jmp, orcreate_blockmethods. Basic-block boundaries, CFG recovery policies, and loop structures differ across emulators, static analyzers, and recompilers. Every semantic execution returns its terminal outcome (SemanticControl<E::Value>) so the consumer's own driver builds whatever CFG or dispatch loop it needs. -
Explicit
ChoiceInstead ofundefor Poison Architectura never lowers architectural uncertainty (undefined flags afterDIV, entropy instructions, implementation-defined behavior, uninitialized state) to backendundefor LLVM poison. Instead, uncertainty is modeled as a first-class, typed, width-exactChoicecarrying aChoiceKind, aChoiceScopecorrelation lifetime, an optionalChoiceKey, and a validChoiceDomain. -
Strict Separation of Providers and Consumers Architectura is a semantics provider, not a closed binary-analysis framework. It provides exact register/flag dependencies, explicit predicates, indirect-target expressions, ordered instruction-local memory/fault events, caller-rooted backward slicing, and solver-neutral proof obligations. Taint policies, alias heuristics, ABI/OS/syscall emulation, dispatcher recovery, and SMT solver invocation remain outside
archsem. -
Fidelity Is Explicit, Never Approximated Silently Every semantic route carries a multidimensional
SemanticFidelityrecord (coverage, determinism, observable facets, validation evidence, and reason codes). Instructions without admitted semantics fail closed with a typed unsupported boundary rather than silently becoming no-ops or unconstrained outputs.
Comparison with Other Semantic Frameworks
| System | Primary Representation | Control Flow | Nondeterminism / UB | Target Independence |
|---|---|---|---|---|
Architectura (archsem) | SemProgram micro-ops + IrEmitter trait + archsem-ir RTL | Returned as SemanticControl; CFG driver is separate | Typed Choice with kind, scope, key, and domain; partial ops explicit | Zero target-IR deps in archsem-core; backends implement IrEmitter or consume archsem-ir |
| Remill | C++ intrinsic templates compiled to LLVM bitcode | Handled by caller / Anvill | Relies on LLVM semantics / __remill_undefined_* intrinsics | Tightly coupled to LLVM IR |
| Ghidra P-Code | Sleigh specifications compiled to p-code ops | Embedded intra-instruction branches + p-code relative jumps | UNIQUE / undefined op semantics; userops (CALLOTHER) lack typed contracts | Coupled to Ghidra address spaces and p-code VM |
| BAP BIL | Algebraic BIL statements in OCaml | Intra-instruction jumps (jmp, cjmp) | Unknown expressions | Coupled to BAP / OCaml ecosystem |
| Valgrind VEX | C IRStmt / IRExpr superblocks | IRJumpKind exits + dirty helpers | Implicit via helper calls | Designed for dynamic instrumentation |
| QEMU TCG | Tiny Code Generator ops | TCG branches / labels inside TB | Architecture helpers in C | Designed for JIT emulation |
Architectura adopts the Remill/Anvill split between instruction semantics and program restructuring, Ghidra P-Code's explicit address spaces and provenance, Sail/ASL's strong bitvector width discipline and explicit nondeterminism, and WebAssembly's mandatory structural validator before execution.
Naming Guide
| Name | Meaning |
|---|---|
| Architectura | The overall repository and project (https://github.com/valeria-org/architectura). |
archsem | The framework name, crate prefix (archsem-core, archsem-ir, ...), and C/C++ library target (libarchsem / archsem::archsem). |
| Asem | "Architectura Semantics" — the .asem source language used to author instruction semantics and machine-code form catalogs, compiled by archsemc. |
valeria-org | The public GitHub organization hosting Architectura and its companion decoder/solver crates (fARM64, fWASM, fLUA, fNET, cildec, bitwright). |
License
Architectura is open-source software licensed under the MIT License (Copyright (c) 2026 valeria-org).
[!NOTE] The bounded symbolic execution crate
archsem-symex(and the optionalsymex/ARCHSEM_SYMEX=ONfeature inarchsem-capi) depends onbitwright, which is licensed under PolyForm-Noncommercial-1.0.0 (free for noncommercial use; commercial use requires a license from its licensor). Every other crate in the workspace is pure MIT.
Rust Quickstart
This chapter walks through four complete, runnable Rust workflows using Architectura's public APIs:
- Decoding, lifting, and simplifying a single x86-64 instruction (
add rax, rbx). - Discovering and lifting a reachable control-flow graph (
lift_reachable_stateless/Function). - Executing an instruction concretely against the independent reference oracle (
archsem-ref). - One-call CFG lifting for WebAssembly (
archsem-wasm) and EVM (archsem-evm).
[!IMPORTANT] MSRV & Feature Flags: Architectura requires Rust 1.88+ (Edition 2024).
archsem-x86keeps its decoder adapter behind theicedfeature (features = ["iced"]).archsem-arm64keeps its decoder adapter behind thefarm64feature (features = ["farm64"]).- Bytecode crates (
archsem-wasm,archsem-evm,archsem-cil,archsem-lua) enable their default frontend features out of the box.
1. Lift and Simplify a Single x86-64 Instruction
Add archsem-core, archsem-ir, archsem-simplify, and archsem-x86 (with iced) to Cargo.toml:
[dependencies]
archsem-core = "0.1"
archsem-ir = "0.1"
archsem-simplify = "0.1"
archsem-x86 = { version = "0.1", features = ["iced"] }
The bytes [0x48, 0x01, 0xd8] encode add rax, rbx in 64-bit mode:
use std::error::Error; use archsem_core::{ lookup, BinaryMode, DecodeContext, Decoder, EnabledFeatures, LiftCtx, NoDecodeState, NoState, ResourceLimits, }; use archsem_ir::RtlEmitter; use archsem_simplify::{simplify_fragment, SimplifyOutcome}; use archsem_x86::decode::{sem_index, IcedX86Decoder}; use archsem_x86::{profile_of, LONG64, X86_MANIFEST, X86_SEMANTICS}; fn main() -> Result<(), Box<dyn Error>> { let bytes = [0x48, 0x01, 0xd8]; // add rax, rbx let va = 0x401000; // 1. Construct a validated DecodeContext for 64-bit x86. let decode_ctx = DecodeContext::for_manifest( &X86_MANIFEST, LONG64, EnabledFeatures::empty(), NoDecodeState, &ResourceLimits::STANDARD, )?; // 2. Decode bytes into an IcedInsn and resolve its semantic table entry. let decoded = IcedX86Decoder.decode(&bytes, va, &decode_ctx)?.instruction; let index = sem_index(decoded.instruction()).expect("ADD has a semantic row"); let entry = lookup(X86_SEMANTICS, index).expect("table index in bounds"); // 3. Lift into neutral RTL via RtlEmitter. let mut rtl = RtlEmitter::new(); let mut arch_state = NoState; let control = { let mut lift_ctx = LiftCtx { emitter: &mut rtl, arch: &X86_MANIFEST, mode: LONG64, profile: profile_of(LONG64).expect("LONG64 profile"), insn_va: decoded.address(), next_va: decoded.next_address(), image: None, binary_mode: BinaryMode::Image, arch_state: &mut arch_state, }; archsem_x86::lift(&mut lift_ctx, &decoded, entry)? }; let mut fragment = rtl.finish(control); fragment.validate()?; let before = fragment.nodes.len(); // 4. Run effect-aware integer simplification. let report = simplify_fragment(&mut fragment)?; assert_eq!(report.outcome, SimplifyOutcome::Complete); println!( "lifted {} ({} -> {} RTL nodes)", entry.mnemonic, before, fragment.nodes.len() ); Ok(()) }
fragment.nodes contains typed SSA definitions (Const, ReadReg, BinOp, Compare, Select, etc.) and ordered side effects (WriteReg, Load, Store, TrapIf, ...), while fragment.control preserves the terminal SemanticControl<ValueId>.
2. Reachable CFG Lifting (lift_reachable_stateless)
To discover and lift a complete function CFG from an in-memory image, implement archsem_core::ImageReader and pass it to archsem_ir::lift_reachable_stateless:
use std::error::Error; use archsem_core::{ lookup, DecodeContext, EnabledFeatures, ImageReader, InsnView, LiftError, NoDecodeState, ResourceLimits, UnsupportedSemanticsReason, }; use archsem_ir::{lift_reachable_stateless, CfgLiftConfig, Completion}; use archsem_x86::decode::{sem_index, IcedX86Decoder}; use archsem_x86::{LONG64, X86_MANIFEST, X86_SEMANTICS}; struct SliceImage<'a> { base: u64, bytes: &'a [u8], } impl ImageReader for SliceImage<'_> { fn read_bytes(&self, va: u64, out: &mut [u8]) -> bool { let Some(offset) = va.checked_sub(self.base).and_then(|o| usize::try_from(o).ok()) else { return false; }; let Some(end) = offset.checked_add(out.len()) else { return false; }; let Some(slice) = self.bytes.get(offset..end) else { return false; }; out.copy_from_slice(slice); true } } fn main() -> Result<(), Box<dyn Error>> { // 0x1000: test edi, edi ; je +5 ; mov eax, 1 ; ret let code = [ 0x85, 0xff, 0x74, 0x05, 0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3, ]; let base = 0x1000; let image = SliceImage { base, bytes: &code }; let decode_ctx = DecodeContext::for_manifest( &X86_MANIFEST, LONG64, EnabledFeatures::empty(), NoDecodeState, &ResourceLimits::STANDARD, )?; let config = CfgLiftConfig { address_range: Some(base..base + code.len() as u64), ..CfgLiftConfig::default() }; let outcome = lift_reachable_stateless( &IcedX86Decoder, &image, &X86_MANIFEST, base, decode_ctx, &config, |insn, ctx| { let idx = sem_index(insn.instruction()).ok_or_else(|| { LiftError::unsupported("unknown", UnsupportedSemanticsReason::ExplicitlyUnsupported) })?; let entry = lookup(X86_SEMANTICS, idx).ok_or_else(|| { LiftError::unsupported("unknown", UnsupportedSemanticsReason::ExplicitlyUnsupported) })?; archsem_x86::lift(ctx, insn, entry) }, ) .map_err(|failure| failure.error)?; assert_eq!(outcome.function.completion(), Completion::Complete); println!( "discovered {} blocks ({} instructions)", outcome.stats.blocks, outcome.stats.instructions ); Ok(()) }
Once lifted, you can run function-level normalization (outcome.function.optimize(...)), build register SSA (outcome.function.register_ssa(&X86_MANIFEST)), or replay into a backend (outcome.function.replay_register_ssa(...)).
3. Concrete Reference Execution (archsem-ref)
archsem-ref provides an independent, bounded concrete evaluator. You drive it using ConcreteEnvironment and ReferenceEmitter:
use std::error::Error; use archsem_core::{ lookup, BinaryMode, DecodeContext, Decoder, EnabledFeatures, LiftCtx, NoDecodeState, NoState, ResourceLimits, }; use archsem_ref::{ BitVector, ConcreteEnvironment, ReferenceCompletion, ReferenceEmitter, ReferenceEmitterConfig, }; use archsem_x86::decode::{sem_index, IcedX86Decoder}; use archsem_x86::{profile_of, regmap, LONG64, X86_MANIFEST, X86_SEMANTICS}; fn main() -> Result<(), Box<dyn Error>> { let bytes = [0x48, 0x01, 0xd8]; // add rax, rbx let decode_ctx = DecodeContext::for_manifest( &X86_MANIFEST, LONG64, EnabledFeatures::empty(), NoDecodeState, &ResourceLimits::STANDARD, )?; let decoded = IcedX86Decoder.decode(&bytes, 0x1000, &decode_ctx)?.instruction; let entry = lookup(X86_SEMANTICS, sem_index(decoded.instruction()).unwrap()).unwrap(); // Seed initial register state. let mut env = ConcreteEnvironment::new(); let rax = regmap::gpr(regmap::RAX, 64); let rbx = regmap::gpr(regmap::RBX, 64); env.set_register(rax, BitVector::from_u64(10, 64)?)?; env.set_register(rbx, BitVector::from_u64(32, 64)?)?; // Lift directly into ReferenceEmitter. let mut emitter = ReferenceEmitter::new(&mut env, ReferenceEmitterConfig::default()); let mut arch_state = NoState; let vm_result = { let mut lift_ctx = LiftCtx { emitter: &mut emitter, arch: &X86_MANIFEST, mode: LONG64, profile: profile_of(LONG64).unwrap(), insn_va: decoded.address(), next_va: decoded.next_address(), image: None, binary_mode: BinaryMode::Image, arch_state: &mut arch_state, }; archsem_x86::lift(&mut lift_ctx, &decoded, entry) }; let execution = emitter.finish_vm(vm_result); assert!(matches!(execution.completion, Ok(ReferenceCompletion::Control(_)))); let final_rax = env.register(rax).expect("RAX written"); assert_eq!(final_rax.to_u64(), Some(42)); println!("RAX = {}", final_rax.to_u64().unwrap()); Ok(()) }
4. One-Call Bytecode CFG Lifting (Wasm & EVM)
Unlike native byte streams, bytecode frontends expose one-call whole-function or whole-contract CFG lifting helpers.
WebAssembly (archsem-wasm)
#![allow(unused)] fn main() { use archsem_core::ResourceLimits; use archsem_ir::Completion; use archsem_wasm::{lift_function_cfg, WasmModule}; fn lift_wasm_fn(wasm_bytes: &[u8], fn_index: u32) -> Result<(), Box<dyn std::error::Error>> { let module = WasmModule::parse(wasm_bytes)?; let lifted = lift_function_cfg(&module, fn_index, &ResourceLimits::STANDARD)?; assert_eq!(lifted.outcome.function.completion(), Completion::Complete); println!("Wasm function {fn_index}: {} blocks", lifted.outcome.function.blocks().len()); Ok(()) } }
Ethereum Virtual Machine (archsem-evm)
#![allow(unused)] fn main() { use archsem_core::ResourceLimits; use archsem_evm::{lift_code_cfg, EvmCode, EvmFork}; use archsem_ir::Completion; fn lift_evm_contract(bytecode: &[u8]) -> Result<(), Box<dyn std::error::Error>> { let code = EvmCode::parse(bytecode, EvmFork::default())?; let lifted = lift_code_cfg(&code, &ResourceLimits::STANDARD)?; assert_eq!(lifted.outcome.function.completion(), Completion::Complete); println!("EVM contract: {} blocks", lifted.outcome.function.blocks().len()); Ok(()) } }
For additional runnable target-neutral Rust examples (direct emission, ActionRecorder -> RtlEmitter -> simplify -> replay, bounded symbolic execution, proof obligations, and runtime-loaded JSON programs), see the archsem-examples crate (cargo run -p archsem-examples --example <name>).
C and C++ Quickstart
archsem-capi exposes Architectura's lifting, CFG discovery, SSA analysis, concrete execution, and optional symbolic execution to C and C++ consumers via:
- C ABI header:
archsem-capi/include/archsem.h(ABI version 4, minor version 9) - Header-only C++17 wrapper:
archsem-capi/include/archsem.hpp - CMake target:
archsem::archsem
archsem-capi links archsem-x86 (iced), archsem-arm64 (farm64), archsem-evm, archsem-cil, archsem-wasm, archsem-lua, and archsem-ref (arm64-guest) into a single native library (libarchsem / archsem.lib / archsem.dll).
Building with CMake
In your CMakeLists.txt:
cmake_minimum_required(VERSION 3.19)
project(my_tool LANGUAGES C CXX)
add_subdirectory(path/to/architectura/archsem-capi archsem)
target_link_libraries(my_tool PRIVATE archsem::archsem)
CMake invokes cargo automatically (Rust 1.88+ must be on PATH) and propagates include directories, C++17 requirements, and platform system libraries.
CMake Options
| Option | Default | Description |
|---|---|---|
ARCHSEM_SHARED | OFF | Build and link a shared library (libarchsem.so / .dylib / archsem.dll) instead of static |
ARCHSEM_SYMEX | OFF | Enable bounded symbolic execution (archsem_symex_*). Links bitwright (PolyForm-Noncommercial-1.0.0) |
ARCHSEM_CARGO_PROFILE | release | Cargo build profile (release, dev, etc.) |
ARCHSEM_CARGO_TARGET_DIR | Build tree | Override Cargo's target directory |
ARCHSEM_BUILD_EXAMPLES | ON when top-level | Build C++ examples and register ctest targets |
Building Directly with Cargo
cargo build --release -p archsem-capi
c++ -std=c++17 -I archsem-capi/include my_tool.cpp target/release/libarchsem.a -lpthread -ldl -lm -lrt -lutil
On Windows (MSVC), link archsem.lib along with kernel32, advapi32, ntdll, userenv, ws2_32, bcrypt, and dbghelp (handled automatically by CMake).
C++17 Quickstart (archsem.hpp)
The C++17 wrapper provides RAII ownership (Lifter, Fragment, Function, Machine), range-based views (Node, Block, CfgTarget), and throws archsem::Error on failure (with non-throwing try_lift / try_discover / try_lift_function alternatives returning archsem::Result).
#include "archsem.hpp"
#include <cstdint>
#include <iostream>
#include <vector>
int main() {
// 1. Lift a single x86-64 instruction: add rax, rbx (48 01 d8)
archsem::Lifter lifter(archsem::Arch::X86_64);
archsem::Fragment add = lifter.lift({0x48, 0x01, 0xd8}, 0x401000);
std::cout << add.text();
for (archsem::Node node : add.nodes()) {
if (node.kind() == archsem::NodeKind::WriteReg) {
std::cout << "writes: " << node.reg().name() << '\n';
}
}
// 2. Discover and optimize a function CFG from an in-memory buffer.
const std::uint8_t code[] = {
0x85, 0xff, // test edi, edi
0x74, 0x05, // je +5
0xb8, 0x01, 0x00, 0x00, 0x00, // mov eax, 1
0xc3, // ret
};
archsem::Lifter opt_lifter(archsem::Arch::X86_64, {/*optimize=*/true});
archsem::Function fn = opt_lifter.lift_function(code, 0x1000, 0x1000);
for (archsem::Block block : fn.blocks()) {
std::cout << "block " << block.id() << " @ 0x" << std::hex << block.start_address() << std::dec << '\n';
}
// Re-optimize with ABI exit liveness and fault-boundary assumptions.
auto abi_opts = archsem::OptimizeOptions::abi().assume_fault_state_unobserved();
archsem::Function lean = fn.optimize(abi_opts);
// 3. Concrete execution with real register aliasing.
archsem::Machine machine(archsem::Arch::X86_64);
machine.load(0x1000, code);
machine.set("edi", 0);
machine.set("rsp", 0x8000);
machine.write(0x8000, std::array<std::uint64_t, 1>{0xdead0000});
archsem::ExecutionResult res = machine.run(lifter, 1000, {0xdead0000});
std::cout << "exit=" << archsem::to_string(res.exit)
<< " rax=" << machine.get("rax") << '\n';
return 0;
}
Symbolic Execution in C++ (ARCHSEM_SYMEX=ON)
When built with -DARCHSEM_SYMEX=ON (or --features symex):
archsem::SymexOptions options;
options.memory = archsem::SymMemory::Symbolic;
options.registers = {{"rsp", {0x8000}}};
archsem::SymbolicReport report = archsem::symex(lean, options);
for (const archsem_sym_path &path : report.paths()) {
if (auto rax = report.value(path, "rax")) {
std::cout << "path rax = " << rax->text() << '\n';
}
}
[!WARNING] Enabling
ARCHSEM_SYMEX=ONlinksbitwright, which is licensed under PolyForm-Noncommercial-1.0.0. KeepARCHSEM_SYMEX=OFFif you require a purely MIT-licensed binary.
C ABI Quickstart (archsem.h)
The C ABI uses explicit heap-owned handles (*_free), archsem_status return codes, and optional archsem_error ** out-parameters:
#include "archsem.h"
#include <stdio.h>
int main(void) {
archsem_error *err = NULL;
archsem_lifter *lifter = NULL;
archsem_fragment *frag = NULL;
if (archsem_lifter_new(ARCHSEM_ARCH_X86_64, 0, &lifter, &err) != ARCHSEM_STATUS_OK) {
fprintf(stderr, "error: %s\n", archsem_error_message(err));
archsem_error_free(err);
return 1;
}
const uint8_t insn[] = {0x48, 0x01, 0xd8}; /* add rax, rbx */
if (archsem_lift_instruction(lifter, insn, sizeof(insn), 0x401000, &frag, &err) != ARCHSEM_STATUS_OK) {
fprintf(stderr, "lift failed: %s\n", archsem_error_message(err));
archsem_error_free(err);
archsem_lifter_free(lifter);
return 1;
}
size_t node_count = 0;
const archsem_node *nodes = archsem_fragment_nodes(frag, &node_count);
for (size_t i = 0; i < node_count; ++i) {
if (nodes[i].kind == ARCHSEM_NODE_WRITE_REG) {
printf("write reg: %s (%u bits)\n", nodes[i].reg.name, nodes[i].reg.bits);
}
}
archsem_fragment_free(frag);
archsem_lifter_free(lifter);
return 0;
}
ABI Versioning, Threading, and Ownership
- Ownership: Top-level handles (
archsem_lifter,archsem_fragment,archsem_function,archsem_machine,archsem_register_ssa,archsem_memory_ssa,archsem_symbolic_report,archsem_*_module,archsem_error) are caller-owned and must be freed via*_free. All returned node/string/slice pointers are borrowed from the owning object. - Thread Safety:
Lifter,Fragment,Function,SymbolicReport, and bytecode module handles are immutable after creation and safe to read concurrently from multiple threads; oneLiftercan lift across multiple threads simultaneously.Machineis single-threaded. - ABI Stability:
archsem_abi_version()returns the major ABI revision (4) andarchsem_abi_minor_version()returns the compatible minor revision (9). Options structs begin withuint32_t struct_sizefor forward/backward compatibility. Unknown node, control, terminator, or exit constants added in future minor releases should be treated as unknown rather than fatal errors. - Panic Safety: No Rust panic crosses the FFI boundary; panics are caught and surfaced as
ARCHSEM_STATUS_INTERNAL.
Workspace & Crate Map
Architectura is organized as a modular Cargo workspace (edition = "2024", MSRV 1.88). A plain cargo build or cargo check operates only on default-members—the environment-independent portable crates—so checking the workspace never unexpectedly pulls LLVM or optional external tooling.
Crate Reference
Core & IR Layers
| Crate | Purpose | Default Features | Optional Features | License |
|---|---|---|---|---|
archsem-core | IrEmitter trait, SemProgram micro-op VM & verifier, ArchManifest, DecodeContext, ControlEffect / SemanticControl, Choice, OpaqueIntrinsic, canonical wire encoder | [] | serde (RON/JSON artifact loading & serialization) | MIT |
archsem-record | IrEmitter action-stream recorder producing validated RecordedInstruction traces | [] | serde | MIT |
archsem-ir | RtlEmitter, Fragment, Function CFG discovery, OriginGraph provenance, SemanticFidelity, backward slicing, effect summaries, register & memory SSA, replay | [] | — | MIT |
archsem-simplify | Self-contained 1–512-bit known-bits, demanded-bits, and effect-aware integer simplification over archsem-ir | [] | — | MIT |
archsem-ref | Independent bounded concrete reference executor (ConcreteEnvironment, ReferenceEmitter) | [] | arm64-guest (links archsem-arm64/farm64) | MIT |
archsem-symex | Bounded symbolic execution, concolic execution, proof obligations, and validation artifacts (backed by bitwright) | [] | serde, transform-check | MIT + bitwright (PolyForm-Noncommercial-1.0.0) |
archsem-llvm | Reference LLVM 21.1 IR emitter (LlvmEmitter via llvm-sys) and SSA replay sink (host-only, publish = false) | [] | — | MIT |
Architecture Frontends
| Crate | Target Architecture | Default Features | Optional Features | External Decoder / Runtime | License |
|---|---|---|---|---|---|
archsem-x86 | x86 (16/32/64-bit) | [] | iced (iced-x86) | iced-x86 (1.21, mvex) | MIT |
archsem-arm64 | AArch64 (A64, SIMD, SVE/SME, system) | [] | farm64 (fARM64) | fARM64 | MIT |
archsem-wasm | WebAssembly modules & functions | Enabled (wasm) | — | fWASM | MIT |
archsem-evm | Ethereum Virtual Machine bytecode | Enabled (evm) | — | evm-disassembler | MIT |
archsem-cil | ECMA-335 (.NET CIL) PE images & methods | Enabled (cil) | — | cildec, fNET | MIT |
archsem-lua | Lua 5.1–5.4 & LuaJIT bytecode chunks | Enabled (lua) | runtime (archsem-ref) | fLUA | MIT |
archsem-python | Experimental CPython 3.11.9 wordcode handler subset | [] | python | Self-contained wordcode decoder | MIT |
Bindings, Authoring Tooling & Verification
| Crate | Role | Host-only / Publishable | License |
|---|---|---|---|
archsem-capi | C ABI (archsem.h), C++17 header (archsem.hpp), CMake target archsem::archsem | Native library (publish = false); optional symex feature | MIT (with symex: links bitwright under PolyForm-Noncommercial-1.0.0) |
archsem-lang | Asem compiler library (lexer, parser, lowerer, Rust & .asemc emitter) | Host-only (publish = false) | MIT |
archsemc | Asem compiler CLI (check, build, fmt, schematic) | Host-only (publish = false) | MIT |
archsem-lsp | Language Server Protocol server for .asem files | Host-only (publish = false) | MIT |
archsem-gen | Checked-in semantic-family generator | Host-only (publish = false) | MIT |
archsem-export | Machine-readable JSON exporter for semantic tables and coverage catalogs | Host-only (publish = false) | MIT |
archsem-uops-info | Offline importer for pinned uops.info XML snapshots | Host-only (publish = false) | MIT |
archsem-conformance | Shared cross-component conformance corpus, adversarial fixtures, and external_oracle sidecar protocol | Publishable (MIT) | MIT |
archsem-examples | Runnable target-neutral public API examples | Workspace examples (publish = false) | MIT |
archsem-benchmarks | Deterministic provider-pipeline performance baselines | Workspace bench (publish = false) | MIT |
[!TIP]
editors/zed/asemis awasm32-wasip2Zed editor extension built independently by Zed's extension builder (excluded from the Cargo workspace socargodoes not descend into it automatically).
Platform & WebAssembly Portability
- MSRV: Rust
1.88.0(rust-version = "1.88"). - Portable Host Platforms: Linux, macOS, and Windows.
- WebAssembly Targets: All core portable crates (
archsem-core,archsem-record,archsem-ir,archsem-simplify,archsem-symex,archsem-ref,archsem-conformance,archsem-x86,archsem-arm64) compile cleanly for bothwasm32-unknown-unknownandwasm32-wasip1(with--all-features):
cargo check --locked --target wasm32-unknown-unknown --all-targets --all-features \
-p archsem-core -p archsem-record -p archsem-ir -p archsem-simplify \
-p archsem-symex -p archsem-ref -p archsem-conformance -p archsem-x86 -p archsem-arm64
- Host-Only Surfaces:
archsem-llvm(requires LLVM 21.1llvm-configonPATH),archsemc,archsem-lang,archsem-lsp,archsem-gen,archsem-export,archsem-uops-info,archsem-benchmarks, fuzzers (fuzz/), and native hardware differential tests are host-only.
Licensing Summary
| Scope | License | Notes |
|---|---|---|
Workspace default & all crates except archsem-symex | MIT License (Copyright (c) 2026 valeria-org) | Permissive commercial and noncommercial use |
archsem-symex & archsem-capi (symex / ARCHSEM_SYMEX=ON) | MIT wrapper + bitwright (PolyForm-Noncommercial-1.0.0) | bitwright is free for noncommercial use; commercial use requires a license from its licensor |
Formal proofs (formal/) | MIT | Pinned to Lean 4.32.0, stdlib-only |
The Core Semantic Model (archsem-core)
archsem-core is the standalone foundation of Architectura. It has zero dependencies on any target IR (archsem-ir, LLVM, etc.) and zero dependencies on any instruction decoder (iced-x86, fARM64, etc.). Every architecture definition and consumer communicates exclusively through its neutral vocabulary.
IrEmitter: Required Core vs. Provided Extensions
Every semantic definition—whether a compiled .asem SemProgram or a hand-written Rust provider—is generic over IrEmitter. The trait splits into a required core and provided extension methods whose defaults expand faithfully onto the core:
┌─────────────────────────────────────────────────────────────────────────┐
│ IrEmitter │
├─────────────────────────────────────────────────────────────────────────┤
│ Required Core │
│ • type Value │
│ • begin_instruction() │
│ • temp(bits), imm(val, bits), reg(RegisterDesc), choice(ChoiceRequest) │
│ • binop(BinOp, a, b, bits), unop(UnOp, a, bits), compare(CmpOp, a, b) │
│ • zext(v, to_bits), sext(v, to_bits), trunc(v, to_bits) │
│ • load(addr, req), store(addr, val, req), write_reg(reg, val) │
│ • select(cond, if_true, if_false), fault(FaultKind) │
│ • opaque_intrinsic(OpaqueIntrinsic, args) / intrinsic(name, args, ...) │
├─────────────────────────────────────────────────────────────────────────┤
│ Provided Extensions (default-lowered onto core, override for precision) │
│ • imm_wide(&[u64], bits) — 1..=512-bit literals │
│ • load_cond / store_cond / load_try / probe_write │
│ • write_reg_with_policy / write_reg_cond_with_policy │
│ • atomic_rmw / atomic_cmpxchg / load_exclusive / store_exclusive │
│ • fence(FenceRequest) / clear_reservation(ReservationId) │
│ • fp_binop / fp_binop_ex / fp_fma_ex / fp_unary_ex / fp_compare_ex ... │
│ • extract_element / insert_element / lut / shuffle_bytes │
│ • transaction_model / progress_model / commit_checkpoint / trap_if ... │
│ • flag_demand() -> FlagDemand │
└─────────────────────────────────────────────────────────────────────────┘
- No control-flow methods:
IrEmitterintentionally lacksbranch,jump, orbasic_block. Every execution returns aControlEffect<E::Value>orSemanticControl<E::Value>. #[non_exhaustive]operation enums:BinOp,UnOp,CmpOp,FpOp,FpUnOp,FpCmp, andAtomicOpcan gain new variants without breaking existing emitters.- Lifecycle boundary (
begin_instruction): Establishes the boundary forInstructionExecutionchoices before the first semantic emission, independent of optional mnemonic or source-address metadata.
SemProgram and the Micro-Op VM
Most instruction semantics live as pure data in a SemProgram (SemProgramRef<'_>): a finite list of typed MicroOps operating over a flat Slot (u16) array:
SemProgram (const / OwnedProgram)
│
▼
verify_program[_for_insn]_with_limits() ◀── mandatory trust boundary
│
▼
run / run_checked / run_with_limits<E: IrEmitter>(program, &mut ctx, insn, entry)
│
▼
Result<SemanticControl<E::Value>, LiftError>
Key micro-op categories include:
- Emit-time expressions (
ImmExpr): Symbolic width and constant expressions resolved per decoded instruction (DstWidth,DstWidthX2,HalfDst,OperandWidth(i),ElemBits,LaneCount,InsnAddr,NextAddr,Lane,OuterLane(k), arithmetic). - Emit-time control (
StaticIf,Unroll,VLoop): Compile-time/decode-time specialization over static predicates (BuildPred:IsVector,LongMode,HasBroadcast,HasEmbeddedRounding,MaskZeroing,OperandIsMemory(i),DstWidthEq(n), etc.) and bounded unrolling. - Dataflow & effects:
Const,ReadOp,WriteOp,WriteMasked,ReadReg,WriteReg,WriteRegCond,BinOp,UnOp,Cmp,Zext,Sext,Trunc,Select,Snapshot,Load,LoadCond,Store,StoreCond,ProbeWrite,AtomicEvent,Fence,ClearReservation,TrapIf,TrapIfCode,Fault,Require,Choice,OpaqueIntrinsic,EmitFlags,EvalCond. - Compound instruction phases: Non-delay compound instructions (e.g., x86 near
CALL) can partition top-level micro-ops viaCompoundInstructionSpec(Operation,MemoryAccess,Completion), retaining member order and provenance within a single fragment.
Execution always runs the canonical verifier (vm_verify) before calling the emitter, checking definite slot assignment, widths in 1..=512, lane/index bounds, partial-operation preconditions (NonZeroDivisor, shift counts), choice compatibility, and transaction-region structure.
LiftCtx and DecodeContext
DecodeContext<S>
Every public decoder (Decoder trait) takes &self, input bytes, an address, and a DecodeContext<S>:
mode: CpuModeand manifest-selecteddecoder_mode: DecoderModeIdenabled_features: EnabledFeatures: canonical, sorted, duplicate-freeDecodeFeatureset admitted underResourceLimitsendianness: Endian: decode-dependent byte orderstate: S: DecodeArchitectureState: bounded, revisioned architecture-specific state (orNoDecodeState)
Decoders return Result<DecodeOutcome<Insn, S>, DecoderFailure>, where DecodeOutcome carries an explicit DecodeContextTransition<S> describing every per-field context change (such as mode switches). Checked entry points (decode_checked, decode_checked_with_limits) validate both input context and transition output before caller state changes.
LiftCtx<'a, E: IrEmitter>
Every semantic provider receives &mut LiftCtx<E>, which bundles:
emitter: &'a mut Earch: &'a ArchManifest— declarative register file, flag model (includingCarryPolarity), CPU modes, address spaces, segmentation model, and stack directionmode: CpuModeandprofile: ModeProfile(address/operand/stack widths,pc_read_bias,SegSemantics)insn_va: u64andnext_va: u64image: Option<&'a dyn ImageReader>andbinary_mode: BinaryModearch_state: &'a mut dyn ArchState— optional lift-time state (plusArchState::post_instructionfor hardware-loop branches)
ControlEffect and SemanticControl
Control flow is never emitted into the IR; it is returned as ControlEffect<V> / SemanticControl<V>:
FallThrough— sequential continuation tonext_vaJump { target }— direct or indirect jump (withModeSwitch)Branch { cond, taken, fallthrough, delay_slots, annul }— 1-bit predicate, takenTarget, fallthrough VA, and delay-slot/annul policy (AnnulRule)Call { target, return_to }— call transfer with continuation VA and explicitControlLinktiming (before_transfer,before_delay_slots,after_delay_slots)Return { target: Option<V> }— register-based (ARM64X30) or stack-popped (x86RET)Trap { kind: FaultKind }— terminal architectural fault/trap (with optionalTrapPayload)Switch { value, cases, default }— direct multi-way branchRep { cond, body, latch, entry }andLoopLatch { cond }— driver-instantiated runtime repeat loops (such as x86REP/REPE/REPNE)
SemanticControl is the unified, checked terminal record carrying dense ControlSuccessorIds, ControlSuccessorRoles, ControlGuards, ControlSchedule, DecodeTransitionIntent, and SemanticFidelity.
OpaqueIntrinsic: Structured Contracts
When portable micro-ops cannot expand an operation, OpaqueIntrinsic replaces raw string-only intrinsics with a complete, validated contract:
identity: OpaqueIntrinsicIdentity— target-independentname+revision(u32)reason: OpaqueReasonCode— why it is opaque (ArchitectureIntrinsic,ExternalEnvironment,ImplementationDefined,PatternOpaque, etc.)inputs: Vec<OpaqueInput>andoutputs: Vec<OpaqueOutput>— typed roles (Value,Address,Predicate,MemoryData,RoundingControl,Custom(u16)) and exact widths (OpaqueBitWidth). Multi-output descriptors denote one single execution, never one call per output.registers: Vec<OpaqueRegisterEffect>— exactSlice,Flag,Storage, or explicit aggregate (AllRegisters,AllFlags,AllArchitecturalState) effects (Read,Write,Preserved,Undefined,ConservativeClobber)memory: OpaqueMemoryBehavior,faults: OpaqueFaultBehavior,control: OpaqueControlBehavior,choices: Vec<OpaqueChoice>volatile: boolandfidelity: SemanticFidelity
Optional algorithm families (OpaqueFamily::Crypto and OpaqueFamily::Math) remain compact opaque intrinsics by default unless an emitter opts into expansion via IrEmitter::opaque_expansion().
Choice & ChoiceBindingEnvironment
Architectural nondeterminism is modeled by ChoiceRequest / ChoiceSpec rather than undef or poison:
| Dimension | Variants |
|---|---|
ChoiceKind | Unspecified, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, Uninitialized |
ChoiceScope | FreshPerObservation, ProducedValue, InstructionExecution, ExecutionSession, MachineProfile, ExternallySupplied |
ChoiceDomain | Any, Masked { known_zero, known_one }, UnsignedRange { min, max }, Finite(alternatives) |
Scopes from InstructionExecution upward require a correlation ChoiceKey. For persistent scopes (ExecutionSession, MachineProfile, ExternallySupplied), ChoiceBindingEnvironment provides the backend-neutral bridge:
- Callers assign deterministic 128-bit
ChoiceBindingNamespaces(ExecutionSession,MachineProfile,ExternallySupplied). (scope, namespace, key)maps to a stableChoiceBindingIdentity, rejecting any incompatible reuse (mismatched width, kind, or domain).- Checked entry points (
predeclare_persistent_choices) validate and register the complete persistent-choice plan before beginning an instruction or mutating target IR. - For multi-fragment instructions (such as
REPloops),InstructionExecutionGroup(Root,RepeatBody,RepeatLatch) andpredeclare_instruction_execution_choicescorrelateInstructionExecutionchoices across fragments.
Register Identity (RegisterId, RegisterDesc, IndexedRegisterBank)
Registers are identified structurally rather than by backend-specific integers:
RegisterId:(cid: u32, arch: u8, offset: u16, role: RegisterRole)whereroleisPhysical,Flag, orSystem.- On x86,
AL/AX/EAX/RAXsharecid = 0, offset = 0, whileAHhascid = 0, offset = 8. - On AArch64,
W0andX0sharecid = 0, offset = 0, andV0is the low 128-bit slice ofZ0.
- On x86,
RegisterDesc:RegisterIdpaired with exact access widthbits: u16.RegisterWritePolicy:Preserve(write slice only, keep upper bits) vs.ZeroExtendParent(zero-extend into parent, e.g. x86 32-bit GPR writes to 64-bit parents, AArch64Wn→Xn, VEX/EVEX vector writes).IndexedRegisterBank: Runtime-indexed register banks (such as x87ST(i)) preserve(base, count, index_bits, element_bits)and are bounds-checked (index < count) before emitter mutation.
Guest Memory Contracts & Fault / Transaction Models
Every memory access carries a MemoryAccessRequest:
- Address space & granularity:
AddrSpace(Data,Code,Io,Vendor(u16)),AddressSpaceResolution(withAddressSpaceAliasGroup),address_width_bits,data_width_bits,addressable_unit_bits(AddressableUnitWidth), andMemoryEndian(Little,Big,Unknown). - Access & strictness:
MemoryVolatility,MemoryOrdering(includingAcquirePerLocationfor Arm RCpc and*_LimitedRegionfor FEAT_LOR),Atomicity(NonAtomic,Atomic,GuestDefined),ReservationAction,MemoryAlignment,MemoryPrivilegePolicy,GuardPolicy,MayFaultPolicy, andTransferMask. - Compound events:
MemoryEventContractpairsMemoryEventDescriptor(Read,Write,Rmw,CompareExchange,LoadExclusive,StoreExclusive,Fence,CacheMaintenance,OpaqueMemory) with runtimeMemoryEventBindings(predicate, dynamic mask, passthrough). - Write probes:
IrEmitter::probe_writechecks store-permission faults overdata_bitswithout writing data or changing memory.
Fault & Transaction Matrix
Each executed SemProgramRef is a transaction-metadata region governed by (TransactionModel, ProgressModel):
TransactionModel | ProgressModel | Semantics on Fault |
|---|---|---|
Restartable (default) | Exact (default) | Entry state or latest explicit Commit checkpoint is visible |
Progressive | Exact | Every preceding effect is visible in exact authored order |
Progressive | CanonicalPrefix | Emitted prefix is guaranteed visible; later permitted effects may also have completed |
PermittedMemorySubset | Exact | Registers/non-memory state roll back to checkpoint; an implementation-selected subset of other memory mutations in the checkpoint segment may be visible (excluding the faulting mutation) |
Explicit Commit checkpoints close pending effect sites since region entry or the previous commit (Commit describes exception visibility, never inter-thread memory ordering).
Neutral RTL & Function CFG (archsem-ir)
archsem-ir sits between architecture lifting and downstream consumers (simplifiers, symbolic engines, decompilers, or LLVM/native code generators). It captures IrEmitter streams as validated, backend-neutral SSA RTL (Fragment) and whole-function CFGs (Function).
decode + arch lift ─▶ RtlEmitter ─▶ Fragment (instruction-local RTL + EventGraph + OriginGraph)
│
▼ lift_reachable_stateless / lift_reachable_stateful
Function (CFG of BasicBlocks + ExceptionalEdges)
│
┌────────────────────────────┼────────────────────────────┐
▼ ▼ ▼
RegisterSsa / StackMemorySsa EffectSummary / replay_cfg /
ConservativeMemorySsa CfgEffectSummary replay_register_ssa
RtlEmitter and Fragment
RtlEmitter implements IrEmitter<Value = ValueId> and produces a Fragment via finish(SemanticControl<ValueId>) (or finish_legacy(ControlEffect<ValueId>)). Unlike an audit-only trace, RtlEmitter:
- Records every register read at its exact position and access width.
- Keeps memory, fault, fence, atomic, reservation, and opaque effects strictly ordered.
- Retains full
MemoryAccessRequest,MemoryEventContract,OpaqueIntrinsic, andChoiceSpecdescriptors. - Materializes terminal control as a distinct final event (
EventId::TERMINAL) insideFragment::control.
Fragment::validate() independently checks positive non-zero widths (1..=512), canonical constants, operand/result width consistency, conversion directions, 1-bit guards, valid memory/opaque contracts, SSA dominance/use-before-definition, and coherent terminal control.
Fragment::optimize
Fragment::optimize(OptimizeConfig) runs a strict instruction-local pass performing:
- Width-aware constant folding (
1..=512bits, sharingarchsem_core::bitvecexact evaluation, never folding partial-operation UB into constants) - Copy/identity propagation and commutative canonicalization
- Conservative GVN (never commoning
Load,ReadReg,Fp*,Opaque*, or distinctChoiceidentities; pure expressions reusing one stable produced choice are eligible) - False-predicate memory simplification (converting a statically false
LoadCondtoConst(0)and dropping a statically falseStoreCond/TrapIf/WriteRegCond) - Dead pure-node elimination while retaining all observable effects and stable
EventIds
EventGraph, Backward Slicing, and Effect Summaries
Instruction-Local EventGraph
Fragment::event_graph() projects the Node sequence into a validated DAG over stable EventIds plus EventId::TERMINAL. Edges explicitly distinguish:
Value(ValueId)— dataflow dependenceAddress(ValueId)— effective-address dependenceControlPredicate(ValueId)— branch/guard predicate dependenceIndirectTarget(ValueId)— computed transfer targetRegisterIndex(ValueId)— dynamic indexed-bank selectorRegisterSlice(RegisterId)/Flag(RegisterId)— architectural register/flag dependenciesMemoryVersion— instruction-local memory orderingEffectOrder/FaultOrder— checkpoint, barrier, and fault precedenceReservationState(ReservationId)— local exclusive monitor state
Policy-Free Backward Slicing
Fragment::backward_slice(&[SliceRoot], SliceEdgeKinds) computes a deterministic BackwardSlice (events, values, and dependency edges) from caller-chosen SliceRoot::Event(EventId) or SliceRoot::Value(ValueId) roots and opt-in SliceEdgeKinds (VALUE, ADDRESS, CONTROL_PREDICATE, INDIRECT_TARGET, REGISTER_SLICE, FLAG, MEMORY_VERSION, EFFECT_ORDER, FAULT_ORDER, REGISTER_INDEX, RESERVATION_STATE). It makes no taint, alias, or recovery assumptions on the caller's behalf.
EffectSummary and CfgEffectSummary
EffectSummary::from_fragmentscomposes straight-line fragments (retaining each fragment's optionalInstructionExecutionGroup) and summarizes register reads/writes/preserved slices (using theArchManifestif provided, or conservative raw descriptors otherwise), memory effects, faults, requirements, and uncertainty boundaries.Function::cfg_effect_summarysummarizes whole functions per block while retaining the original typed terminator, exceptional edges, multi-predecessor joins (CfgSummaryJoin), and cyclic strongly connected components (CfgSummaryLoop) without flattening mutually exclusive paths.
OriginGraph Provenance & SemanticFidelity
OriginGraph
Every value, effect, and terminal in a Fragment resolves to a stable OriginId inside a bounded, interned OriginGraph DAG:
- Instruction origin (
InstructionOrigin: address, exact bytes, decode context fingerprint, architecture identity, mnemonic, optional consumer-supplied execution/trace/occurrence/epoch supplement viaOriginSupplementProvider) - Semantic sites (
SemanticSite: program identity, revision, nestedMicroOpPath, operand role, lane) - Ordered bundle membership (
OrderedBundleMemberfor delay slots and compound instructions) - Derived values, local transforms, aliases/merges, and explicit truncation markers (
OriginTruncationReason)
Optimization passes (Fragment::optimize, archsem-simplify, CFG passes) return explicit transformation mappings (FragmentTransformMappings, FunctionTransformMappings) instead of silently dropping provenance.
SemanticFidelity & FidelityAnalysis
Each Fragment carries a declared SemanticFidelity (coverage, determinism, choice kinds, observable facets, validation evidence, and reason codes). Calling fragment.analyze_fidelity() derives a fresh FidelityAnalysis over the current typed graph—tainting values and observable events only through their actual dependencies and matching observable facets—so rewrites never leave stale side tables.
Function: Reachable CFG Discovery
lift_reachable_stateless and lift_reachable_stateful discover reachable basic blocks starting from an entry address using a Decoder and ImageReader:
- State-keyed discovery:
lift_reachable_statefulkeys blocks by(address, CpuMode, DiscoveryState::Key).ContextualDiscoveryState<S, K>lets consumers compose a caller-owned key (such as a code epoch or virtual-PC context) without exposing dispatcher or unpacking heuristics toarchsem. - Bounds & Incompleteness (
Completion):CfgLiftConfigboundsaddress_range,extra_ranges,additional_entries,max_instruction_bytes,max_instructions,max_blocks,max_total_bytes,max_switch_cases, anddecode_limits. If discovery hits a decode failure, unsupported instruction, or resource limit, it attaches a boundedIncompletenessRecordand returns aCfgLiftFailurecontaining the partialFunction(Completion::Incomplete). Destructive transforms and executable replay reject incomplete functions until explicitly valid and marked complete (mark_complete). - Ordered Bundles & Repeat Loops: Non-annulled straight-line delay slots and compound instructions remain grouped via
OrderedBundle/TransactionRegionId; taken-only annulled slots clone blocks as needed;REPinstructions lower intoRoot,RepeatBody, andRepeatLatchInstructionExecutionGroupfragments. - Function Normalization (
Function::optimize_function&canonicalize_cfg): Supports fragment simplification, expression forwarding across blocks, register SCCP (RegisterSccpStats), architecture-aware bit-granular register DCE (RegisterDceConfig,ExitLivenessPolicy,ExceptionalStateRoots), constant branch/switch folding, unreachable-block pruning, and optional empty-trampoline threading / linear block coalescing (Function::canonicalize_cfg).
Register SSA & Memory SSA
archsem-ir provides three validated CFG-level SSA products, each independently reconstructible and verifiable via ssa_validation:
RegisterSsa::build(&function, &arch)Promotes architectural parent registers (ParentReg) into SSA values with block-entryRegisterPhis across diamonds and loops. Understands x86 nested GPR slices (AL/AH/AX/EAX/RAX), AArch64Wn→Xnzero-extension, and vector parent clearing/merging policies.StackMemorySsa::build(&function, &arch)&optimize_stack_memoryIdentifies exact, non-overlapping affineSP ± constslots whenSPis stable and no call, unwind, atomic, conditional, or opaque memory boundary intervenes. UnderStackMemoryConfig::strict(), no loads or stores are eliminated; underassume_private_stack_accesses_non_faulting(), dead private stack stores can be removed.ConservativeMemorySsa::build(&function)/build_with_partition&MemoryDependencyGraphAssigns whole-memory tokens (MemoryToken) across arbitrary-address loads, stores, atomics, fences, opaque intrinsics, and call clobbers. Callers may supply a labeledMemoryPartitionPolicyto separate disjoint memory classes.MemoryDependencyGraph::buildprojects constant-address unit ranges (MemoryDependencyRange) and supports function-level memory backward slicing (MemoryDependencyGraph::backward_slice) without claiming general alias recovery.
Retained Artifacts & External Observations
- Immutable Lineage (
RetainedFragmentArtifact,RetainedFunctionArtifact): Keeps the raw lifted artifact immutable while running normalization as a transactional clone-transform-validate-commit query (NormalizationGeneration,NormalizationRecord). - External Observation Binding (
ObservationSet,TraceSequence): Binds dynamic execution evidence (PC, observed bytes, occurrence IDs, code epochs, register values with known-bit masks, memory transfers, unified control outcomes, and pre-terminal faults) to fragment values/events/origins via typedObservationBindingRoles. Caller hypotheses live separately inObservationAssumptionSet(AssumptionHint).
Replay (replay, replay_cfg, replay_register_ssa)
Fragment::replay(&mut emitter): Replays an instruction fragment into anyIrEmitter, predeclaring persistent choices and installing per-event and terminalSemanticSites.Function::replay_cfg(&mut sink): Replays raw blocks, transaction regions, grouped repeat roles, and prioritizedExceptionalEdges withExceptionalMemoryStatevisibility descriptors into aFunctionReplaySink.Function::replay_register_ssa(&mut sink)/replay_register_ssa_with_calls: Lowers sparse live-in block parameters (ParentReg), edge-parallelEdgeAssignmentbatches, partial-parent reconstruction, and injectedCallSummarys into an executableRegisterSsaReplaySink(such asarchsem-llvm). Before mutating backend state, replay checksReplayCapabilitiesagainst the function'sReplayRequirements.
Simplification & Formal Proofs (archsem-simplify & formal/)
archsem-simplify provides self-contained, effect-aware integer analysis and rewriting over archsem-ir fragments and functions. Its directed fragment rewrite contract is backed by a machine-checked Lean 4 model in formal/.
Contexts, Budgets & Strictness
All scratch state, known-bits facts, and telemetry live in a caller-owned SimplifyContext—there are no process-global interners, caches, or thread-local state. Every entry point (simplify_fragment, simplify_fragment_with_summary, simplify_function, simplify_function_with_summary, simplify_function_unsummarized) is transactional:
- Incomplete (
Completion::Incomplete) and observation-bound artifacts are rejected on every destructive path—even whenmax_iterationsormax_node_visitsis0. - Candidate rewrites are validated against
Fragment::validate()/Functioninvariants and remapped acrossOriginGraphandEffectSummarybefore committing. If validation fails, the input IR and provenance remain untouched. - A deterministic SSA-user worklist recomputes only definitions affected by a local replacement or alias rather than re-analyzing the whole fragment on every wave.
Known-Bits & Range Analysis (archsem_simplify::analysis)
analyze_known_bits computes forward dataflow facts for 1–512-bit integer values using archsem_core::known_bits:
KnownBits: Separateknown_zeroandknown_onebitmasks (1..=512bits).UnsignedRange&SmallUnsignedRange: Exact modular interval tracking for comparison proving (prove_known_bits_compare,prove_known_bits_signed_greater,prove_unsigned_range_compare).- Shared Production Evaluator: Constant folding and known-bit transfer share
archsem_core::bitvecwitharchsem-irandarchsem-symex, guaranteeing identical 1–512-bit modular arithmetic, sign/zero extensions, and explicit invalid partial-operation tracking (division by zero,INT_MIN / -1, shift count>= width, out-of-bounds lanes).
Demanded-Bits & Consumer Flag Demand
Fragment Demanded-Bits (analyze_demanded_bits)
analyze_demanded_bits performs backward bit-liveness over a Fragment, returning a DemandMask per ValueId and per-register read demand (RegisterReadDemand). Callers can supply an OutputDemand specifying which parent-register bit slices are observed at fragment exit; by default every bit is demanded.
[!IMPORTANT] Soundness Contract for Narrowed Demand: Just like
archsem_core::FlagDemand, narrowingOutputDemandis a consumer assertion about the surrounding program. A consumer may drop a bit only when that bit is overwritten before any read on every path leaving the instruction—including fault, trap, exception, and unwind edges and any unknown exit. Exceptional checkpoints and side effects inside the fragment always retain full demand on their own operands.
Static Flag-Demand Inference (infer_flag_effects_for_insn)
For consumers lifting one instruction at a time into their own IR, archsem_core::FlagDemand (read via IrEmitter::flag_demand) lets the micro-op VM suppress entire per-flag computations and dead pure intermediates feeding only undemanded flags—while preserving the exact relative op sequence of every demanded flag. archsem_core::infer_flag_effects_for_insn computes a static FlagEffects summary (flags read, written, undefined, defined on all paths, or unbounded) for a decoded instruction form without executing it.
Effect-Aware Rewrite Rules & Telemetry
archsem-simplify only replaces or aliases pure integer definitions. Loads, stores, probes, atomics, fences, traps, faults, opaque intrinsics, and register writes retain their order and stable EventIds.
The 31 RuleId Families
| Category | RuleId Variants |
|---|---|
| Constants & Identities | ConstantFold, AddZero, SubZero, MulOne, MulZero, BitwiseIdentity, BitwiseAnnihilator, ShiftZero, DivideOne, RemainderOne, ConvertNoop |
| Same-Operand & Select | SameOperand, SelectConstant, SelectSameArms, CompareSameOperand |
| Boolean & Comparisons | BooleanCompare, CompareInversion, CompareCanonicalOrder, SelectToMask, KnownMaskRedundant, KnownConstantResult |
| Algebraic & Bitwise | DoubleUnary, AffineCancellation, NegatedArithmetic, ComplementaryBitwise, ConversionChain, RotateInverse |
| Packed Lanes | ExtractInsertedLane, ExtractDisjointLane, InsertExtractedLane, OverwriteInsertedLane |
Partial-Operation & Choice Guards
A rewrite never erases a partial-operation validity obligation or alters choice correlation:
(x + y) - y,(x - y) + y,x & 0,x * 0, inverse rotates, and packed-lane cancellations drop a retired dependency only if that operand is proven defined (cannot divide by zero, overflow signed division, or shift by>= width).Unspecifiedchoices atProducedValuescope without a correlation key may be eliminated by DCE only if all uses are gone; keyedInstructionExecution,FreshPerObservation,ConstrainedUnpredictable,ImplementationDefined,Environment,Entropy, andUninitializedchoices are preserved.
Per-Rule Decision Telemetry
RuleStats / RuleDecisionStats distinguishes:
considered,applied,declined(proof refused),deferred(another rule fired first)choice_sensitiveandpotentially_invalidorthogonal flagsbudget_limitedwhen stopped atSimplifyOutcome::IterationLimitorSimplifyOutcome::NodeVisitLimit
Lean 4 Formal Proofs (formal/)
The formal/ Lake project (pinned to Lean 4.32.0, standard-library-only, no sorry, no custom axioms, no unsafe, verified via lake build and AxiomAudit.lean) formalizes the strict, semantics-preserving transformation contract of archsem-simplify and whole-function CFG sealing:
| Module | Contents |
|---|---|
Archsem/Word.lean | Concrete BitVec semantics and explicit invalid-partial-operation reasons |
Archsem/Expr.lean | Typed pure expressions, lazy select, inputs, and site/correlation-keyed Choices |
Archsem/Rewrite.lean | All 31 RuleId names plus proof-carrying local steps, congruence, and guarded cancellation/annihilator rules |
Archsem/Behavior.lean | Observation profiles, protected event contracts, domain-checked choice plans, behavior sets, and certified deletion-ledger cleanup |
Archsem/CFG.lean | Scope/epoch/generation-indexed CFG completion, unique block/entry obligations, closed targets, total outer-value remapping, and sealing certificates |
Archsem/Soundness.lean | Main theorem simplifyFragment_behavior_equiv, complete mapping records, and transactional rollback |
Archsem/Examples.lean | Regression witnesses (e.g., correlated-choice cancellation and refusal to totalize unconstrained division) |
[!NOTE] Proof Boundary: The Lean development is a denotational unfolding of validated acyclic SSA rather than extracted Rust. It verifies the proof-carrying transformation contract (
AnalysisCertificate) and modeled architectural projection—not the compiled Rustchoose_rewriteimplementation itself, which is cross-checked byarchsem-simplifyproperty suites andarchsem-symex'stransform-checkfeature.
Execution, Recording & Lowering
Architectura provides four execution and backend consumers alongside archsem-ir:
archsem-ref— Independent bounded concrete reference oraclearchsem-symex— Self-contained bounded symbolic & concolic execution and proof obligationsarchsem-record— Action-stream recorder (IrEmitter→ serializableRecordedInstruction)archsem-llvm— Reference LLVM IR emitter and Register-SSA lowering backend
Concrete Reference Execution (archsem-ref)
archsem-ref is an independent concrete interpreter (#![forbid(unsafe_code)]) used as a common-mode-failure oracle against archsem-simplify, archsem-symex, and archsem-llvm. It deliberately maintains its own 1–512-bit BitVector evaluator rather than sharing evaluation code with archsem-simplify or archsem-symex.
- Definedness: Raw shifts/rotates with count
>= width, division/remainder by zero,INT_MIN / -1, and invalid lane indices returnPartialOperationinstead of panicking or inheriting host overflow. - Pluggable Environment (
ReferenceEnvironment): ComposesRegisterEnvironment,MemoryEnvironment,ChoiceEnvironment,FloatingPointEnvironment, andOpaqueEnvironment.- The stock
ConcreteEnvironmentstores exact(RegisterId, bits)cells and byte-addressed sparse memory keyed by(AddrSpace, BitVector). - Optional
arm64-guestfeature connectsConcreteEnvironment::with_arm64_bindingsandwith_arm64_servicesto exact AArch64 FP, SVE/SME VL/SVL, MOPS, MTE, RCW/LSFE, LS64, and TIndex policies.
- The stock
- Fault Visibility (
ReferenceExecution::visible_state):ReferenceExecutionseparates raw environment mutations (outcome: ExecutionOutcome) fromArchitecturallyVisibleState(Exact,CanonicalPrefix,PermittedMemorySubset, orUnsupported(ReferenceVisibilityBoundary)when an eager environment cannot roll back aRestartablefault). - Suspensible Opaque Execution:
ReferenceEmitter::suspend()/ReferenceEmitterState::resume()allows embeddings (such asarchsem-lua/runtime) to complete reentrant guest services without losing session counters, choices, or transaction state.
Bounded Symbolic & Concolic Execution (archsem-symex)
archsem-symex lowers a complete Function via RegisterSsa into SymbolicProgram block templates and explores paths deterministically within explicit ExecutionConfig budgets—without requiring LLVM or an external SMT solver.
[!WARNING] Licensing:
archsem-symexdepends onbitwright(PolyForm-Noncommercial-1.0.0). Noncommercial use is free; commercial use requires a license frombitwright's licensor.
Symbolic Engine & bitwright Integration
- Context-Owned Arena (
ExprArena): Structurally interned 1–512-bit expressions with exact widths, ternaryselects, conservative symbols, and scopedChoices (FreshPerObservation,ProducedValue,InstructionExecution, persistent scopes). - Total Translation + Definedness Guards: Each node translates into a total
bitwrightbitvector value paired with a 1-bit invalidness guard (1iff a partial operation is violated). Invalid operations are excluded from path-condition input inference so path pruning never erases a shift/division definedness obligation. - Deterministic Constraint Solving & Simplification: Each path maintains
bitwrightconstraints (known bits, signed/unsigned ranges, equality classes) and prunes only proven contradictions. Reported expressions are simplified (and optionally equality-saturated viaSimplificationBudgets::max_saturation_work_per_expression) deterministically. - Nested Resource Budgets (
ExecutionConfig): Independently capsPathBudgets(max_steps_per_path,max_paths,max_block_visits_per_path),ExpressionBudgets,SubstitutionBudgets,RecursionBudgets,MemoryBudgets,SimplificationBudgets, andDiagnosticBudgets. Each limit produces a typedBudgetKindexit. - Policy Boundaries (
ExecutionContext): Unmodeled memory, opaque intrinsics, calls, fences, atomics, reservations, transactions, and faults fail closed withPathExit::Unsupported(UnsupportedReason)unless the caller injects a path-localMemoryPolicy(e.g.,ExactByteMemoryfor concrete bytes),IntrinsicPolicy,CallPolicy, orEffectPolicy. All policy mutations are staged transactionally per path.
Concolic Execution (execute_concolic)
execute_concolic executes a single deterministic path guided by a ConcolicTrace of typed branch, switch, indirect-target, and concrete ordinary-memory observations. It returns the consumed observations, exact path condition, and negated exploration alternatives, stopping cleanly at any missing, mismatched, or ambiguous boundary.
Proof Obligations & Validation Artifacts
ProofObligation/ProofObligationArtifact: Projects caller-selected inputs and one path's reachable outputs into solver-neutralProofTermOpDAGs (tNtopological names, per-term provenance/fidelity, typed assumption/definedness/fault/output roots) exportable to bounded JSON/RON.InstructionValidationObligation&InstructionCounterexampleArtifact: Packages a complete instruction/case validation handoff (inputs, choices, preconditions, observable roots, faults, register deltas, rewrite mappings, and bounds). External solver models can be replayed againstInstructionCounterexampleArtifactto verify mismatches and map them backward through rewrite provenance.- Rewrite Checking (
transform-checkfeature):check_fragment_transformandcheck_function_transformprovide translation-validation checks for fragment/function rewrites during fuzzing and testing.
Action Recording (archsem-record)
ActionRecorder implements IrEmitter<Value = ValueRef> to record every emitted semantic action as a self-typed SemanticAction trace without committing to any compiler IR:
ActionRecorder::finish(control)validates definition order, widths (1..=512), choice identities, memory contracts, transaction/progress placement, and terminal consistency, returning aRecordedInstructionwith stableEventIds, internedSemanticSites, andRecordedControlEffect.- With the
serdefeature enabled,RecordedInstructionserializes cleanly to JSON for inspection, cross-architecture diffing, or external transpilation.
Reference LLVM Backend (archsem-llvm)
archsem-llvm (publish = false, host-only, linking LLVM 21.1 via llvm-sys) provides LlvmEmitter, proving the framework's IR-agnostic design on a production compiler IR:
- Uniform Integer Values: Every
IrEmitter::Valueis an LLVM integer of exact bit width (1..=512); registers use width-typedallocas in the prologue initialized withfreeze undef(never raw per-useundefor poison); floating-point opsbitcastacrossfloat/double. - Choice Bindings:
LlvmEmitter::newaccepts non-persistent choices;LlvmEmitter::new_with_choice_bindingstakes aChoiceBindingEnvironmentto declare and load immutable external symbols for persistent scopes (ExecutionSession,MachineProfile,ExternallySupplied). - Conservative Lowering of Unmodeled Contracts: Unsupported guest-memory contracts, fences, and valid fall-through
OpaqueIntrinsics lower to single observable external calls retaining full typed diagnostics (MemoryLoweringDiagnostic,FenceLoweringDiagnostic,OpaqueLoweringDiagnostic). Opt-inenable_guest_fault_reporting_loads()lowersLoadTryto packed(data, fault)guest helper calls. - Register-SSA Lowering (
RegisterSsaReplaySink):Function::replay_register_ssalowers complete functions into LLVM basic blocks andphinodes (using bridge predecessors where needed) and emits external ABI boundaries@archsem.return,@archsem.jump.*, and@archsem.call.*.
x86 & x86-64 (archsem-x86)
archsem-x86 defines the x86 architecture manifest (X86_MANIFEST), register map (regmap), semantic table (X86_SEMANTICS), Asem-generated programs (programs), and—when the optional iced feature is enabled—the iced-x86 decoder adapter, form identity catalog, and performance scenario model.
# Pure data only (no decoder dependency):
archsem-x86 = "0.1"
# With iced-x86 decoder, form catalog, and performance adapters:
archsem-x86 = { version = "0.1", features = ["iced"] }
CPU Modes & Segmentation
X86_MANIFEST declares three CpuModes sharing one unified semantic table:
| Constant | Bit Width | SegSemantics | Description |
|---|---|---|---|
LONG64 | 64-bit | SegSemantics::None | Long / 64-bit mode (FS/GS linear bases modeled explicitly) |
PROT32 | 32-bit | SegSemantics::Descriptor | 32-bit protected mode (with optional architectural segmentation checks) |
REAL16 | 16-bit | SegSemantics::RealMode | 16-bit real-address mode |
Address formation uses SegmentationModel::Flat by default. Selecting SegmentationModel::Architectural (via RtlEmitter::with_segmentation_model or CfgLiftConfig::segmentation_model) routes 16-bit real-mode, virtual-8086, and 32-bit protected accesses through hidden descriptor caches with guarded #GP/#SS limit and attribute checks, plus descriptor-table/gate/IRETQ semantics and Require modeled-domain preconditions.
Decoder Adapter (iced Feature)
Enabling features = ["iced"] unlocks archsem_x86::decode:
IcedX86Decoder: Stateless default Intel-personalityDecoder<Insn = IcedInsn, State = NoDecodeState>.IcedX86DecoderWithOptions(pub u32): Selects vendor/historical opcode personalities:AMD— AMD decode differences (honours66operand-size prefix on near branches in 64-bit mode,UD0without ModRM,LOCK MOV CR0asMOV CR8, etc.)KNC— Intel Knights Corner (MVEXand KNC VEX maps in 64-bit mode)- Legacy/vendor personalities:
CYRIX,LOADALL286,LOADALL386,UMOV,XBTS,CYRIX_SMINT_0F7E,CYRIX_DMI,ALTINST,STOREALL,CL1INVMB,UDBG,POP_CS
#UDHandling: Complete invalid encodings (Code::INVALID) lift through theUD2semantic row (#UDtrap) rather than failing as truncated input.
Register Aliasing, Flags, and REP Loops
- GPRs (
cid0..16):RAX–R15useSubRegMap::X86Nested:- 8-bit low (
AL) and high (AH,offset = 8) and 16-bit (AX) writes useRegisterWritePolicy::Preserve. - 32-bit (
EAX) writes useRegisterWritePolicy::ZeroExtendParentinto the 64-bit parent (RAX).
- 8-bit low (
- Status Flags (
CarryPolarity::BorrowSet):CF,PF,AF,ZF,SF,OF, andDFare modeled as individual 1-bitRegisterRole::Flagregisters (cid1..7), whileRFLAGS_CONTROLholds the remaining non-condition bits. - String Operations (
REP/REPE/REPNE): Expand viaControlEffect::Repinto executableRoot/RepeatBody/RepeatLatchInstructionExecutionGroups.REPE/REPNECMPS/SCASrun each iteration in the latch and commit final flags on the terminating iteration, preserving pre-instructionEFLAGSbeside committedRCX/RSI/RDIprogress if a later iteration faults. - Atomic Routes:
XCHGwith a memory destination andLOCK-prefixed memory-destination RMW instructions selectprograms::atomic_program_forand emitAtomicEvents; illegalLOCKcombinations fail closed before emission.
x87, MMX, SIMD, AVX-512, and MVEX
- x87 FPU (
x87_exact.asem,x87_projection.asem,x87_state_image.asem): Models the 80-bitST(0)..ST(7)stack (IndexedRegisterBank),FPCW,FPSW(reconstructing liveX87_TOP),FPTW, and state-image layouts (FXSAVE/FXRSTOR,FNSAVE/FRSTOR,FNSTENV/FLDENV). - MMX (
mmx.asem): Decoded operands touchingMM0..MM7dispatch to dedicated x87-aliased routes rather than silently aliasing XMM vectors. - SSE / AVX / AVX-512 (
VEC_BASE = 0x100,K_BASE = 0x90):XMM/YMM/ZMMalias a single 512-bit parent (SubRegMap::VectorNested); legacy SSE writes preserve upper lanes while VEX/EVEX/XOP writes clear them.- EVEX write masking (
{k1}/{z}), embedded rounding ({rn-sae}), SAE,{1toN}broadcast, and fault-suppressed masked memory loads (E##vsE##NFwithprobe_write) are modeled explicitly. - AVX-512 scatter programs declare
TransactionModel::Progressive.
- Crypto / Math Expansion: AES, SHA, SM3/SM4, and x87 transcendentals stay compact structured
OpaqueIntrinsics by default unlessIrEmitter::opaque_expansion()enablesOpaqueExpansion::CRYPTOorMATH.
Architecture Profiles, Form & Performance Catalogs
- Profiles (
X86_ARCHITECTURE_PROFILES):X86_PROFILE_BASELINE,LEGACY_BASE,X87,LEGACY_MMX,SSE,AVX,AVX512,CRYPTO,MVEX,OTHER_EXTENSION. - Form Catalog (
archsem_x86::form): Assigns stable, versionedX86FormIddigests (architectura.x86.form.v1) from symbolicicedCodenames andX86ExecutionModes (13,028reviewediced1.21.0 forms), independent of unstable enum discriminants. - Performance Catalog (
archsem_x86::performance): Models CPU tuning IDs (X86Microarchitecture),ResolvedX86Scenario, latency/throughput records (X86PerformanceDatabase), and macro/micro-fusion rules imported offline fromuops.infoviaarchsem-uops-info.
AArch64 / ARM64 (archsem-arm64)
archsem-arm64 provides the AArch64 architecture manifest (ARM64_MANIFEST), register map (regmap), semantic table (ARM64_SEMANTICS), Asem-generated instruction programs, and—behind the farm64 feature—the fARM64 decoder adapter and form catalogs.
# Pure data only:
archsem-arm64 = "0.1"
# With fARM64 decoder adapter:
archsem-arm64 = { version = "0.1", features = ["farm64"] }
Execution Mode & NZCV Carry Polarity
ARM64_MANIFEST declares a single 64-bit execution mode (A64, flat little-endian 64-bit addressing, pc_read_bias = 0).
Register Model & CarryPolarity::BorrowClear
- GPRs (
0..32):X0–X30(X30=LR) plus dedicatedSP(cid = 31). WritingWn(32bits) usesSubRegMap::ArmLowHalf(ZeroExtendParentintoXn).XZR/WZR(cid = 32) is a sentinel outside the GPR bank that reads asimm(0)and ignores writes. - NZCV Flags (
0x80..0x83) & Inverted Carry Polarity:ARM64_MANIFESTsetscarry_polarity: CarryPolarity::BorrowClear. Unlike x86 (whereSUBsetsCFon borrow,ULt), ARM64SUBSsetsCon no-borrow (UGe). The shared flag engine (emit_flags) and Asemflagsrecipes derive both polarities automatically from the manifest.
Farm64Decoder (farm64 Feature)
Farm64Decoder (Decoder<Insn = FarmInsn, State = NoDecodeState>) wraps fARM64 and enforces canonical EnabledFeatures gating (neon, fp, lse):
- Pure Branches (
B,B.cond,BC.cond,CBZ,CBNZ,TBZ,TBNZ): Classified byFlowClassrather than carrying aSemProgram.conditional_branch_metadata(&Instruction)extracts exactConditionalBranchPredicate(Flags(Cond),Zero, orBit) plus resolvedtakenandfallthroughaddresses so the generic CFG driver never guesses branch conditions. - Pre/Post-Indexed Memory & Pairs (
LDR/STR/LDP/STP): Emit all memory accesses before base writeback (Writeback::Pre/Post) so faults preserve architectural register state. - Decoder Extensions (
decoder_extensions): Covers exact published instruction words (such asZT0LDR/STRandLDAP1/STL1forms) alongside the corefARM64catalog.
FP/SIMD, SVE/SME Scalable State, and Extensions
| Extension Family | Storage & Semantic Modeling |
|---|---|
| AdvSIMD & FP | V0–V31 (VEC_BASE = 0x100, SubRegMap::VectorNested) share the low 128 bits of Z0–Z31. Writes to V registers under SVE use an Asem write_hook (vector_overlap) to zero or preserve active Z bits above bit 127 according to CurrentVL and the constrained-unpredictable choice. FPCR, FPSR, and FPMR (0x200..0x202) track rounding, controls, and cumulative exceptions. |
| SVE / SVE2 / SVE2p3 | Z0–Z31 (2048-bit storage), P0–P15 (256-bit predicates, 0x300+n), and FFR (256-bit, 0x310). Runtime VL supports 128–2048 bits in 128-bit increments (including non-powers-of-two). Scalable memory instructions model first-fault/non-fault FFR progress and guest-resolved permissions. |
| SME / SME2 / SME2p3 | ZA matrix (256 rows of 2048 bits, 0x400+row), ZT0 (512-bit lookup table, 0x500), PSTATE.SM (0x501), PSTATE.ZA (0x502), and LUTI6 / outer-product / tile operations. |
| FP16 / BF16 / FP8 | Typed lane formats and integer-only fp_values::fp8_dot_add (E5M2/E4M3) primitives without host FPU dependence. |
PAC (PAuth) & PSTATE.PACM | QARMA3/5 integer rounds, pointer-tag insertion/authentication, explicit faults, and PSTATE.PACM (0x503) with guest-supplied keys and VA/TBI/MTX masks. |
| MTE (Memory Tagging) | Tag arithmetic/packing, RGSR seed/tag (0x680..0x681), and allocation-tag vendor space (0xA64). |
| MOPS, LS64, RCW/RCWS, FEAT_LOR, Unprivileged | Ordered copy/set/tag stages with deferred abort delivery (MOPS); single-copy 512-bit LD64B/ST64B* (LS64); lease-scoped RCW/RCWS (guest_atomicity); AcquirePerLocation (RCpc); *_LimitedRegion (FEAT_LOR); and unprivileged (LDTR/STTR) memory policies. |
| Apple AMX & GXF | Explicit M1–M4 AMX X/Y/Z (0x600+n, 0x608+n, 0x620+n) matrix storage and integer/FP kernels (AMX_ENABLED 0x660), plus GXF (TINDEX/SAVED_TINDEX/TENTER_RETURN 0x670..0x672) with vendor guest callbacks. |
Executable Guest Bindings (archsem-ref/arm64-guest)
When running AArch64 semantics concretely in archsem-ref (with features = ["arm64-guest"]), ConcreteEnvironment::with_arm64_bindings and with_arm64_services provide exact integer IEEE FP arithmetic/status traces, effective VL/SVL feature access checks, and byte-level MOPS, MTE, single-agent RCW/LSFE, LS64, and TIndex policies—while keeping OS exception routing, address translation, and multi-agent locking as explicit caller contracts.
Bytecode & Managed VMs
Architectura applies the same ArchManifest + SemProgram + IrEmitter model to stack-based and register-based virtual machines. Rather than treating bytecode as an unstructured native byte stream, each frontend validates and normalizes the container's function/method/prototype structure first, then lifts through checked Asem programs into archsem-ir.
[!NOTE] The four production bytecode crates—
archsem-wasm,archsem-evm,archsem-cil, andarchsem-lua—enable their default frontend features out of the box.archsem-pythonis an experimental handler-level frontend gated behindfeatures = ["python"].
WebAssembly (archsem-wasm)
- Parser & Validator: Backed by
fWASM(re-exportingwasmparsertypes).WasmModule::parse/parse_with_featuresvalidates the Wasm binary up front. - Modes & Memory:
WASM32(32-bit linear memory) andWASM64(Memory64,64-bit linear memory).AddrSpace::Datamodels little-endian linear memory. - Stack Normalization (
WasmFunction): Precomputes the deterministic WebAssembly operand-stack heights at every instruction and maps stack slots (STACK_REGISTER_BASE = 0x1000), locals (0x2000), and globals (0x3000) into synthetic registers. Structured control (block,loop,if/else,br,br_if,br_table,end) lowers directly to byte-addressed CFG edges. - One-Call Lifting:
lift_function_cfg(&module, fn_index, &limits)returnsLiftedWasmFunctioncontaining the completearchsem_ir::FunctionCFG. Proposal opcodes outside the neutral core appear asWasmOpcode::Opaquewith validated stack arity.
Ethereum Virtual Machine (archsem-evm)
- Decoder & Fork Gating: Backed by
evm-disassembler(EvmCode::parse/parse_hex).EvmFork(FrontierthroughOsaka) gates opcodes by hard fork—opcodes absent in the selected fork decode asINVALID. Truncated trailingPUSHnimmediates zero-pad to full width, andJUMPDESToffsets are collected at instruction boundaries. - Static Jump-Target Resolution (
EvmFunction): Performs bounded value-set analysis (AnalysisLimits) to resolveJUMPandJUMPIdestinations within the code object, exposingFunctionStackGraphandEvmStackSsaviews. - Address Spaces: Disjoint
AddressSpaceAliasGroups separate big-endian EVMMEMORY_SPACE(Data),CODE_SPACE(Code),STACK_SPACE(Vendor(0)),STORAGE_SPACE(Vendor(1), 256-bit word-addressed),TRANSIENT_SPACE(Vendor(2)),CALLDATA_SPACE(Vendor(3)),RETURNDATA_SPACE(Vendor(4)), andWORLD_STATE_SPACE(Vendor(5)). - 256-bit Semantics & Stack Templates: Stack ops (
stack evmin Asem) emit explicit underflow and 1024-word overflow guards (EVM_SP) around 256-bit arithmetic (ADD,MUL,EXP,ADDMOD,MULMOD,SHL/SHR/SAR,CLZ, etc.). External world-state, gas, and message calls remain typed opaque boundaries. - One-Call Lifting:
lift_code_cfg(&code, &limits)lifts an entire contract intoLiftedCode.
.NET CIL / ECMA-335 (archsem-cil)
- PE & Metadata Decoder: Backed by
cildec(metadata tables, method headers, signatures, exception clauses) andfNET(IL instruction decoder). - Modes (
CIL32/CIL64):mode_for_image_flagsresolves32BITREQUIREDvs PE32+ headers. - Evaluation Stack & Method Slots:
CilFunction::normalizecomputes stack heights and assigns synthetic registers for evaluation-stack slots (0x1000), method arguments (0x2000), and locals (0x3000), plusCIL_STACK_POINTER,CIL_EXCEPTION,CIL_RET, andCIL_FILTER. - Exception Handling (
lift_method_cfg&attach_unwind_edges): Discoverstry/catch/filter/finally/faulthandler entry points viaCfgLiftConfig::additional_entriesand attaches prioritizedExceptionalEdges onto the liftedFunction. - Managed Object Services: Object-model instructions (
newobj,callvirt,ldfld,castclass, etc.) emit typedOpaqueIntrinsics andvolatile./ ordered memory contracts (LoadContract/StoreContract).
Lua & LuaJIT (archsem-lua)
- Chunk Decoder: Backed by
fLUA, supportingLUA51,LUA52,LUA53,LUA54,LUAJIT21, andLUAJIT21_BITOPS(mode_for_version). - Boxed 128-bit Slot Model: Frame slots hold 128-bit boxed values (64-bit payload + 64-bit tag:
NIL_VALUE,FALSE_VALUE,TRUE_VALUE,INTEGER_TAG,FLOAT_TAG) addressed relative toLUA_FRAME, withLUA_LINKfor continuations and dedicated system temporaries for numeric loops and scalar operations. - CFG Lifting & Optional Runtime (
runtimefeature):lift_function_cfg(&module, index, &limits)lifts a prototype's CFG (LiftedLuaFunction). Enablingfeatures = ["runtime"]integratesarchsem-refwith a suspensible cursor (lift_cursor/ProgramCursor) and version-matched error/scope policies (VmErrorPolicy), while table metamethods, upvalues, GC, and native C calls remain explicit guest services.
Experimental: CPython 3.11.9 (archsem-python)
archsem-python (gated behind features = ["python"], not enabled by default) is an experimental, handler-level frontend for baseline CPython 3.11.9 wordcode (LOAD_FAST, BINARY_OP, and generic vectorcall CALL). Callers supply a FrameContext with stack-slot ownership evidence (StackSlot::Object, Null, Unknown) and PreparedVectorcall witness data to decode_3119, then lift single handlers via archsem_python::lift into PYTHON_MANIFEST (PY_LOCALS, PY_SP, PY_LASTI) and five cpython.3119.* reference-counting/protocol opaque services (own_fast, binary, vectorcall, decref, pending_after_success).
The Asem Language
Asem (Architectura Semantics, dialect asem 1.0) is the source language for authoring instruction semantics and machine-code form catalogs in Architectura. Every .asem file under semantics/ is compiled by archsem-lang (archsemc) into the exact same archsem_core::SemProgram representation and validated by the canonical archsem-core verifier before any code or package is emitted.
source.asem ─▶ lex ─▶ parse ─▶ lower (resolve · typecheck · instantiate)
─▶ SemProgramBuilder ─▶ canonical verifier ─▶ Rust / .asemc
Asem adds no runtime control flow or hidden semantics of its own: everything lowers to archsem-core micro-ops, and any verifier rejection is a compile-time error.
File Structure & Imports
Every .asem file opens with a dialect header, a dotted module path, optional relative imports, and top-level items:
language asem 1.0;
module x86.bmi2_shift;
import "common_helpers.asem";
import "PATH";imports declarations (fragment,template,register,fault,table,opaque intrinsic,atomic event) transitively under a shared namespace with no shadowing. An imported file'sprogram,pattern,subprogram,form, andwrite_hookitems are not emitted by the importer.- Comments support
//line and/* ... */block syntax. Keywords are contextual.
Top-Level Items
| Item | Syntax | Purpose |
|---|---|---|
template | template NAME<TypeParams>(ValueParams) [stack evm ...] { ... } | Parameterized program body instantiated by program items |
program | program SYM [annots] [atomic] route "ROUTE" [compound(...)] = TEMPLATE<...>(...); | Instantiates a template for a decoder route (program_for or atomic_program_for) |
pattern | pattern NAME [@revision(n)] [@slots(n)] { ... } | Non-parameterized, self-routed program (often entry-parameterized via entry) |
subprogram | subprogram NAME [@slots(n)] { ... } | Non-routed helper program (used by finish rep ... body ... latch ...) |
fragment | fragment NAME [(params) -> (outs)] { ... } | Reusable statement block expanded via expand (hygienic when parameterized; splice when parameterless) |
form | form NAME for SEMANTIC { ... } | Declares one legal machine-code encoding/operand/decorator realization |
register | register NAME = physical|flag|system CID [arch N] [offset B] [count N]; | Declares an architectural register or contiguous register bank |
fault | fault NAME = "MNEMONIC" trigger TRIGGER class CLASS; | Declares an architectural fault/trap identity |
table | table NAME : bits<W> = { v0, v1, ... }; | Declares a compile-time / lut byte table |
opaque intrinsic | opaque intrinsic NAME { ... } | Declares a typed OpaqueIntrinsic descriptor |
write_hook | write_hook NAME on register BANK max_bits N { ... } | Dispatch-time transformer bracketing writes to a register bank (e.g. ARM64 AdvSIMD V→Z overlap) |
Types, Widths & Meta-Expressions
Every value has a positive bit width : bits<M>, where M is an ImmExpr meta-expression:
- Literals & parameters:
bits<8>,bits<64>, templatewidthparameters (bits<w>), numericstatic forloop indices (ImmExpr::Lane,ImmExpr::OuterLane(k)). - Symbolic width leaves:
dst_width,dst_width_x2,half_dst,addr_width,stack_width,elem_bits,lane_count,entry_narrow_bits,insn_addr,next_addr,lane,operand_width,embedded_rounding,insn_word,guest_addr_width,x86_fpu_opcode. - Operand builtins:
operand_width(n),imm_of_operand(n),operand_reg_num(n),mem_scale(n),mem_disp(n),mem_segment(n),operand_lane(n),operand_lane_bits(n),operand_shift(n), etc. - Meta arithmetic & folding:
add,sub,mul,div,shl,shr,and,xor,eq,ne,lt,le,gt,ge,mask,lit(...).
Statements, Expressions & Templates
language asem 1.0;
module x86.bmi2_shift;
template shift_to_dest<Op: binop>() {
let src = read operand 1 : bits<dst_width>;
let count = read operand 2 : bits<dst_width>;
let mask = const sub(dst_width, 1) : bits<dst_width>;
let masked = binop and(count, mask) : bits<dst_width>;
let result = binop Op(src, masked) : bits<dst_width>;
write operand 0 <- result;
finish fallthrough;
}
program RORX route "RORX" = shift_to_dest<ror>();
program SARX route "SARX" = shift_to_dest<ashr>();
program SHRX route "SHRX" = shift_to_dest<lshr>();
program SHLX route "SHLX" = shift_to_dest<shl>();
- Slot allocation: Each fresh
let x = ...;claims the nextSlotin source order (@slot(n)pins an exact slot;@slots(n)sets minimum capacity). Re-binding an existing name (let x = ...;) reuses its slot in place. - Compile-time specialization:
static if PRED { ... } else { ... }selects at instantiation or emitsStaticIf(is_vector,long_mode,has_broadcast,has_embedded_rounding,mask_zeroing,operand_is_memory(i),predicate_is(COND), etc.).static for I in 0 .. Nlowers toUnroll;static for X in { ... }unrolls at compile time. - Value & vector ops:
binop,unop,cmp,zext,sext,trunc,resize,snapshot,select,funnel_shift,vec_binop,vec_unop,vec_compare,vec_reduce,vec_broadcast,vec_extract,vec_insert,vec_resize,vec_shift_var,lut, plus explicit-rounding scalar/packed floating point (fp_binop,fp_binop_ex,fp_fma_ex,fp_unop_ex,fp_compare,fp_convert_ex,fp_to_int_ex,int_to_fp_ex,vec_fp_*). - Status flags (
emit_flags&flagsblocks):emit_flagsinvokes the manifest-driven flag engine (entry,logic,add,sub,adc,sbb).flags over(...) [when C] [covers status|nzcv] { ... }declares per-flag symbolic expressions (withzf,sf,pf,carry_add,carry_sub,borrow_sub,overflow_add,overflow_sub,aux_*,undefined,preserve, or recipe arms). Canonicalflagsblocks lower to the exact shared flag-engine micro-op. - Memory & atomics:
load,load_cond,store,store_cond,probe_write,load linear,store linear,segment_address,atomic_rmw,atomic_cmpxchg,load_excl,store_excl,clear_reservation, andfence. Qualified memory accesses supportunprivileged,volatile,ordered <ORDERING>,space data|code|io, andguest_atomicity(...). - Predicated writes (
when):when COND { write reg ...; }lowers toWriteRegCond/ApplyWritebackCond(pure expressions execute unconditionally; only architectural register writes and writebacks are predicated). - Compound phases & terminals: Non-delay compound instructions partition top-level ops via
phase operation 0 { ... } phase memory 0 { ... } phase completion { ... }. Terminals includefinish fallthrough;,jump,branch,switch,call ... link ... timing ...;,stop halt|wait|unreachable;,trap ...;,fault NAME [when COND];,require C "reason";, andfinish rep ... body ... latch ...;.
choose & opaque intrinsic
Nondeterminism (choose)
let undef_cf = choose unspecified : bits<1>;
let z_choice = choose constrained_unpredictable scope instruction_execution key 0x5356455a4552_4f55 values(0, 1) : bits<1>;
- Kinds:
unspecified,constrained_unpredictable,implementation_defined,environment,entropy,uninitialized. - Scopes:
fresh_per_observation,produced_value(default),instruction_execution,execution_session,machine_profile,externally_supplied(correlation scopes requirekey N). - Domains: Unrestricted by default, or
values(v0, v1, ...)for finite domains.
Structured Opaques (opaque intrinsic)
opaque intrinsic CPUID_LEAF {
identity: "x86.cpuid";
revision: 0;
reason: architecture_intrinsic;
inputs: (value : bits<32>, value : bits<32>);
outputs: (value unknown : bits<32>, value unknown : bits<32>,
value unknown : bits<32>, value unknown : bits<32>);
registers: (
reg EAX read, reg ECX read,
reg EAX write output(0), reg EBX write output(1),
reg ECX write output(2), reg EDX write output(3)
);
memory: none;
faults: none;
control: fall_through;
choices: ();
volatile: false;
fidelity: opaque_dataflow;
}
@preserve_form programs wrap a single zero-input/zero-output opaque intrinsic for RecompilationDisposition::PreserveForm rows (such as PAUSE).
form Declarations
form declarations describe legal machine-code realizations independently of semantic behavior:
form LOCK_ADD for atomic_add {
decoder "Add_rm64_r64";
family legacy;
modes(64);
operand 0 read_write mem any : bits<64>;
operand 1 read reg gpr : bits<64>;
prefix lock required;
}
Forms support value extensions (sign_extend/zero_extend/truncate to bits<W>), destination parent write policies (preserve/zero_extend/sign_extend), EVEX mask/zeroing/sae/rounding/evex_b, vsib, fixed, implicit, immediate, upper_lanes, alternative, memory legality contracts, address overrides, and Knights Corner mvex conversions/swizzles/eviction hints.
Canonical Verification & Static Lints
Every program runs archsem-core's canonical verifier during compilation, rejecting slot errors, width mismatches, and unproved partial operations (NonZeroDivisor obligations can be discharged in-program via explicit guards/selects or deferred to per-instruction verification).
Additionally, passing --lint (or annotating @lint / @allow(...)) enables four cross-cutting static lints in archsem-lang:
form_mismatch: Cross-checks everyformcontract against the inferredProgramEffectSummaryacross syntheticInsnViewrealizations (operand read/write directions, memory access contracts, and implicit flags).fault_after_commit: Flags uncommitted architectural register, flag, or operand writes that precede a potentially faulting memory access or trap/fault check without an interveningcommit;ortransaction progressive;.unhygienic_fragment: Flags legacy parameterless splice fragments in favor of hygienic parameterized fragments.duplicate_register: Flags distinctregisterdeclarations in the same unit that alias an identical(role, cid, arch, offset)identity.
Compiler, LSP & Exporters
Architectura separates authoring-time host tooling from the runtime semantic libraries: archsemc, archsem-lang, archsem-lsp, archsem-gen, archsem-export, and archsem-uops-info are host-only tools and are never cargo build dependencies of archsem-core, archsem-x86, or archsem-arm64.
archsemc: The Asem Compiler CLI
archsemc drives archsem-lang to type-check, verify, format, inspect, and emit Rust modules or portable .asemc packages from .asem sources.
Commands & Flags
# Parse, type-check, and run the canonical verifier (add --lint for static lints)
archsemc check [--lint] [--deny-dead-values] <file.asem>
# Emit checked-in Rust to stdout
archsemc build --emit rust <file.asem>
# Write or drift-check a generated Rust file (--out <path> is REQUIRED with --write or --check)
archsemc build --emit rust --out archsem-x86/src/generated/opmask_programs.rs --write semantics/x86/opmask.asem
archsemc build --emit rust --out archsem-x86/src/generated/opmask_programs.rs --check semantics/x86/opmask.asem
# Use --source-label to set a custom provenance banner path (used by ARM64 modules)
archsemc build --emit rust --source-label semantics/arm64/<name>.asem \
--out archsem-arm64/src/programs/<name>.rs --write semantics/arm64/<name>.asem
# Emit a portable, re-verifiable .asemc package
archsemc build --emit asemc --out path/to/output.asemc --write <file.asem>
# Check or normalize canonical whitespace (LF, 4-space tabs, no trailing spaces)
archsemc fmt --check <file.asem>
archsemc fmt --write <file.asem>
[!IMPORTANT] When running
archsemc buildwith--writeor--check, you must pass--out <path>. Omitting--outdefaults to--stdout(and returns an error if--writeor--checkis specified).
archsemc schematic: Symbolic & Graph View
archsemc schematic reconstructs a verified program into folded, architecturally named expressions (using the file's register declarations and ISA flag spellings):
archsemc schematic semantics/arm64/conditional_ops.asem --program CCMP
program CCMP route "CCMP" arm64.conditional_ops · 22 slot(s), 27 top-level op(s)
reads op0 op1 cond
writes N Z C V
memory none
control fall-through
render complete
%cond : 1 = cond_holds(insn.cond)
%r : W = op0 - op1
N <- %cond ? %r <s 0 : imm(op2)[3]
Z <- %cond ? %r == 0 : imm(op2)[2]
C <- %cond ? op0 >=u op1 : imm(op2)[1]
V <- %cond ? ((op0 ^ op1) & (op0 ^ %r)) <s 0 : imm(op2)[0]
end fall-through
Pass --emit dot for Graphviz DOT or --emit json for machine-readable dataflow graphs (--internal includes non-routed subprograms; --out <path> writes to disk). The archsem-lang test suite enforces render complete across the entire checked-in semantics/ corpus.
archsem-lsp & the Zed Extension (editors/zed/asem)
archsem-lsp is the Language Server Protocol front end for Asem:
archsem-lsp [--trace FILE] # Speak LSP over stdin/stdout
archsem-lsp --check-json NAME # Compile stdin and emit JSON diagnostics (isolated subprocess)
It provides:
- Live diagnostics from the canonical
archsem-coreverifier (including imported declarations) - Hover information showing verified slot and top-level micro-op counts
- Inlay hints displaying allocated
@slotnumbers onletbindings - Completion and full semantic token highlighting (Asem has no tree-sitter grammar; highlighting is driven by LSP semantic tokens)
The companion Zed editor extension lives in editors/zed/asem (targeting wasm32-wasip2). Configure Zed with "semantic_tokens": "full" and "inlay_hints": { "enabled": true } under "languages": { "Asem": { ... } }, and install via editors/zed/asem/install.ps1 (or Zed's install dev extension).
archsem-export: Semantic Table & Coverage Export
archsem-export (publish = false, host-only) exports audited declarative tables, resolved SemPrograms, ImplementationDispositions, and decoder-catalog coverage as JSON:
archsem-export x86 > x86.json
archsem-export arm64 > arm64.json
archsem-export coverage x86 > x86-coverage.json
archsem-export coverage arm64 > arm64-coverage.json
archsem-export coverage x86 --profile x86.avx > x86-avx-coverage.json
archsem-export inspect x86 4801d8
archsem-export inspect arm64 d2800020
Coverage generation independently resolves each decoder form's implementation disposition (implemented, implemented_with_opaque_boundary, explicit_opaque, explicit_unsupported) and validates that every reviewed CoverageLabel (Faithful, Partial, Opaque, Absent) matches its implementation before emitting JSON.
archsem-uops-info: Offline Performance Importer
archsem-uops-info (publish = false, host-only) imports a caller-supplied, pinned uops.info instructions.xml snapshot offline (performing no network access during generation) using a crosswalk CSV (xed_iform,iced_code,mode):
archsem-uops-info \
--input path/to/instructions.xml \
--crosswalk path/to/crosswalk.csv \
--output x86_perf.json \
--coverage x86_perf_coverage.json \
[--dataset-version LABEL] [--dataset-date YYYY-MM-DD]
It validates exact case-sensitive iced Code spellings and execution modes (16, 32, 64), hashes the input XML with SHA-256 for provenance, and emits archsem-x86::performance dataset artifacts and coverage reports.
Normative Semantics Contract
This chapter distills the normative rules from SEMANTICS.md. In Architectura, semantic conformance is defined by this contract; Rust types and .asem syntax are implementations of it.
1. Semantic Objects & Behavior Sets
An instruction semantic definition maps:
- Exact instruction bytes and decoded operands
- A typed
DecodeContext(architecture, mode, canonicalEnabledFeatures, endianness, and bounded, revisionedDecodeArchitectureState) - Initial architectural state
- Architectural-choice and environment provider selections
to a behavior set B(X, P) under observation profile P. Each member execution consists of:
- An acyclic instruction-local event trace and typed
EventGraph. - One coherent terminal outcome (fallthrough, control transfer, or architectural fault/trap).
- The architecturally visible state delta at that outcome.
Decode context transitions MUST be explicit outputs; hidden mutable decoder state MUST NOT influence semantics.
2. Architectural Observables & Consumer Flag Demand
Under the full-observation profile, observables include:
- Writes, undefinedness, and preservation of architectural register slices and flags (distinguishing preserved vs. unwritten-unknown, at bit-slice granularity).
- Guest-memory reads, writes, atomics, reservations, fences, and declared memory events (retaining exact bit widths and byte masks).
- Direct and indirect control transfers, predicates, fallthroughs, link effects, delay-slot/repeat behavior, and mode transitions.
- Faults/traps, their class, priority, trigger point, and visible pre-fault state.
- Transaction checkpoints, partial-progress markers, memory ordering, and atomicity.
- Structured opaque effects and choice observations.
Consumer Flag Demand (FlagDemand)
FlagDemandis a consumer assertion about surrounding liveness, never an Architectura inference.- A consumer MAY drop a status flag from demand only when that flag is overwritten before any read on every path leaving the instruction—including fault, trap, exception, unwind, call, return, indirect transfer, and incomplete boundaries.
- Narrowing removes whole per-flag computations (and pure intermediates reaching only suppressed flag writes); it never rewrites a demanded flag's computation or suppresses memory, fault, fence, intrinsic, or register-read events.
- Repeat (
REP) body/latch programs always execute under full flag demand.
3. Values, Widths & Partial Operations
- Positive Bit Widths: Every value has a positive width (
1..=512bits).Int(1)is the predicate type. Arithmetic wraps modulo2^width; signedness is an operation property, not type state. - No Inherited Backend UB: Architectura never inherits undefined behavior or poison from Rust, C, or LLVM. Partial operations MUST have explicit boundary handling:
- Shifts/rotates require
count < width - Unsigned division/remainder requires
divisor != 0 - Signed division requires
divisor != 0and representable quotient (notINT_MIN / -1) ExtractElement,InsertElement, andIndexedRegisterBankaccesses require in-bounds lanes/indices
- Shifts/rotates require
- Mandatory Trust-Boundary Verification: Builder finalization, generated tables, and deserialized artifacts MUST pass the canonical semantic-program verifier before the first emitter call.
4. Effects, Guards, Transactions & Control
- Trace Order vs. Memory Order: Instruction-local trace order governs same-instruction visibility, exception priority, and checkpoint prefixes; inter-thread ordering MUST be stated explicitly via
MemoryOrdering/FenceRequest. - Guarded Suppression: A false guard on
LoadCond,StoreCond,LoadTry,ProbeWrite,TrapIf, orWriteRegCondsuppresses the event, its memory access, ordering edges, and associated faults (LoadCondyields0;LoadTryyields(0, false)). - Transaction & Progress Matrix:
TransactionModel | ProgressModel | Contract |
|---|---|---|
Restartable | Exact | Entry state or latest explicit Commit is visible on fault |
Progressive | Exact | Every preceding effect is visible in authored order |
Progressive | CanonicalPrefix | Emitted prefix is guaranteed visible; later permitted effects may also have completed |
PermittedMemorySubset | Exact | Registers/non-memory roll back to checkpoint; an implementation-selected subset of other memory mutations in the segment may be visible (excluding the faulting mutation) |
Combinations (Restartable, CanonicalPrefix) and (PermittedMemorySubset, CanonicalPrefix) are illegal. Commit requires at least one pending observable effect site since entry or the prior commit.
- Control Transfer: Every completed instruction has one coherent terminal record (
SemanticControl) retaining kind, direct/indirect destination, predicate, fallthrough, trap payload, link timing, delay-slot/repeat policy, mode switch, and fidelity/choice dependencies.
5. Architectural Choices
A Choice is a typed, domain-constrained source of allowed behaviors—never backend undef or poison:
- Kinds:
Unspecified,ConstrainedUnpredictable,ImplementationDefined,Environment,Entropy,Uninitialized. - Correlation Scopes:
FreshPerObservation,ProducedValue,InstructionExecution,ExecutionSession,MachineProfile,ExternallySupplied. - Lifecycle & Predeclaration:
InstructionExecutionchoices begin atbegin_instruction(or explicitInstructionExecutionGroupRoot/RepeatBody/RepeatLatchboundaries). Persistent scopes (ExecutionSession,MachineProfile,ExternallySupplied) require deterministic 128-bitChoiceBindingNamespacesviaChoiceBindingEnvironmentand MUST be predeclared before emitter mutation. - DCE Rule: Only an
Unspecifiedchoice atProducedValuescope with no correlation key and zero remaining uses may be deleted as dead pure computation; all other choices MUST be retained.
6. Faults, Unsupported Boundaries & Malformed Semantics
- Architectural Faults/Traps belong to the behavior set (carrying kind, class, priority, and visible prefix; OS exception dispatch is outside
archsem). - Unsupported Dispositions (
UnsupportedSemantics,BackendCapabilityError) fail closed before destination mutation—never silently becoming no-ops or unconstrained values. - Malformed Semantics (width mismatch, uninitialized slot, unhandled partial op, invalid domain, cycle, incoherent transaction) are rejected by validation before emission.
- Incompleteness Metadata: Partial CFGs carry explicit
IncompletenessState(Absent,Complete,Unknown,Unresolved) and finiteIncompletenessRecords; unknown/unresolved functions cannot be markedCompleteand are rejected by destructive transforms and executable replay.
7. Equivalence, Refinement & Fidelity Review Labels
Behavior-set relations compare B(L, P) and B(R, P):
Equivalent:B(L, P) = B(R, P)LeftRefinesRight:B(L, P) ⊂ B(R, P)RightRefinesLeft:B(R, P) ⊂ B(L, P)Unknown: insufficient evidence or bounds (MUST NOT be reported asEquivalent)
Architecture catalogs map (SemanticCoverage, SemanticImplementationDisposition) to exactly one reviewed CoverageLabel:
CoverageLabel | Required SemanticCoverage | Required Disposition |
|---|---|---|
Faithful | Exact | Modeled semantics |
Partial | ConservativeOverapproximation, Underapproximation, or MixedPartial | Modeled semantics |
Opaque | OpaqueDataflow | Structured opaque semantics |
Absent | Unsupported | No executable semantics provider |
8. Resource Limits (ResourceLimits)
All decoding, validation, artifact loading, provenance construction, and CFG discovery enforce explicit finite bounds (ResourceLimits: input_bytes, string_bytes, decode_rows, decode_fields, program_ops, expression_nodes, nesting_depth, expansion_ops, value_slots, intrinsic_arguments, identifiers, lookup_table_bytes, permutation_elements, register_list_entries, instruction_bytes, instruction_operands, ir_values, ir_events, dependency_edges, cfg_blocks, cfg_edges, diagnostics). Exceeding a bound fails cleanly with LimitExceeded before mutation.
Canonical Wire & Artifacts
Architectura defines two complementary serialization contracts:
- Canonical Semantic Wire (
archsem_core::canonical): A deterministic,serde-independent binary encoding used for content-addressed semantic fingerprints (fragment and whole-function dual fingerprints). - Versioned Artifact Envelopes (
archsem_core::artifact,archsem-ir,archsem-symex,archsem-conformance): Self-identifying, resource-bounded JSON/RON envelopes for runtime-loaded semantic programs, decode tables, symbolic execution reports, proof obligations, and oracle exchanges.
Canonical Binary Wire (archsem_core::canonical)
Defined normatively in CANONICAL_WIRE.md, CanonicalEncode requires every encoded struct field and enum variant to be named explicitly—adding a Rust enum variant never silently assigns a wire tag.
Primitive & Aggregate Encodings
| Type | Wire Format |
|---|---|
u8, u16, u32, u64, u128, i64 | Fixed-width little-endian two's complement |
usize | Admitted only if it fits u64; encoded as little-endian u64 (lengths only) |
bool | 0x00 (false) or 0x01 (true) |
| Byte strings & UTF-8 text | u64 byte length ` |
| Enum tags | Normative UTF-8 tag strings |
Option<T> | 0x00 (absent) or `0x01 |
| Wide bitvectors | u16 width ` |
| Sequences | u64 item count ` |
| Maps | Sorted lexicographically by the complete canonical bytes of each key (duplicate canonical keys rejected) |
Recursive semantic-program encoding is bounded by MAX_CANONICAL_NESTING and the caller's byte limit.
Dual Fingerprints (Definition vs. Lift Instance)
archsem-ir fragments and complete Functions expose two SHA-256 canonical projections (current core canonical wire revision 2, embedded by neutral fragment schema 2.2 and neutral function schema 2.2):
| Projection | Retained | Redacted |
|---|---|---|
| Semantic-Definition | Wide constants, architectural choices, ordered events, unified control shape, semantic sites, origin-DAG topology, relocatable PC + displacement basis/displacement, dense first-occurrence InstructionExecutionGroup ordinals (or group-id-redacted on standalone fragments) | Concrete instruction address, exact bytes, decode-context instance, direct control addresses, concrete relocatable PC base/value |
| Lift-Instance | Everything in definition plus specification revision, exact architecture/decode-state identity, bytes/address, decoder options, code epoch, semantic-program revision, exact InstructionExecutionGroup IDs, and concrete relocatable bases | None |
[!NOTE] Schema major
1(which embeddedserde_jsonwire) is intentionally rejected by revision2. Within a major version, existing tags, widths, and field orders never change; additive IR vocabulary increments the minor version (e.g.,2.1addedextract-element/insert-element;2.2addedinstruction-execution-group). Golden fixtures pin the exact canonical bytes and SHA-256 digests.
Versioned JSON & RON Artifact Envelopes
Runtime-loaded programs and decode tables cross an explicit trust boundary in archsem_core::artifact (serde feature):
- Envelope:
ArtifactEnvelope<T>carries:schema:"archsem.semantic-artifact"(ARCHSEM_ARTIFACT_SCHEMA)version:SchemaVersion { major: 1, minor: 0 }(ARCHSEM_ARTIFACT_VERSION)kind:ArtifactKind::SemanticProgram("semantic_program") orArtifactKind::DecodeTable("decode_table")payload:OwnedProgramorOwnedDecodeTable
- Loaders:
load_program_json,load_program_ron,load_decode_table_json,load_decode_table_ron. - Fail-Closed Admission:
- Checks
ResourceLimits::input_bytesbefore parsing. - Rejects wrong
schema, incompatiblemajorversion, and newer unsupportedminorversions (never assuming unknown fields are inert). - Validates the decoded payload structurally (
ExecutableProgram/OwnedTableDecoder) before returning or leaking any process-lifetime state.
- Checks
- Legacy
UndefRejection: Artifacts containing removed pre-v0.2Undefencodings are rejected at admission rather than silently mapped toChoice.
Other versioned bounded artifacts in the workspace follow the same hostile-input admission pattern:
archsem-symex:ExecutionReportArtifact,ConcolicExecutionArtifact,ProofObligationArtifact,InstructionValidationArtifact,InstructionCounterexampleArtifactarchsem-conformance:ExternalOracleRequest/ExternalOracleResponse,OracleDisagreementArtifactarchsem-lang/archsemc:.asemcportable semantic packages
API Stability & Releasing
This chapter summarizes Architectura's public API evolution rules (docs/api-stability.md), external formal oracle protocol (docs/external-formal-oracles.md), deterministic performance baselines (docs/performance-baselines.md), and staged release process (docs/releasing.md).
Public API Stability Policy
Architectura is currently pre-0.2: semantic and artifact contracts are versioned and validated, while deliberate public API refinements remain permitted until 0.2 is cut (monitored via cargo-semver-checks on portable libraries in CI).
Closed Vocabulary vs. Extensible Boundaries
- Closed Semantic Vocabulary (Exhaustive Matching): Representation-bearing types that are the portable semantic language—
archsem_core::IrEmitter,SemProgram,MicroOp, control/memory/fault/choice/decode contracts,archsem_record::SemanticAction, andarchsem_irRTLNodes, events, origins, and SSA records—may be matched exhaustively. Adding a primitive is a semantic language change so consumers are never silently incomplete. - Open-Ended Results (
#[non_exhaustive]): Failures, resource/boundary reasons, evidence classifications, and backend capability outcomes use#[non_exhaustive]so callers fail closed or preserve unknown future cases. Analysis-internal arena indices (e.g.,archsem-symexexpression nodes) are opaque behind typed accessors.
Extension-Point Taxonomy
Public extension points follow six explicit roles:
| Suffix | Responsibility |
|---|---|
Emitter | Receives the portable semantic vocabulary and constructs another IR (RtlEmitter, LlvmEmitter, ReferenceEmitter) |
Environment | Supplies concrete external state and records effects (ConcreteEnvironment, ReferenceEnvironment) |
Policy | Chooses a bounded analysis action without supplying machine state (MemoryPartitionPolicy, MemoryPolicy, CallPolicy) |
Provider | Supplies caller-owned facts, summaries, choices, or supplements (ChoiceProvider, CallSummaryProvider, OriginSupplementProvider) |
Sink | Consumes an exported stream or obligation (FunctionReplaySink, RegisterSsaReplaySink, ProofObligationSink) |
Adapter | Translates to an external framework or toolchain |
External Formal Oracle Sidecar Protocol (archsem-conformance::external_oracle)
To validate semantics against independently installed formal ISA models (Arm ASL, K x86-64, ACL2 x86isa) without embedding external toolchains, licenses, or command execution into archsem, archsem-conformance::external_oracle defines a bounded JSON/RON exchange protocol:
archsem process independently managed sidecar
--------------- -----------------------------
ExternalOracleRequest ──────────▶ translate & execute ASL / K / ACL2
ExternalOracleResponse ◀────────── observed / unsupported / unavailable
compare_external_result()
├─ Agreement
└─ OracleDisagreementArtifact
- Schemas:
archsem.external-oracle-request(v1.0) andarchsem.external-oracle-response. - Cryptographic Request Binding: Every response carries
request_binding(sha256canonical revision 1 over the complete validated request: architecture, profile, sorted context, address, bytes, initial registers/flags/memory, choices, environment inputs, and model name/version/revision), preventing response substitution. - Typed Non-Agreement:
unsupported(model lacks coverage or observation vocabulary) andunavailable(model_not_installed,license_not_accepted,toolchain_incompatible, timeout) remain distinct fromobservedmismatches (OracleDisagreementArtifact). - Maintained Differential:
archsem-conformance/oracles/x86isamaintains a pinned ACL2 8.5 /x86isadifferential fixture (48 89 d8MOV RAX, RBX) with source-hash verification (ARCHSEM_X86ISA_LIVE=1).
Deterministic Performance Baselines (archsem-benchmarks)
Rather than brittle wall-clock assertions in CI, archsem-benchmarks guards provider-pipeline regressions using deterministic work units, output units, SHA-256/checksum verification, and generous allocation ceilings stored in archsem-benchmarks/baselines/semantics_pipeline.json:
| Stage | Fixed Workload | Work Unit | Output Unit |
|---|---|---|---|
decode_lift | 384 instances from a 6-instruction x86 corpus | Decoded instructions + actions | Recorded actions |
vm_interpret | 32 interpretations of a 64-lane VM program | Verified expanded micro-ops | Recorded actions |
rtl_build | 1 fragment with 256 redundant outputs | RTL nodes built | Fragment events |
optimize | 1 copy of that redundant fragment | Simplifier node visits | Retained RTL nodes |
replay | 32 replays of the optimized fragment | Input RTL nodes replayed | Replayed record events |
bounded_symex | 8 executions of a depth-3, 15-block CFG | Symbolic execution steps | Completed return paths |
Run the CI deterministic check or local release calibration via:
# CI deterministic contract (work, output, checksum, allocation ceilings):
cargo test --locked -p archsem-benchmarks --bench semantics_pipeline -- --check
# Local calibration / median-of-7 release timing:
cargo bench --locked -p archsem-benchmarks --bench semantics_pipeline -- --calibrate
cargo bench --locked -p archsem-benchmarks --bench semantics_pipeline
Staged crates.io Release Procedure
Pre-Release Verification Gates (Rust 1.88)
cargo fmt --all -- --check
cargo test --locked --workspace --all-targets --all-features --exclude archsem-llvm
cargo check --locked --target wasm32-unknown-unknown --all-targets --all-features \
-p archsem-core -p archsem-record -p archsem-ir -p archsem-simplify \
-p archsem-symex -p archsem-ref -p archsem-conformance -p archsem-x86 -p archsem-arm64
cargo check --locked --target wasm32-wasip1 --all-targets --all-features \
-p archsem-core -p archsem-record -p archsem-ir -p archsem-simplify \
-p archsem-symex -p archsem-ref -p archsem-conformance -p archsem-x86 -p archsem-arm64
Staged Dependency Order
Publish portable crates in topological order, verifying each archive (cargo package --locked -p <crate> and cargo publish --locked -p <crate> --dry-run) and waiting for index visibility before packaging the next layer:
archsem-corearchsem-record,archsem-arm64,archsem-x86archsem-ir,archsem-conformancearchsem-simplifyarchsem-symex,archsem-ref(plus bytecode frontendsarchsem-wasm,archsem-evm,archsem-cil,archsem-lua)
Host-only tools (archsemc, archsem-lang, archsem-lsp, archsem-gen, archsem-export, archsem-uops-info, archsem-llvm) and the native archsem-capi library remain publish = false.