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

  1. Semantics as Verified Data (SemProgram) Most instruction semantics live as pure, static SemProgram tables of typed MicroOp instructions operating over a finite value-slot array. An interpreter (run / run_checked) executes a SemProgram against any IrEmitter, calling the exact same primitive methods a hand-written handler would—after running the canonical semantic verifier at the trust boundary.

  2. Control Flow Is Returned, Never Emitted (ControlEffect / SemanticControl) An IrEmitter has no br, jmp, or create_block methods. 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.

  3. Explicit Choice Instead of undef or Poison Architectura never lowers architectural uncertainty (undefined flags after DIV, entropy instructions, implementation-defined behavior, uninitialized state) to backend undef or LLVM poison. Instead, uncertainty is modeled as a first-class, typed, width-exact Choice carrying a ChoiceKind, a ChoiceScope correlation lifetime, an optional ChoiceKey, and a valid ChoiceDomain.

  4. 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.

  5. Fidelity Is Explicit, Never Approximated Silently Every semantic route carries a multidimensional SemanticFidelity record (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

SystemPrimary RepresentationControl FlowNondeterminism / UBTarget Independence
Architectura (archsem)SemProgram micro-ops + IrEmitter trait + archsem-ir RTLReturned as SemanticControl; CFG driver is separateTyped Choice with kind, scope, key, and domain; partial ops explicitZero target-IR deps in archsem-core; backends implement IrEmitter or consume archsem-ir
RemillC++ intrinsic templates compiled to LLVM bitcodeHandled by caller / AnvillRelies on LLVM semantics / __remill_undefined_* intrinsicsTightly coupled to LLVM IR
Ghidra P-CodeSleigh specifications compiled to p-code opsEmbedded intra-instruction branches + p-code relative jumpsUNIQUE / undefined op semantics; userops (CALLOTHER) lack typed contractsCoupled to Ghidra address spaces and p-code VM
BAP BILAlgebraic BIL statements in OCamlIntra-instruction jumps (jmp, cjmp)Unknown expressionsCoupled to BAP / OCaml ecosystem
Valgrind VEXC IRStmt / IRExpr superblocksIRJumpKind exits + dirty helpersImplicit via helper callsDesigned for dynamic instrumentation
QEMU TCGTiny Code Generator opsTCG branches / labels inside TBArchitecture helpers in CDesigned 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

NameMeaning
ArchitecturaThe overall repository and project (https://github.com/valeria-org/architectura).
archsemThe 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-orgThe 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 optional symex / ARCHSEM_SYMEX=ON feature in archsem-capi) depends on bitwright, 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:

  1. Decoding, lifting, and simplifying a single x86-64 instruction (add rax, rbx).
  2. Discovering and lifting a reachable control-flow graph (lift_reachable_stateless / Function).
  3. Executing an instruction concretely against the independent reference oracle (archsem-ref).
  4. One-call CFG lifting for WebAssembly (archsem-wasm) and EVM (archsem-evm).

[!IMPORTANT] MSRV & Feature Flags: Architectura requires Rust 1.88+ (Edition 2024).

  • archsem-x86 keeps its decoder adapter behind the iced feature (features = ["iced"]).
  • archsem-arm64 keeps its decoder adapter behind the farm64 feature (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

OptionDefaultDescription
ARCHSEM_SHAREDOFFBuild and link a shared library (libarchsem.so / .dylib / archsem.dll) instead of static
ARCHSEM_SYMEXOFFEnable bounded symbolic execution (archsem_symex_*). Links bitwright (PolyForm-Noncommercial-1.0.0)
ARCHSEM_CARGO_PROFILEreleaseCargo build profile (release, dev, etc.)
ARCHSEM_CARGO_TARGET_DIRBuild treeOverride Cargo's target directory
ARCHSEM_BUILD_EXAMPLESON when top-levelBuild 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=ON links bitwright, which is licensed under PolyForm-Noncommercial-1.0.0. Keep ARCHSEM_SYMEX=OFF if 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; one Lifter can lift across multiple threads simultaneously. Machine is single-threaded.
  • ABI Stability: archsem_abi_version() returns the major ABI revision (4) and archsem_abi_minor_version() returns the compatible minor revision (9). Options structs begin with uint32_t struct_size for 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

CratePurposeDefault FeaturesOptional FeaturesLicense
archsem-coreIrEmitter trait, SemProgram micro-op VM & verifier, ArchManifest, DecodeContext, ControlEffect / SemanticControl, Choice, OpaqueIntrinsic, canonical wire encoder[]serde (RON/JSON artifact loading & serialization)MIT
archsem-recordIrEmitter action-stream recorder producing validated RecordedInstruction traces[]serdeMIT
archsem-irRtlEmitter, Fragment, Function CFG discovery, OriginGraph provenance, SemanticFidelity, backward slicing, effect summaries, register & memory SSA, replay[]—MIT
archsem-simplifySelf-contained 1–512-bit known-bits, demanded-bits, and effect-aware integer simplification over archsem-ir[]—MIT
archsem-refIndependent bounded concrete reference executor (ConcreteEnvironment, ReferenceEmitter)[]arm64-guest (links archsem-arm64/farm64)MIT
archsem-symexBounded symbolic execution, concolic execution, proof obligations, and validation artifacts (backed by bitwright)[]serde, transform-checkMIT + bitwright (PolyForm-Noncommercial-1.0.0)
archsem-llvmReference LLVM 21.1 IR emitter (LlvmEmitter via llvm-sys) and SSA replay sink (host-only, publish = false)[]—MIT

Architecture Frontends

CrateTarget ArchitectureDefault FeaturesOptional FeaturesExternal Decoder / RuntimeLicense
archsem-x86x86 (16/32/64-bit)[]iced (iced-x86)iced-x86 (1.21, mvex)MIT
archsem-arm64AArch64 (A64, SIMD, SVE/SME, system)[]farm64 (fARM64)fARM64MIT
archsem-wasmWebAssembly modules & functionsEnabled (wasm)—fWASMMIT
archsem-evmEthereum Virtual Machine bytecodeEnabled (evm)—evm-disassemblerMIT
archsem-cilECMA-335 (.NET CIL) PE images & methodsEnabled (cil)—cildec, fNETMIT
archsem-luaLua 5.1–5.4 & LuaJIT bytecode chunksEnabled (lua)runtime (archsem-ref)fLUAMIT
archsem-pythonExperimental CPython 3.11.9 wordcode handler subset[]pythonSelf-contained wordcode decoderMIT

Bindings, Authoring Tooling & Verification

CrateRoleHost-only / PublishableLicense
archsem-capiC ABI (archsem.h), C++17 header (archsem.hpp), CMake target archsem::archsemNative library (publish = false); optional symex featureMIT (with symex: links bitwright under PolyForm-Noncommercial-1.0.0)
archsem-langAsem compiler library (lexer, parser, lowerer, Rust & .asemc emitter)Host-only (publish = false)MIT
archsemcAsem compiler CLI (check, build, fmt, schematic)Host-only (publish = false)MIT
archsem-lspLanguage Server Protocol server for .asem filesHost-only (publish = false)MIT
archsem-genChecked-in semantic-family generatorHost-only (publish = false)MIT
archsem-exportMachine-readable JSON exporter for semantic tables and coverage catalogsHost-only (publish = false)MIT
archsem-uops-infoOffline importer for pinned uops.info XML snapshotsHost-only (publish = false)MIT
archsem-conformanceShared cross-component conformance corpus, adversarial fixtures, and external_oracle sidecar protocolPublishable (MIT)MIT
archsem-examplesRunnable target-neutral public API examplesWorkspace examples (publish = false)MIT
archsem-benchmarksDeterministic provider-pipeline performance baselinesWorkspace bench (publish = false)MIT

[!TIP] editors/zed/asem is a wasm32-wasip2 Zed editor extension built independently by Zed's extension builder (excluded from the Cargo workspace so cargo does 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 both wasm32-unknown-unknown and wasm32-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.1 llvm-config on PATH), 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

ScopeLicenseNotes
Workspace default & all crates except archsem-symexMIT 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/)MITPinned 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: IrEmitter intentionally lacks branch, jump, or basic_block. Every execution returns a ControlEffect<E::Value> or SemanticControl<E::Value>.
  • #[non_exhaustive] operation enums: BinOp, UnOp, CmpOp, FpOp, FpUnOp, FpCmp, and AtomicOp can gain new variants without breaking existing emitters.
  • Lifecycle boundary (begin_instruction): Establishes the boundary for InstructionExecution choices 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 via CompoundInstructionSpec (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: CpuMode and manifest-selected decoder_mode: DecoderModeId
  • enabled_features: EnabledFeatures: canonical, sorted, duplicate-free DecodeFeature set admitted under ResourceLimits
  • endianness: Endian: decode-dependent byte order
  • state: S: DecodeArchitectureState: bounded, revisioned architecture-specific state (or NoDecodeState)

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 E
  • arch: &'a ArchManifest — declarative register file, flag model (including CarryPolarity), CPU modes, address spaces, segmentation model, and stack direction
  • mode: CpuMode and profile: ModeProfile (address/operand/stack widths, pc_read_bias, SegSemantics)
  • insn_va: u64 and next_va: u64
  • image: Option<&'a dyn ImageReader> and binary_mode: BinaryMode
  • arch_state: &'a mut dyn ArchState — optional lift-time state (plus ArchState::post_instruction for 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 to next_va
  • Jump { target } — direct or indirect jump (with ModeSwitch)
  • Branch { cond, taken, fallthrough, delay_slots, annul } — 1-bit predicate, taken Target, fallthrough VA, and delay-slot/annul policy (AnnulRule)
  • Call { target, return_to } — call transfer with continuation VA and explicit ControlLink timing (before_transfer, before_delay_slots, after_delay_slots)
  • Return { target: Option<V> } — register-based (ARM64 X30) or stack-popped (x86 RET)
  • Trap { kind: FaultKind } — terminal architectural fault/trap (with optional TrapPayload)
  • Switch { value, cases, default } — direct multi-way branch
  • Rep { cond, body, latch, entry } and LoopLatch { cond } — driver-instantiated runtime repeat loops (such as x86 REP/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-independent name + revision (u32)
  • reason: OpaqueReasonCode — why it is opaque (ArchitectureIntrinsic, ExternalEnvironment, ImplementationDefined, PatternOpaque, etc.)
  • inputs: Vec<OpaqueInput> and outputs: 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> — exact Slice, Flag, Storage, or explicit aggregate (AllRegisters, AllFlags, AllArchitecturalState) effects (Read, Write, Preserved, Undefined, ConservativeClobber)
  • memory: OpaqueMemoryBehavior, faults: OpaqueFaultBehavior, control: OpaqueControlBehavior, choices: Vec<OpaqueChoice>
  • volatile: bool and fidelity: 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:

DimensionVariants
ChoiceKindUnspecified, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, Uninitialized
ChoiceScopeFreshPerObservation, ProducedValue, InstructionExecution, ExecutionSession, MachineProfile, ExternallySupplied
ChoiceDomainAny, 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 stable ChoiceBindingIdentity, 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 REP loops), InstructionExecutionGroup (Root, RepeatBody, RepeatLatch) and predeclare_instruction_execution_choices correlate InstructionExecution choices 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) where role is Physical, Flag, or System.
    • On x86, AL/AX/EAX/RAX share cid = 0, offset = 0, while AH has cid = 0, offset = 8.
    • On AArch64, W0 and X0 share cid = 0, offset = 0, and V0 is the low 128-bit slice of Z0.
  • RegisterDesc: RegisterId paired with exact access width bits: 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, AArch64 Wn→Xn, VEX/EVEX vector writes).
  • IndexedRegisterBank: Runtime-indexed register banks (such as x87 ST(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 (with AddressSpaceAliasGroup), address_width_bits, data_width_bits, addressable_unit_bits (AddressableUnitWidth), and MemoryEndian (Little, Big, Unknown).
  • Access & strictness: MemoryVolatility, MemoryOrdering (including AcquirePerLocation for Arm RCpc and *_LimitedRegion for FEAT_LOR), Atomicity (NonAtomic, Atomic, GuestDefined), ReservationAction, MemoryAlignment, MemoryPrivilegePolicy, GuardPolicy, MayFaultPolicy, and TransferMask.
  • Compound events: MemoryEventContract pairs MemoryEventDescriptor (Read, Write, Rmw, CompareExchange, LoadExclusive, StoreExclusive, Fence, CacheMaintenance, OpaqueMemory) with runtime MemoryEventBindings (predicate, dynamic mask, passthrough).
  • Write probes: IrEmitter::probe_write checks store-permission faults over data_bits without writing data or changing memory.

Fault & Transaction Matrix

Each executed SemProgramRef is a transaction-metadata region governed by (TransactionModel, ProgressModel):

TransactionModelProgressModelSemantics on Fault
Restartable (default)Exact (default)Entry state or latest explicit Commit checkpoint is visible
ProgressiveExactEvery preceding effect is visible in exact authored order
ProgressiveCanonicalPrefixEmitted prefix is guaranteed visible; later permitted effects may also have completed
PermittedMemorySubsetExactRegisters/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, and ChoiceSpec descriptors.
  • Materializes terminal control as a distinct final event (EventId::TERMINAL) inside Fragment::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..=512 bits, sharing archsem_core::bitvec exact evaluation, never folding partial-operation UB into constants)
  • Copy/identity propagation and commutative canonicalization
  • Conservative GVN (never commoning Load, ReadReg, Fp*, Opaque*, or distinct Choice identities; pure expressions reusing one stable produced choice are eligible)
  • False-predicate memory simplification (converting a statically false LoadCond to Const(0) and dropping a statically false StoreCond / 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 dependence
  • Address(ValueId) — effective-address dependence
  • ControlPredicate(ValueId) — branch/guard predicate dependence
  • IndirectTarget(ValueId) — computed transfer target
  • RegisterIndex(ValueId) — dynamic indexed-bank selector
  • RegisterSlice(RegisterId) / Flag(RegisterId) — architectural register/flag dependencies
  • MemoryVersion — instruction-local memory ordering
  • EffectOrder / FaultOrder — checkpoint, barrier, and fault precedence
  • ReservationState(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_fragments composes straight-line fragments (retaining each fragment's optional InstructionExecutionGroup) and summarizes register reads/writes/preserved slices (using the ArchManifest if provided, or conservative raw descriptors otherwise), memory effects, faults, requirements, and uncertainty boundaries.
  • Function::cfg_effect_summary summarizes 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 via OriginSupplementProvider)
  • Semantic sites (SemanticSite: program identity, revision, nested MicroOpPath, operand role, lane)
  • Ordered bundle membership (OrderedBundleMember for 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_stateful keys 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 to archsem.
  • Bounds & Incompleteness (Completion): CfgLiftConfig bounds address_range, extra_ranges, additional_entries, max_instruction_bytes, max_instructions, max_blocks, max_total_bytes, max_switch_cases, and decode_limits. If discovery hits a decode failure, unsupported instruction, or resource limit, it attaches a bounded IncompletenessRecord and returns a CfgLiftFailure containing the partial Function (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; REP instructions lower into Root, RepeatBody, and RepeatLatch InstructionExecutionGroup fragments.
  • 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:

  1. RegisterSsa::build(&function, &arch) Promotes architectural parent registers (ParentReg) into SSA values with block-entry RegisterPhis across diamonds and loops. Understands x86 nested GPR slices (AL/AH/AX/EAX/RAX), AArch64 Wn→Xn zero-extension, and vector parent clearing/merging policies.
  2. StackMemorySsa::build(&function, &arch) & optimize_stack_memory Identifies exact, non-overlapping affine SP ± const slots when SP is stable and no call, unwind, atomic, conditional, or opaque memory boundary intervenes. Under StackMemoryConfig::strict(), no loads or stores are eliminated; under assume_private_stack_accesses_non_faulting(), dead private stack stores can be removed.
  3. ConservativeMemorySsa::build(&function) / build_with_partition & MemoryDependencyGraph Assigns whole-memory tokens (MemoryToken) across arbitrary-address loads, stores, atomics, fences, opaque intrinsics, and call clobbers. Callers may supply a labeled MemoryPartitionPolicy to separate disjoint memory classes. MemoryDependencyGraph::build projects 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 typed ObservationBindingRoles. Caller hypotheses live separately in ObservationAssumptionSet (AssumptionHint).

Replay (replay, replay_cfg, replay_register_ssa)

  • Fragment::replay(&mut emitter): Replays an instruction fragment into any IrEmitter, predeclaring persistent choices and installing per-event and terminal SemanticSites.
  • Function::replay_cfg(&mut sink): Replays raw blocks, transaction regions, grouped repeat roles, and prioritized ExceptionalEdges with ExceptionalMemoryState visibility descriptors into a FunctionReplaySink.
  • Function::replay_register_ssa(&mut sink) / replay_register_ssa_with_calls: Lowers sparse live-in block parameters (ParentReg), edge-parallel EdgeAssignment batches, partial-parent reconstruction, and injected CallSummarys into an executable RegisterSsaReplaySink (such as archsem-llvm). Before mutating backend state, replay checks ReplayCapabilities against the function's ReplayRequirements.

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 when max_iterations or max_node_visits is 0.
  • Candidate rewrites are validated against Fragment::validate() / Function invariants and remapped across OriginGraph and EffectSummary before 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: Separate known_zero and known_one bitmasks (1..=512 bits).
  • 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::bitvec with archsem-ir and archsem-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, narrowing OutputDemand is 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

CategoryRuleId Variants
Constants & IdentitiesConstantFold, AddZero, SubZero, MulOne, MulZero, BitwiseIdentity, BitwiseAnnihilator, ShiftZero, DivideOne, RemainderOne, ConvertNoop
Same-Operand & SelectSameOperand, SelectConstant, SelectSameArms, CompareSameOperand
Boolean & ComparisonsBooleanCompare, CompareInversion, CompareCanonicalOrder, SelectToMask, KnownMaskRedundant, KnownConstantResult
Algebraic & BitwiseDoubleUnary, AffineCancellation, NegatedArithmetic, ComplementaryBitwise, ConversionChain, RotateInverse
Packed LanesExtractInsertedLane, 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).
  • Unspecified choices at ProducedValue scope without a correlation key may be eliminated by DCE only if all uses are gone; keyed InstructionExecution, FreshPerObservation, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, and Uninitialized choices are preserved.

Per-Rule Decision Telemetry

RuleStats / RuleDecisionStats distinguishes:

  • considered, applied, declined (proof refused), deferred (another rule fired first)
  • choice_sensitive and potentially_invalid orthogonal flags
  • budget_limited when stopped at SimplifyOutcome::IterationLimit or SimplifyOutcome::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:

ModuleContents
Archsem/Word.leanConcrete BitVec semantics and explicit invalid-partial-operation reasons
Archsem/Expr.leanTyped pure expressions, lazy select, inputs, and site/correlation-keyed Choices
Archsem/Rewrite.leanAll 31 RuleId names plus proof-carrying local steps, congruence, and guarded cancellation/annihilator rules
Archsem/Behavior.leanObservation profiles, protected event contracts, domain-checked choice plans, behavior sets, and certified deletion-ledger cleanup
Archsem/CFG.leanScope/epoch/generation-indexed CFG completion, unique block/entry obligations, closed targets, total outer-value remapping, and sealing certificates
Archsem/Soundness.leanMain theorem simplifyFragment_behavior_equiv, complete mapping records, and transactional rollback
Archsem/Examples.leanRegression 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 Rust choose_rewrite implementation itself, which is cross-checked by archsem-simplify property suites and archsem-symex's transform-check feature.

Execution, Recording & Lowering

Architectura provides four execution and backend consumers alongside archsem-ir:

  1. archsem-ref — Independent bounded concrete reference oracle
  2. archsem-symex — Self-contained bounded symbolic & concolic execution and proof obligations
  3. archsem-record — Action-stream recorder (IrEmitter → serializable RecordedInstruction)
  4. 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 return PartialOperation instead of panicking or inheriting host overflow.
  • Pluggable Environment (ReferenceEnvironment): Composes RegisterEnvironment, MemoryEnvironment, ChoiceEnvironment, FloatingPointEnvironment, and OpaqueEnvironment.
    • The stock ConcreteEnvironment stores exact (RegisterId, bits) cells and byte-addressed sparse memory keyed by (AddrSpace, BitVector).
    • Optional arm64-guest feature connects ConcreteEnvironment::with_arm64_bindings and with_arm64_services to exact AArch64 FP, SVE/SME VL/SVL, MOPS, MTE, RCW/LSFE, LS64, and TIndex policies.
  • Fault Visibility (ReferenceExecution::visible_state): ReferenceExecution separates raw environment mutations (outcome: ExecutionOutcome) from ArchitecturallyVisibleState (Exact, CanonicalPrefix, PermittedMemorySubset, or Unsupported(ReferenceVisibilityBoundary) when an eager environment cannot roll back a Restartable fault).
  • Suspensible Opaque Execution: ReferenceEmitter::suspend() / ReferenceEmitterState::resume() allows embeddings (such as archsem-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-symex depends on bitwright (PolyForm-Noncommercial-1.0.0). Noncommercial use is free; commercial use requires a license from bitwright's licensor.

Symbolic Engine & bitwright Integration

  • Context-Owned Arena (ExprArena): Structurally interned 1–512-bit expressions with exact widths, ternary selects, conservative symbols, and scoped Choices (FreshPerObservation, ProducedValue, InstructionExecution, persistent scopes).
  • Total Translation + Definedness Guards: Each node translates into a total bitwright bitvector value paired with a 1-bit invalidness guard (1 iff 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 bitwright constraints (known bits, signed/unsigned ranges, equality classes) and prunes only proven contradictions. Reported expressions are simplified (and optionally equality-saturated via SimplificationBudgets::max_saturation_work_per_expression) deterministically.
  • Nested Resource Budgets (ExecutionConfig): Independently caps PathBudgets (max_steps_per_path, max_paths, max_block_visits_per_path), ExpressionBudgets, SubstitutionBudgets, RecursionBudgets, MemoryBudgets, SimplificationBudgets, and DiagnosticBudgets. Each limit produces a typed BudgetKind exit.
  • Policy Boundaries (ExecutionContext): Unmodeled memory, opaque intrinsics, calls, fences, atomics, reservations, transactions, and faults fail closed with PathExit::Unsupported(UnsupportedReason) unless the caller injects a path-local MemoryPolicy (e.g., ExactByteMemory for concrete bytes), IntrinsicPolicy, CallPolicy, or EffectPolicy. 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-neutral ProofTermOp DAGs (tN topological 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 against InstructionCounterexampleArtifact to verify mismatches and map them backward through rewrite provenance.
  • Rewrite Checking (transform-check feature): check_fragment_transform and check_function_transform provide 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 a RecordedInstruction with stable EventIds, interned SemanticSites, and RecordedControlEffect.
  • With the serde feature enabled, RecordedInstruction serializes 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::Value is an LLVM integer of exact bit width (1..=512); registers use width-typed allocas in the prologue initialized with freeze undef (never raw per-use undef or poison); floating-point ops bitcast across float/double.
  • Choice Bindings: LlvmEmitter::new accepts non-persistent choices; LlvmEmitter::new_with_choice_bindings takes a ChoiceBindingEnvironment to 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-in enable_guest_fault_reporting_loads() lowers LoadTry to packed (data, fault) guest helper calls.
  • Register-SSA Lowering (RegisterSsaReplaySink): Function::replay_register_ssa lowers complete functions into LLVM basic blocks and phi nodes (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:

ConstantBit WidthSegSemanticsDescription
LONG6464-bitSegSemantics::NoneLong / 64-bit mode (FS/GS linear bases modeled explicitly)
PROT3232-bitSegSemantics::Descriptor32-bit protected mode (with optional architectural segmentation checks)
REAL1616-bitSegSemantics::RealMode16-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-personality Decoder<Insn = IcedInsn, State = NoDecodeState>.
  • IcedX86DecoderWithOptions(pub u32): Selects vendor/historical opcode personalities:
    • AMD — AMD decode differences (honours 66 operand-size prefix on near branches in 64-bit mode, UD0 without ModRM, LOCK MOV CR0 as MOV CR8, etc.)
    • KNC — Intel Knights Corner (MVEX and 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
  • #UD Handling: Complete invalid encodings (Code::INVALID) lift through the UD2 semantic row (#UD trap) rather than failing as truncated input.

Register Aliasing, Flags, and REP Loops

  • GPRs (cid 0..16): RAX–R15 use SubRegMap::X86Nested:
    • 8-bit low (AL) and high (AH, offset = 8) and 16-bit (AX) writes use RegisterWritePolicy::Preserve.
    • 32-bit (EAX) writes use RegisterWritePolicy::ZeroExtendParent into the 64-bit parent (RAX).
  • Status Flags (CarryPolarity::BorrowSet): CF, PF, AF, ZF, SF, OF, and DF are modeled as individual 1-bit RegisterRole::Flag registers (cid 1..7), while RFLAGS_CONTROL holds the remaining non-condition bits.
  • String Operations (REP/REPE/REPNE): Expand via ControlEffect::Rep into executable Root / RepeatBody / RepeatLatch InstructionExecutionGroups. REPE/REPNE CMPS/SCAS run each iteration in the latch and commit final flags on the terminating iteration, preserving pre-instruction EFLAGS beside committed RCX/RSI/RDI progress if a later iteration faults.
  • Atomic Routes: XCHG with a memory destination and LOCK-prefixed memory-destination RMW instructions select programs::atomic_program_for and emit AtomicEvents; illegal LOCK combinations 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-bit ST(0)..ST(7) stack (IndexedRegisterBank), FPCW, FPSW (reconstructing live X87_TOP), FPTW, and state-image layouts (FXSAVE/FXRSTOR, FNSAVE/FRSTOR, FNSTENV/FLDENV).
  • MMX (mmx.asem): Decoded operands touching MM0..MM7 dispatch to dedicated x87-aliased routes rather than silently aliasing XMM vectors.
  • SSE / AVX / AVX-512 (VEC_BASE = 0x100, K_BASE = 0x90):
    • XMM/YMM/ZMM alias 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## vs E##NF with probe_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 unless IrEmitter::opaque_expansion() enables OpaqueExpansion::CRYPTO or MATH.

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, versioned X86FormId digests (architectura.x86.form.v1) from symbolic iced Code names and X86ExecutionModes (13,028 reviewed iced 1.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 from uops.info via archsem-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 dedicated SP (cid = 31). Writing Wn (32 bits) uses SubRegMap::ArmLowHalf (ZeroExtendParent into Xn). XZR/WZR (cid = 32) is a sentinel outside the GPR bank that reads as imm(0) and ignores writes.
  • NZCV Flags (0x80..0x83) & Inverted Carry Polarity: ARM64_MANIFEST sets carry_polarity: CarryPolarity::BorrowClear. Unlike x86 (where SUB sets CF on borrow, ULt), ARM64 SUBS sets C on no-borrow (UGe). The shared flag engine (emit_flags) and Asem flags recipes 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 by FlowClass rather than carrying a SemProgram. conditional_branch_metadata(&Instruction) extracts exact ConditionalBranchPredicate (Flags(Cond), Zero, or Bit) plus resolved taken and fallthrough addresses 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 as ZT0 LDR/STR and LDAP1/STL1 forms) alongside the core fARM64 catalog.

FP/SIMD, SVE/SME Scalable State, and Extensions

Extension FamilyStorage & Semantic Modeling
AdvSIMD & FPV0–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 / SVE2p3Z0–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 / SME2p3ZA 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 / FP8Typed lane formats and integer-only fp_values::fp8_dot_add (E5M2/E4M3) primitives without host FPU dependence.
PAC (PAuth) & PSTATE.PACMQARMA3/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, UnprivilegedOrdered 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 & GXFExplicit 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, and archsem-lua—enable their default frontend features out of the box. archsem-python is an experimental handler-level frontend gated behind features = ["python"].

WebAssembly (archsem-wasm)

  • Parser & Validator: Backed by fWASM (re-exporting wasmparser types). WasmModule::parse / parse_with_features validates the Wasm binary up front.
  • Modes & Memory: WASM32 (32-bit linear memory) and WASM64 (Memory64, 64-bit linear memory). AddrSpace::Data models 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) returns LiftedWasmFunction containing the complete archsem_ir::Function CFG. Proposal opcodes outside the neutral core appear as WasmOpcode::Opaque with validated stack arity.

Ethereum Virtual Machine (archsem-evm)

  • Decoder & Fork Gating: Backed by evm-disassembler (EvmCode::parse / parse_hex). EvmFork (Frontier through Osaka) gates opcodes by hard fork—opcodes absent in the selected fork decode as INVALID. Truncated trailing PUSHn immediates zero-pad to full width, and JUMPDEST offsets are collected at instruction boundaries.
  • Static Jump-Target Resolution (EvmFunction): Performs bounded value-set analysis (AnalysisLimits) to resolve JUMP and JUMPI destinations within the code object, exposing FunctionStackGraph and EvmStackSsa views.
  • Address Spaces: Disjoint AddressSpaceAliasGroups separate big-endian EVM MEMORY_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)), and WORLD_STATE_SPACE (Vendor(5)).
  • 256-bit Semantics & Stack Templates: Stack ops (stack evm in 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 into LiftedCode.

.NET CIL / ECMA-335 (archsem-cil)

  • PE & Metadata Decoder: Backed by cildec (metadata tables, method headers, signatures, exception clauses) and fNET (IL instruction decoder).
  • Modes (CIL32 / CIL64): mode_for_image_flags resolves 32BITREQUIRED vs PE32+ headers.
  • Evaluation Stack & Method Slots: CilFunction::normalize computes stack heights and assigns synthetic registers for evaluation-stack slots (0x1000), method arguments (0x2000), and locals (0x3000), plus CIL_STACK_POINTER, CIL_EXCEPTION, CIL_RET, and CIL_FILTER.
  • Exception Handling (lift_method_cfg & attach_unwind_edges): Discovers try / catch / filter / finally / fault handler entry points via CfgLiftConfig::additional_entries and attaches prioritized ExceptionalEdges onto the lifted Function.
  • Managed Object Services: Object-model instructions (newobj, callvirt, ldfld, castclass, etc.) emit typed OpaqueIntrinsics and volatile. / ordered memory contracts (LoadContract / StoreContract).

Lua & LuaJIT (archsem-lua)

  • Chunk Decoder: Backed by fLUA, supporting LUA51, LUA52, LUA53, LUA54, LUAJIT21, and LUAJIT21_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 to LUA_FRAME, with LUA_LINK for continuations and dedicated system temporaries for numeric loops and scalar operations.
  • CFG Lifting & Optional Runtime (runtime feature): lift_function_cfg(&module, index, &limits) lifts a prototype's CFG (LiftedLuaFunction). Enabling features = ["runtime"] integrates archsem-ref with 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's program, pattern, subprogram, form, and write_hook items are not emitted by the importer.
  • Comments support // line and /* ... */ block syntax. Keywords are contextual.

Top-Level Items

ItemSyntaxPurpose
templatetemplate NAME<TypeParams>(ValueParams) [stack evm ...] { ... }Parameterized program body instantiated by program items
programprogram SYM [annots] [atomic] route "ROUTE" [compound(...)] = TEMPLATE<...>(...);Instantiates a template for a decoder route (program_for or atomic_program_for)
patternpattern NAME [@revision(n)] [@slots(n)] { ... }Non-parameterized, self-routed program (often entry-parameterized via entry)
subprogramsubprogram NAME [@slots(n)] { ... }Non-routed helper program (used by finish rep ... body ... latch ...)
fragmentfragment NAME [(params) -> (outs)] { ... }Reusable statement block expanded via expand (hygienic when parameterized; splice when parameterless)
formform NAME for SEMANTIC { ... }Declares one legal machine-code encoding/operand/decorator realization
registerregister NAME = physical|flag|system CID [arch N] [offset B] [count N];Declares an architectural register or contiguous register bank
faultfault NAME = "MNEMONIC" trigger TRIGGER class CLASS;Declares an architectural fault/trap identity
tabletable NAME : bits<W> = { v0, v1, ... };Declares a compile-time / lut byte table
opaque intrinsicopaque intrinsic NAME { ... }Declares a typed OpaqueIntrinsic descriptor
write_hookwrite_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>, template width parameters (bits<w>), numeric static for loop 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 next Slot in 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 emits StaticIf (is_vector, long_mode, has_broadcast, has_embedded_rounding, mask_zeroing, operand_is_memory(i), predicate_is(COND), etc.). static for I in 0 .. N lowers to Unroll; 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 & flags blocks): emit_flags invokes the manifest-driven flag engine (entry, logic, add, sub, adc, sbb). flags over(...) [when C] [covers status|nzcv] { ... } declares per-flag symbolic expressions (with zf, sf, pf, carry_add, carry_sub, borrow_sub, overflow_add, overflow_sub, aux_*, undefined, preserve, or recipe arms). Canonical flags blocks 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, and fence. Qualified memory accesses support unprivileged, volatile, ordered <ORDERING>, space data|code|io, and guest_atomicity(...).
  • Predicated writes (when): when COND { write reg ...; } lowers to WriteRegCond / 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 include finish fallthrough;, jump, branch, switch, call ... link ... timing ...;, stop halt|wait|unreachable;, trap ...;, fault NAME [when COND];, require C "reason";, and finish 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 require key 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:

  1. form_mismatch: Cross-checks every form contract against the inferred ProgramEffectSummary across synthetic InsnView realizations (operand read/write directions, memory access contracts, and implicit flags).
  2. fault_after_commit: Flags uncommitted architectural register, flag, or operand writes that precede a potentially faulting memory access or trap/fault check without an intervening commit; or transaction progressive;.
  3. unhygienic_fragment: Flags legacy parameterless splice fragments in favor of hygienic parameterized fragments.
  4. duplicate_register: Flags distinct register declarations 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 build with --write or --check, you must pass --out <path>. Omitting --out defaults to --stdout (and returns an error if --write or --check is 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-core verifier (including imported declarations)
  • Hover information showing verified slot and top-level micro-op counts
  • Inlay hints displaying allocated @slot numbers on let bindings
  • 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, canonical EnabledFeatures, endianness, and bounded, revisioned DecodeArchitectureState)
  • 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:

  1. An acyclic instruction-local event trace and typed EventGraph.
  2. One coherent terminal outcome (fallthrough, control transfer, or architectural fault/trap).
  3. 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)

  • FlagDemand is 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..=512 bits). Int(1) is the predicate type. Arithmetic wraps modulo 2^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 != 0 and representable quotient (not INT_MIN / -1)
    • ExtractElement, InsertElement, and IndexedRegisterBank accesses require in-bounds lanes/indices
  • 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, or WriteRegCond suppresses the event, its memory access, ordering edges, and associated faults (LoadCond yields 0; LoadTry yields (0, false)).
  • Transaction & Progress Matrix:
TransactionModelProgressModelContract
RestartableExactEntry state or latest explicit Commit is visible on fault
ProgressiveExactEvery preceding effect is visible in authored order
ProgressiveCanonicalPrefixEmitted prefix is guaranteed visible; later permitted effects may also have completed
PermittedMemorySubsetExactRegisters/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: InstructionExecution choices begin at begin_instruction (or explicit InstructionExecutionGroup Root/RepeatBody/RepeatLatch boundaries). Persistent scopes (ExecutionSession, MachineProfile, ExternallySupplied) require deterministic 128-bit ChoiceBindingNamespaces via ChoiceBindingEnvironment and MUST be predeclared before emitter mutation.
  • DCE Rule: Only an Unspecified choice at ProducedValue scope 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 finite IncompletenessRecords; unknown/unresolved functions cannot be marked Complete and 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 as Equivalent)

Architecture catalogs map (SemanticCoverage, SemanticImplementationDisposition) to exactly one reviewed CoverageLabel:

CoverageLabelRequired SemanticCoverageRequired Disposition
FaithfulExactModeled semantics
PartialConservativeOverapproximation, Underapproximation, or MixedPartialModeled semantics
OpaqueOpaqueDataflowStructured opaque semantics
AbsentUnsupportedNo 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:

  1. Canonical Semantic Wire (archsem_core::canonical): A deterministic, serde-independent binary encoding used for content-addressed semantic fingerprints (fragment and whole-function dual fingerprints).
  2. 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

TypeWire Format
u8, u16, u32, u64, u128, i64Fixed-width little-endian two's complement
usizeAdmitted only if it fits u64; encoded as little-endian u64 (lengths only)
bool0x00 (false) or 0x01 (true)
Byte strings & UTF-8 textu64 byte length `
Enum tagsNormative UTF-8 tag strings
Option<T>0x00 (absent) or `0x01
Wide bitvectorsu16 width `
Sequencesu64 item count `
MapsSorted 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):

ProjectionRetainedRedacted
Semantic-DefinitionWide 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-InstanceEverything 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 basesNone

[!NOTE] Schema major 1 (which embedded serde_json wire) is intentionally rejected by revision 2. Within a major version, existing tags, widths, and field orders never change; additive IR vocabulary increments the minor version (e.g., 2.1 added extract-element / insert-element; 2.2 added instruction-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") or ArtifactKind::DecodeTable ("decode_table")
    • payload: OwnedProgram or OwnedDecodeTable
  • Loaders: load_program_json, load_program_ron, load_decode_table_json, load_decode_table_ron.
  • Fail-Closed Admission:
    1. Checks ResourceLimits::input_bytes before parsing.
    2. Rejects wrong schema, incompatible major version, and newer unsupported minor versions (never assuming unknown fields are inert).
    3. Validates the decoded payload structurally (ExecutableProgram / OwnedTableDecoder) before returning or leaking any process-lifetime state.
  • Legacy Undef Rejection: Artifacts containing removed pre-v0.2 Undef encodings are rejected at admission rather than silently mapped to Choice.

Other versioned bounded artifacts in the workspace follow the same hostile-input admission pattern:

  • archsem-symex: ExecutionReportArtifact, ConcolicExecutionArtifact, ProofObligationArtifact, InstructionValidationArtifact, InstructionCounterexampleArtifact
  • archsem-conformance: ExternalOracleRequest / ExternalOracleResponse, OracleDisagreementArtifact
  • archsem-lang / archsemc: .asemc portable 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, and archsem_ir RTL Nodes, 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-symex expression nodes) are opaque behind typed accessors.

Extension-Point Taxonomy

Public extension points follow six explicit roles:

SuffixResponsibility
EmitterReceives the portable semantic vocabulary and constructs another IR (RtlEmitter, LlvmEmitter, ReferenceEmitter)
EnvironmentSupplies concrete external state and records effects (ConcreteEnvironment, ReferenceEnvironment)
PolicyChooses a bounded analysis action without supplying machine state (MemoryPartitionPolicy, MemoryPolicy, CallPolicy)
ProviderSupplies caller-owned facts, summaries, choices, or supplements (ChoiceProvider, CallSummaryProvider, OriginSupplementProvider)
SinkConsumes an exported stream or obligation (FunctionReplaySink, RegisterSsaReplaySink, ProofObligationSink)
AdapterTranslates 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) and archsem.external-oracle-response.
  • Cryptographic Request Binding: Every response carries request_binding (sha256 canonical 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) and unavailable (model_not_installed, license_not_accepted, toolchain_incompatible, timeout) remain distinct from observed mismatches (OracleDisagreementArtifact).
  • Maintained Differential: archsem-conformance/oracles/x86isa maintains a pinned ACL2 8.5 / x86isa differential fixture (48 89 d8 MOV 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:

StageFixed WorkloadWork UnitOutput Unit
decode_lift384 instances from a 6-instruction x86 corpusDecoded instructions + actionsRecorded actions
vm_interpret32 interpretations of a 64-lane VM programVerified expanded micro-opsRecorded actions
rtl_build1 fragment with 256 redundant outputsRTL nodes builtFragment events
optimize1 copy of that redundant fragmentSimplifier node visitsRetained RTL nodes
replay32 replays of the optimized fragmentInput RTL nodes replayedReplayed record events
bounded_symex8 executions of a depth-3, 15-block CFGSymbolic execution stepsCompleted 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:

  1. archsem-core
  2. archsem-record, archsem-arm64, archsem-x86
  3. archsem-ir, archsem-conformance
  4. archsem-simplify
  5. archsem-symex, archsem-ref (plus bytecode frontends archsem-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.