The Core Semantic Model (archsem-core)
archsem-core is the standalone foundation of Architectura. It has zero dependencies on any target IR (archsem-ir, LLVM, etc.) and zero dependencies on any instruction decoder (iced-x86, fARM64, etc.). Every architecture definition and consumer communicates exclusively through its neutral vocabulary.
IrEmitter: Required Core vs. Provided Extensions
Every semantic definition—whether a compiled .asem SemProgram or a hand-written Rust provider—is generic over IrEmitter. The trait splits into a required core and provided extension methods whose defaults expand faithfully onto the core:
┌─────────────────────────────────────────────────────────────────────────┐
│ IrEmitter │
├─────────────────────────────────────────────────────────────────────────┤
│ Required Core │
│ • type Value │
│ • begin_instruction() │
│ • temp(bits), imm(val, bits), reg(RegisterDesc), choice(ChoiceRequest) │
│ • binop(BinOp, a, b, bits), unop(UnOp, a, bits), compare(CmpOp, a, b) │
│ • zext(v, to_bits), sext(v, to_bits), trunc(v, to_bits) │
│ • load(addr, req), store(addr, val, req), write_reg(reg, val) │
│ • select(cond, if_true, if_false), fault(FaultKind) │
│ • opaque_intrinsic(OpaqueIntrinsic, args) / intrinsic(name, args, ...) │
├─────────────────────────────────────────────────────────────────────────┤
│ Provided Extensions (default-lowered onto core, override for precision) │
│ • imm_wide(&[u64], bits) — 1..=512-bit literals │
│ • load_cond / store_cond / load_try / probe_write │
│ • write_reg_with_policy / write_reg_cond_with_policy │
│ • atomic_rmw / atomic_cmpxchg / load_exclusive / store_exclusive │
│ • fence(FenceRequest) / clear_reservation(ReservationId) │
│ • fp_binop / fp_binop_ex / fp_fma_ex / fp_unary_ex / fp_compare_ex ... │
│ • extract_element / insert_element / lut / shuffle_bytes │
│ • transaction_model / progress_model / commit_checkpoint / trap_if ... │
│ • flag_demand() -> FlagDemand │
└─────────────────────────────────────────────────────────────────────────┘
- No control-flow methods:
IrEmitterintentionally lacksbranch,jump, orbasic_block. Every execution returns aControlEffect<E::Value>orSemanticControl<E::Value>. #[non_exhaustive]operation enums:BinOp,UnOp,CmpOp,FpOp,FpUnOp,FpCmp, andAtomicOpcan gain new variants without breaking existing emitters.- Lifecycle boundary (
begin_instruction): Establishes the boundary forInstructionExecutionchoices before the first semantic emission, independent of optional mnemonic or source-address metadata.
SemProgram and the Micro-Op VM
Most instruction semantics live as pure data in a SemProgram (SemProgramRef<'_>): a finite list of typed MicroOps operating over a flat Slot (u16) array:
SemProgram (const / OwnedProgram)
│
▼
verify_program[_for_insn]_with_limits() ◀── mandatory trust boundary
│
▼
run / run_checked / run_with_limits<E: IrEmitter>(program, &mut ctx, insn, entry)
│
▼
Result<SemanticControl<E::Value>, LiftError>
Key micro-op categories include:
- Emit-time expressions (
ImmExpr): Symbolic width and constant expressions resolved per decoded instruction (DstWidth,DstWidthX2,HalfDst,OperandWidth(i),ElemBits,LaneCount,InsnAddr,NextAddr,Lane,OuterLane(k), arithmetic). - Emit-time control (
StaticIf,Unroll,VLoop): Compile-time/decode-time specialization over static predicates (BuildPred:IsVector,LongMode,HasBroadcast,HasEmbeddedRounding,MaskZeroing,OperandIsMemory(i),DstWidthEq(n), etc.) and bounded unrolling. - Dataflow & effects:
Const,ReadOp,WriteOp,WriteMasked,ReadReg,WriteReg,WriteRegCond,BinOp,UnOp,Cmp,Zext,Sext,Trunc,Select,Snapshot,Load,LoadCond,Store,StoreCond,ProbeWrite,AtomicEvent,Fence,ClearReservation,TrapIf,TrapIfCode,Fault,Require,Choice,OpaqueIntrinsic,EmitFlags,EvalCond. - Compound instruction phases: Non-delay compound instructions (e.g., x86 near
CALL) can partition top-level micro-ops viaCompoundInstructionSpec(Operation,MemoryAccess,Completion), retaining member order and provenance within a single fragment.
Execution always runs the canonical verifier (vm_verify) before calling the emitter, checking definite slot assignment, widths in 1..=512, lane/index bounds, partial-operation preconditions (NonZeroDivisor, shift counts), choice compatibility, and transaction-region structure.
LiftCtx and DecodeContext
DecodeContext<S>
Every public decoder (Decoder trait) takes &self, input bytes, an address, and a DecodeContext<S>:
mode: CpuModeand manifest-selecteddecoder_mode: DecoderModeIdenabled_features: EnabledFeatures: canonical, sorted, duplicate-freeDecodeFeatureset admitted underResourceLimitsendianness: Endian: decode-dependent byte orderstate: S: DecodeArchitectureState: bounded, revisioned architecture-specific state (orNoDecodeState)
Decoders return Result<DecodeOutcome<Insn, S>, DecoderFailure>, where DecodeOutcome carries an explicit DecodeContextTransition<S> describing every per-field context change (such as mode switches). Checked entry points (decode_checked, decode_checked_with_limits) validate both input context and transition output before caller state changes.
LiftCtx<'a, E: IrEmitter>
Every semantic provider receives &mut LiftCtx<E>, which bundles:
emitter: &'a mut Earch: &'a ArchManifest— declarative register file, flag model (includingCarryPolarity), CPU modes, address spaces, segmentation model, and stack directionmode: CpuModeandprofile: ModeProfile(address/operand/stack widths,pc_read_bias,SegSemantics)insn_va: u64andnext_va: u64image: Option<&'a dyn ImageReader>andbinary_mode: BinaryModearch_state: &'a mut dyn ArchState— optional lift-time state (plusArchState::post_instructionfor hardware-loop branches)
ControlEffect and SemanticControl
Control flow is never emitted into the IR; it is returned as ControlEffect<V> / SemanticControl<V>:
FallThrough— sequential continuation tonext_vaJump { target }— direct or indirect jump (withModeSwitch)Branch { cond, taken, fallthrough, delay_slots, annul }— 1-bit predicate, takenTarget, fallthrough VA, and delay-slot/annul policy (AnnulRule)Call { target, return_to }— call transfer with continuation VA and explicitControlLinktiming (before_transfer,before_delay_slots,after_delay_slots)Return { target: Option<V> }— register-based (ARM64X30) or stack-popped (x86RET)Trap { kind: FaultKind }— terminal architectural fault/trap (with optionalTrapPayload)Switch { value, cases, default }— direct multi-way branchRep { cond, body, latch, entry }andLoopLatch { cond }— driver-instantiated runtime repeat loops (such as x86REP/REPE/REPNE)
SemanticControl is the unified, checked terminal record carrying dense ControlSuccessorIds, ControlSuccessorRoles, ControlGuards, ControlSchedule, DecodeTransitionIntent, and SemanticFidelity.
OpaqueIntrinsic: Structured Contracts
When portable micro-ops cannot expand an operation, OpaqueIntrinsic replaces raw string-only intrinsics with a complete, validated contract:
identity: OpaqueIntrinsicIdentity— target-independentname+revision(u32)reason: OpaqueReasonCode— why it is opaque (ArchitectureIntrinsic,ExternalEnvironment,ImplementationDefined,PatternOpaque, etc.)inputs: Vec<OpaqueInput>andoutputs: Vec<OpaqueOutput>— typed roles (Value,Address,Predicate,MemoryData,RoundingControl,Custom(u16)) and exact widths (OpaqueBitWidth). Multi-output descriptors denote one single execution, never one call per output.registers: Vec<OpaqueRegisterEffect>— exactSlice,Flag,Storage, or explicit aggregate (AllRegisters,AllFlags,AllArchitecturalState) effects (Read,Write,Preserved,Undefined,ConservativeClobber)memory: OpaqueMemoryBehavior,faults: OpaqueFaultBehavior,control: OpaqueControlBehavior,choices: Vec<OpaqueChoice>volatile: boolandfidelity: SemanticFidelity
Optional algorithm families (OpaqueFamily::Crypto and OpaqueFamily::Math) remain compact opaque intrinsics by default unless an emitter opts into expansion via IrEmitter::opaque_expansion().
Choice & ChoiceBindingEnvironment
Architectural nondeterminism is modeled by ChoiceRequest / ChoiceSpec rather than undef or poison:
| Dimension | Variants |
|---|---|
ChoiceKind | Unspecified, ConstrainedUnpredictable, ImplementationDefined, Environment, Entropy, Uninitialized |
ChoiceScope | FreshPerObservation, ProducedValue, InstructionExecution, ExecutionSession, MachineProfile, ExternallySupplied |
ChoiceDomain | Any, Masked { known_zero, known_one }, UnsignedRange { min, max }, Finite(alternatives) |
Scopes from InstructionExecution upward require a correlation ChoiceKey. For persistent scopes (ExecutionSession, MachineProfile, ExternallySupplied), ChoiceBindingEnvironment provides the backend-neutral bridge:
- Callers assign deterministic 128-bit
ChoiceBindingNamespaces(ExecutionSession,MachineProfile,ExternallySupplied). (scope, namespace, key)maps to a stableChoiceBindingIdentity, rejecting any incompatible reuse (mismatched width, kind, or domain).- Checked entry points (
predeclare_persistent_choices) validate and register the complete persistent-choice plan before beginning an instruction or mutating target IR. - For multi-fragment instructions (such as
REPloops),InstructionExecutionGroup(Root,RepeatBody,RepeatLatch) andpredeclare_instruction_execution_choicescorrelateInstructionExecutionchoices across fragments.
Register Identity (RegisterId, RegisterDesc, IndexedRegisterBank)
Registers are identified structurally rather than by backend-specific integers:
RegisterId:(cid: u32, arch: u8, offset: u16, role: RegisterRole)whereroleisPhysical,Flag, orSystem.- On x86,
AL/AX/EAX/RAXsharecid = 0, offset = 0, whileAHhascid = 0, offset = 8. - On AArch64,
W0andX0sharecid = 0, offset = 0, andV0is the low 128-bit slice ofZ0.
- On x86,
RegisterDesc:RegisterIdpaired with exact access widthbits: u16.RegisterWritePolicy:Preserve(write slice only, keep upper bits) vs.ZeroExtendParent(zero-extend into parent, e.g. x86 32-bit GPR writes to 64-bit parents, AArch64Wn→Xn, VEX/EVEX vector writes).IndexedRegisterBank: Runtime-indexed register banks (such as x87ST(i)) preserve(base, count, index_bits, element_bits)and are bounds-checked (index < count) before emitter mutation.
Guest Memory Contracts & Fault / Transaction Models
Every memory access carries a MemoryAccessRequest:
- Address space & granularity:
AddrSpace(Data,Code,Io,Vendor(u16)),AddressSpaceResolution(withAddressSpaceAliasGroup),address_width_bits,data_width_bits,addressable_unit_bits(AddressableUnitWidth), andMemoryEndian(Little,Big,Unknown). - Access & strictness:
MemoryVolatility,MemoryOrdering(includingAcquirePerLocationfor Arm RCpc and*_LimitedRegionfor FEAT_LOR),Atomicity(NonAtomic,Atomic,GuestDefined),ReservationAction,MemoryAlignment,MemoryPrivilegePolicy,GuardPolicy,MayFaultPolicy, andTransferMask. - Compound events:
MemoryEventContractpairsMemoryEventDescriptor(Read,Write,Rmw,CompareExchange,LoadExclusive,StoreExclusive,Fence,CacheMaintenance,OpaqueMemory) with runtimeMemoryEventBindings(predicate, dynamic mask, passthrough). - Write probes:
IrEmitter::probe_writechecks store-permission faults overdata_bitswithout writing data or changing memory.
Fault & Transaction Matrix
Each executed SemProgramRef is a transaction-metadata region governed by (TransactionModel, ProgressModel):
TransactionModel | ProgressModel | Semantics on Fault |
|---|---|---|
Restartable (default) | Exact (default) | Entry state or latest explicit Commit checkpoint is visible |
Progressive | Exact | Every preceding effect is visible in exact authored order |
Progressive | CanonicalPrefix | Emitted prefix is guaranteed visible; later permitted effects may also have completed |
PermittedMemorySubset | Exact | Registers/non-memory state roll back to checkpoint; an implementation-selected subset of other memory mutations in the checkpoint segment may be visible (excluding the faulting mutation) |
Explicit Commit checkpoints close pending effect sites since region entry or the previous commit (Commit describes exception visibility, never inter-thread memory ordering).