Neutral RTL & Function CFG (archsem-ir)
archsem-ir sits between architecture lifting and downstream consumers (simplifiers, symbolic engines, decompilers, or LLVM/native code generators). It captures IrEmitter streams as validated, backend-neutral SSA RTL (Fragment) and whole-function CFGs (Function).
decode + arch lift ─▶ RtlEmitter ─▶ Fragment (instruction-local RTL + EventGraph + OriginGraph)
│
▼ lift_reachable_stateless / lift_reachable_stateful
Function (CFG of BasicBlocks + ExceptionalEdges)
│
┌────────────────────────────┼────────────────────────────┐
▼ ▼ ▼
RegisterSsa / StackMemorySsa EffectSummary / replay_cfg /
ConservativeMemorySsa CfgEffectSummary replay_register_ssa
RtlEmitter and Fragment
RtlEmitter implements IrEmitter<Value = ValueId> and produces a Fragment via finish(SemanticControl<ValueId>) (or finish_legacy(ControlEffect<ValueId>)). Unlike an audit-only trace, RtlEmitter:
- Records every register read at its exact position and access width.
- Keeps memory, fault, fence, atomic, reservation, and opaque effects strictly ordered.
- Retains full
MemoryAccessRequest,MemoryEventContract,OpaqueIntrinsic, andChoiceSpecdescriptors. - Materializes terminal control as a distinct final event (
EventId::TERMINAL) insideFragment::control.
Fragment::validate() independently checks positive non-zero widths (1..=512), canonical constants, operand/result width consistency, conversion directions, 1-bit guards, valid memory/opaque contracts, SSA dominance/use-before-definition, and coherent terminal control.
Fragment::optimize
Fragment::optimize(OptimizeConfig) runs a strict instruction-local pass performing:
- Width-aware constant folding (
1..=512bits, sharingarchsem_core::bitvecexact evaluation, never folding partial-operation UB into constants) - Copy/identity propagation and commutative canonicalization
- Conservative GVN (never commoning
Load,ReadReg,Fp*,Opaque*, or distinctChoiceidentities; pure expressions reusing one stable produced choice are eligible) - False-predicate memory simplification (converting a statically false
LoadCondtoConst(0)and dropping a statically falseStoreCond/TrapIf/WriteRegCond) - Dead pure-node elimination while retaining all observable effects and stable
EventIds
EventGraph, Backward Slicing, and Effect Summaries
Instruction-Local EventGraph
Fragment::event_graph() projects the Node sequence into a validated DAG over stable EventIds plus EventId::TERMINAL. Edges explicitly distinguish:
Value(ValueId)— dataflow dependenceAddress(ValueId)— effective-address dependenceControlPredicate(ValueId)— branch/guard predicate dependenceIndirectTarget(ValueId)— computed transfer targetRegisterIndex(ValueId)— dynamic indexed-bank selectorRegisterSlice(RegisterId)/Flag(RegisterId)— architectural register/flag dependenciesMemoryVersion— instruction-local memory orderingEffectOrder/FaultOrder— checkpoint, barrier, and fault precedenceReservationState(ReservationId)— local exclusive monitor state
Policy-Free Backward Slicing
Fragment::backward_slice(&[SliceRoot], SliceEdgeKinds) computes a deterministic BackwardSlice (events, values, and dependency edges) from caller-chosen SliceRoot::Event(EventId) or SliceRoot::Value(ValueId) roots and opt-in SliceEdgeKinds (VALUE, ADDRESS, CONTROL_PREDICATE, INDIRECT_TARGET, REGISTER_SLICE, FLAG, MEMORY_VERSION, EFFECT_ORDER, FAULT_ORDER, REGISTER_INDEX, RESERVATION_STATE). It makes no taint, alias, or recovery assumptions on the caller's behalf.
EffectSummary and CfgEffectSummary
EffectSummary::from_fragmentscomposes straight-line fragments (retaining each fragment's optionalInstructionExecutionGroup) and summarizes register reads/writes/preserved slices (using theArchManifestif provided, or conservative raw descriptors otherwise), memory effects, faults, requirements, and uncertainty boundaries.Function::cfg_effect_summarysummarizes whole functions per block while retaining the original typed terminator, exceptional edges, multi-predecessor joins (CfgSummaryJoin), and cyclic strongly connected components (CfgSummaryLoop) without flattening mutually exclusive paths.
OriginGraph Provenance & SemanticFidelity
OriginGraph
Every value, effect, and terminal in a Fragment resolves to a stable OriginId inside a bounded, interned OriginGraph DAG:
- Instruction origin (
InstructionOrigin: address, exact bytes, decode context fingerprint, architecture identity, mnemonic, optional consumer-supplied execution/trace/occurrence/epoch supplement viaOriginSupplementProvider) - Semantic sites (
SemanticSite: program identity, revision, nestedMicroOpPath, operand role, lane) - Ordered bundle membership (
OrderedBundleMemberfor delay slots and compound instructions) - Derived values, local transforms, aliases/merges, and explicit truncation markers (
OriginTruncationReason)
Optimization passes (Fragment::optimize, archsem-simplify, CFG passes) return explicit transformation mappings (FragmentTransformMappings, FunctionTransformMappings) instead of silently dropping provenance.
SemanticFidelity & FidelityAnalysis
Each Fragment carries a declared SemanticFidelity (coverage, determinism, choice kinds, observable facets, validation evidence, and reason codes). Calling fragment.analyze_fidelity() derives a fresh FidelityAnalysis over the current typed graph—tainting values and observable events only through their actual dependencies and matching observable facets—so rewrites never leave stale side tables.
Function: Reachable CFG Discovery
lift_reachable_stateless and lift_reachable_stateful discover reachable basic blocks starting from an entry address using a Decoder and ImageReader:
- State-keyed discovery:
lift_reachable_statefulkeys blocks by(address, CpuMode, DiscoveryState::Key).ContextualDiscoveryState<S, K>lets consumers compose a caller-owned key (such as a code epoch or virtual-PC context) without exposing dispatcher or unpacking heuristics toarchsem. - Bounds & Incompleteness (
Completion):CfgLiftConfigboundsaddress_range,extra_ranges,additional_entries,max_instruction_bytes,max_instructions,max_blocks,max_total_bytes,max_switch_cases, anddecode_limits. If discovery hits a decode failure, unsupported instruction, or resource limit, it attaches a boundedIncompletenessRecordand returns aCfgLiftFailurecontaining the partialFunction(Completion::Incomplete). Destructive transforms and executable replay reject incomplete functions until explicitly valid and marked complete (mark_complete). - Ordered Bundles & Repeat Loops: Non-annulled straight-line delay slots and compound instructions remain grouped via
OrderedBundle/TransactionRegionId; taken-only annulled slots clone blocks as needed;REPinstructions lower intoRoot,RepeatBody, andRepeatLatchInstructionExecutionGroupfragments. - Function Normalization (
Function::optimize_function&canonicalize_cfg): Supports fragment simplification, expression forwarding across blocks, register SCCP (RegisterSccpStats), architecture-aware bit-granular register DCE (RegisterDceConfig,ExitLivenessPolicy,ExceptionalStateRoots), constant branch/switch folding, unreachable-block pruning, and optional empty-trampoline threading / linear block coalescing (Function::canonicalize_cfg).
Register SSA & Memory SSA
archsem-ir provides three validated CFG-level SSA products, each independently reconstructible and verifiable via ssa_validation:
RegisterSsa::build(&function, &arch)Promotes architectural parent registers (ParentReg) into SSA values with block-entryRegisterPhis across diamonds and loops. Understands x86 nested GPR slices (AL/AH/AX/EAX/RAX), AArch64Wn→Xnzero-extension, and vector parent clearing/merging policies.StackMemorySsa::build(&function, &arch)&optimize_stack_memoryIdentifies exact, non-overlapping affineSP ± constslots whenSPis stable and no call, unwind, atomic, conditional, or opaque memory boundary intervenes. UnderStackMemoryConfig::strict(), no loads or stores are eliminated; underassume_private_stack_accesses_non_faulting(), dead private stack stores can be removed.ConservativeMemorySsa::build(&function)/build_with_partition&MemoryDependencyGraphAssigns whole-memory tokens (MemoryToken) across arbitrary-address loads, stores, atomics, fences, opaque intrinsics, and call clobbers. Callers may supply a labeledMemoryPartitionPolicyto separate disjoint memory classes.MemoryDependencyGraph::buildprojects constant-address unit ranges (MemoryDependencyRange) and supports function-level memory backward slicing (MemoryDependencyGraph::backward_slice) without claiming general alias recovery.
Retained Artifacts & External Observations
- Immutable Lineage (
RetainedFragmentArtifact,RetainedFunctionArtifact): Keeps the raw lifted artifact immutable while running normalization as a transactional clone-transform-validate-commit query (NormalizationGeneration,NormalizationRecord). - External Observation Binding (
ObservationSet,TraceSequence): Binds dynamic execution evidence (PC, observed bytes, occurrence IDs, code epochs, register values with known-bit masks, memory transfers, unified control outcomes, and pre-terminal faults) to fragment values/events/origins via typedObservationBindingRoles. Caller hypotheses live separately inObservationAssumptionSet(AssumptionHint).
Replay (replay, replay_cfg, replay_register_ssa)
Fragment::replay(&mut emitter): Replays an instruction fragment into anyIrEmitter, predeclaring persistent choices and installing per-event and terminalSemanticSites.Function::replay_cfg(&mut sink): Replays raw blocks, transaction regions, grouped repeat roles, and prioritizedExceptionalEdges withExceptionalMemoryStatevisibility descriptors into aFunctionReplaySink.Function::replay_register_ssa(&mut sink)/replay_register_ssa_with_calls: Lowers sparse live-in block parameters (ParentReg), edge-parallelEdgeAssignmentbatches, partial-parent reconstruction, and injectedCallSummarys into an executableRegisterSsaReplaySink(such asarchsem-llvm). Before mutating backend state, replay checksReplayCapabilitiesagainst the function'sReplayRequirements.