From 05cf8e292f2a684a0807da0b36e51e30de5a160f Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:05:26 +0900 Subject: [PATCH] refactor(native): support state-aware outlined kernel calls Add an internal image-local call ABI with a hidden state pointer, signed status propagation, and preservation of pinned host state. Treat these callees as opaque state effects in SIR memory passes and invalidate cached load origins across calls. Ordinary DPI imports keep their existing ABI. Validation: SIR, optimizer and x86 unit suites; native-call regressions cover zero, positive and negative status values, pinned R15/GS state, tick-loop state and live vector values. Memory regressions prevent forwarding or reloading overwritten state across a kernel call. Owning-crate clippy and formatting pass. Generated-kernel callers now require explicit complete callee arena bounds; emission without them is rejected. The direct emit_with_callees entry and X86BackendOptions::with_native_callees reserve the caller above every callee's full required_state_size, including nested reservations. Existing explicit arena placements remain supported by the prepared pipeline. A regression reproduced the review finding with two generated functions emitted at the same 4096-byte semantic state size: the caller's last seven spilled values became zero. The fixed test supplies the actual emitted callee extent. Three-level generated call regressions force spills at every level, cover R15/GS and tick-loop entry, propagate zero, positive and wide negative status values, and reject missing or overflowing arena bounds. All 623 x86 unit tests and owning-crate clippy pass. Change-Id: Ia444d9f7754e3f118e5a3945b32360c2acd7298d --- .../src/backend/native/emit.rs | 97 +++++- .../src/backend/native/emit/extern_call.rs | 26 +- .../src/backend/native/emit/pipeline.rs | 8 + .../backend/native/emit/tests/extern_calls.rs | 305 ++++++++++++++++++ .../src/backend/native/isel/slice.rs | 5 + .../src/backend/native/isel/tests/slice.rs | 8 +- .../src/backend/native/regalloc/assignment.rs | 10 +- crates/celox-backend-x86/src/lib.rs | 16 +- .../optimizer/passes/analysis/state_ssa.rs | 89 +++++ .../pass_eliminate_working_round_trip.rs | 13 + .../pass_global_store_load_forwarding.rs | 13 + .../memory/pass_store_load_forwarding.rs | 63 ++++ crates/celox-sir/src/extern_abi.rs | 15 + crates/celox-sir/src/verify.rs | 10 + 14 files changed, 661 insertions(+), 17 deletions(-) diff --git a/crates/celox-backend-x86/src/backend/native/emit.rs b/crates/celox-backend-x86/src/backend/native/emit.rs index 39a76440b4e..329e4c68f77 100644 --- a/crates/celox-backend-x86/src/backend/native/emit.rs +++ b/crates/celox-backend-x86/src/backend/native/emit.rs @@ -815,6 +815,32 @@ pub fn emit( ) } +/// Emit a caller with disjoint storage above every generated callee's arena. +/// Pass `required_state_size` from each reachable callee's `EmitResult`; +/// each callee must itself have been emitted with its own callees' extents. +/// `state_size` describes the common semantic state, not an arena reservation. +pub fn emit_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + callee_ends: &[usize], +) -> Result { + verify_emission_inputs(func, assignment, spill_frame_size, false)?; + let plan = SsaDestructionPlan::build(func, assignment)?; + plan.verify(func, assignment, spill_frame_size)?; + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + &plan, + false, + false, + callee_ends, + ) +} + /// Direct emitter tests do not carry a complete `MemoryLayout`. Place their /// native arena beyond every statically named SimState byte plus a guard so /// test-owned sentinel bytes cannot alias prologue/scratch storage. @@ -845,11 +871,12 @@ pub(crate) fn emit_with_plan( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, false)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -857,6 +884,7 @@ pub(crate) fn emit_with_plan( plan, false, false, + callee_ends, ) } @@ -865,12 +893,13 @@ fn emit_with_plan_tick_loop( assignment: &AssignmentMap, spill_frame_size: u32, state_size: usize, + callee_ends: &[usize], plan: &SsaDestructionPlan, check_runtime_events: bool, ) -> Result { verify_emission_inputs(func, assignment, spill_frame_size, true)?; plan.verify(func, assignment, spill_frame_size)?; - emit_planned( + emit_planned_with_callees( func, assignment, spill_frame_size, @@ -878,6 +907,7 @@ fn emit_with_plan_tick_loop( plan, true, check_runtime_events, + callee_ends, ) } @@ -1043,6 +1073,45 @@ fn emit_planned( tick_loop: bool, check_runtime_events: bool, ) -> Result { + emit_planned_with_callees( + func, + assignment, + spill_frame_size, + state_size, + plan, + tick_loop, + check_runtime_events, + &[], + ) +} + +/// Callee extents include their own recursively reserved callees. The state +/// pointer stays unchanged; only the caller's private arena is placed above +/// those complete extents. Merely using the same semantic state size for both +/// functions is not sufficient to isolate live spills and pinned saves. +fn emit_planned_with_callees( + func: &MFunction, + assignment: &AssignmentMap, + spill_frame_size: u32, + state_size: usize, + plan: &SsaDestructionPlan, + tick_loop: bool, + check_runtime_events: bool, + callee_ends: &[usize], +) -> Result { + let has_kernels = func.blocks.iter().flat_map(|b| &b.insts).any(|inst| + matches!(inst, MInst::CallExtern { func, .. } if celox_sir::extern_abi::native_kernel_index(*func).is_some())); + if has_kernels && (callee_ends.is_empty() || callee_ends.contains(&0)) { + return Err(EmitInputError::new( + "EMIT.NATIVE_CALLEE_ARENA", + None, + None, + None, + "generated kernel calls require the callees' complete required_state_size extents", + ) + .into()); + } + let state_size = callee_ends.iter().copied().fold(state_size, usize::max); let mut uses_bmi2 = false; let mut uses_avx = false; let mut uses_popcnt = false; @@ -1297,6 +1366,30 @@ fn emit_planned( asm.jmp(epilogue_label)?; } } + MInst::CallExtern { func, arg_count } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + extern_call::emit_call_extern(&mut asm, *func, *arg_count)?; + // The call restored our state base and pinned registers. + // RAX still holds the complete signed callee status. + asm.test(rax, rax)?; + if tick_loop { + let mut success = asm.create_label(); + asm.jz(success)?; + // Match ReturnError's completed-tick accounting while + // retaining RAX for the common epilogue. + asm.movq(r10, xmm15)?; + asm.dec(r10)?; + asm.movq(xmm15, r10)?; + asm.jmp(epilogue_label)?; + asm.set_label(&mut success)?; + // A following MIR block may start here; code_asm + // cannot bind two labels to the same instruction. + asm.nop()?; + } else { + asm.jnz(epilogue_label)?; + } + } MInst::ReturnError { code } => { if tick_loop { asm.movq(rax, xmm15)?; diff --git a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs index 3c40c1e1030..35867c2a8a5 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs @@ -50,8 +50,10 @@ pub(super) fn set_call_area( } /// The XMM registers a call must save: pinned ones the callee may change. -fn saved_xmms(context: &EmissionContext) -> impl Iterator { - let saved = context.pinned_xmms & !C_PRESERVED_XMMS; +fn saved_xmms(context: &EmissionContext, native_kernel: bool) -> impl Iterator { + // Generated x86 functions use SysV on every host, including Windows. + let preserved = if native_kernel { 0 } else { C_PRESERVED_XMMS }; + let saved = context.pinned_xmms & !preserved; (0..16).filter(move |index| saved & (1 << index) != 0) } @@ -98,11 +100,12 @@ pub(super) fn emit_call_extern( let context = asm.context; let area = call_area(&context); let strategy = state_base_strategy(&context); + let kernel = celox_sir::extern_abi::native_kernel_index(func); // RBX is callee-saved in every C ABI and free here: it holds the state // pointer while the segment base belongs to C code. emit_state_base(asm, rbx)?; - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), xmm_register(index), @@ -119,14 +122,15 @@ pub(super) fn emit_call_extern( StateBaseStrategy::R15 => {} } - let (registers, shadow): (&[AsmRegister64], i32) = if cfg!(target_os = "windows") { - (&[rcx, rdx, r8, r9], 32) - } else { - (&[rdi, rsi, rdx, rcx, r8, r9], 0) - }; + let (registers, shadow): (&[AsmRegister64], i32) = + if cfg!(target_os = "windows") && kernel.is_none() { + (&[rcx, rdx, r8, r9], 32) + } else { + (&[rdi, rsi, rdx, rcx, r8, r9], 0) + }; // The heap helper takes the state pointer before the staged arguments. let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; - let leading = usize::from(heap); + let leading = usize::from(heap || kernel.is_some()); let arg_count = usize::from(arg_count) + leading; let stack_args = arg_count.saturating_sub(registers.len()) as i32; // Generated code is entered with RSP = 8 (mod 16) and never moves it. @@ -158,7 +162,7 @@ pub(super) fn emit_call_extern( } else if heap { -16 } else { - i32::try_from(u64::from(func) * 8).expect("extern function index") + i32::try_from(u64::from(kernel.unwrap_or(func)) * 8).expect("extern function index") }; asm.mov(rax, qword_ptr(rax + offset))?; asm.call(rax)?; @@ -170,7 +174,7 @@ pub(super) fn emit_call_extern( StateBaseStrategy::Gs => asm.wrgsbase(rbx)?, StateBaseStrategy::R15 => {} } - for index in saved_xmms(&context) { + for index in saved_xmms(&context, kernel.is_some()) { asm.movq( xmm_register(index), qword_ptr(rbx + (area + CALL_AREA_XMM_SAVE + 8 * index as i32)), diff --git a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs index 73fc6a8af8c..92855fcad1b 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs @@ -336,12 +336,19 @@ fn emit_prepared_eu_inner( let state_size = options .arena_base .map_or(semantic_size, |base| base.max(semantic_size)); + let native_callee_end = [options.arena_base.unwrap_or(0)]; + let callee_ends = if options.arena_base.is_some() { + &native_callee_end[..] + } else { + &[] + }; let result = if label == "eval_comb_apply_ff" && options.native_tick_loop { emit_with_plan_tick_loop( &mfunc, &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, check_runtime_events, )? @@ -351,6 +358,7 @@ fn emit_prepared_eu_inner( &ra.assignment, ra.spill_frame_size, state_size, + callee_ends, &ssa_destruction, )? }; diff --git a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs index 94d09772410..93aa15c764e 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/tests/extern_calls.rs @@ -172,3 +172,308 @@ fn extern_calls_preserve_live_values_with_a_segment_state_base() { run(StateBaseStrategy::Gs, false); run(StateBaseStrategy::Gs, true); } + +/// The implicit state argument and signed status must survive ABI register +/// clobbers, spills across the call, and both state-base strategies. +extern "sysv64" fn kernel_with_status(state: *mut u8) -> i64 { + let _ = trashing_weighted_sum(1, 2, 3, 4, 5, 6, 7, 8); + // SAFETY: the generated caller passes this test's complete state buffer. + unsafe { *state.add(RESULT + 16).cast::() } +} + +#[test] +fn native_kernel_calls_preserve_live_values_and_propagate_signed_status() { + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + let mut function = live_across_calls(strategy); + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG; + *arg_count = 0; + } + } + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let emitted = emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + RESULT + 24, + &plan, + tick_loop, + false, + &[RESULT + 24], // This Rust ABI surrogate uses no private native arena. + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let table = [kernel_with_status as *const () as usize]; + let event_sequence = 0u64; + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut memory = vec![0u64; emitted.required_state_size as usize / 8 + 1]; + memory[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + memory[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&event_sequence as *const u64) as u64; + memory[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + memory[(RESULT + 16) / 8] = status as u64; + let values = (1..=LIVE as u64).collect::>(); + memory[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&values); + let calls = CALLS.get(); + assert_eq!(unsafe { (jit.fn_ptr)(memory.as_mut_ptr().cast()) }, status); + assert_eq!(CALLS.get() - calls, if status == 0 { 2 } else { 1 }); + if status == 0 { + assert_eq!(&memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &values); + } else { + assert!( + memory[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE] + .iter() + .all(|&v| v == 0) + ); + } + } + } + } +} + +fn generated_kernel( + strategy: StateBaseStrategy, + input_base: usize, + callee: Option, +) -> MFunction { + let mut function = live_across_calls(strategy); + for inst in &mut function.blocks[0].insts { + if let MInst::Load { offset, .. } = inst { + *offset += input_base as i32 - BASE as i32; + } + } + let instructions = &mut function.blocks[0].insts; + instructions.retain(|inst| !matches!(inst, MInst::ExternArg { .. })); + match callee { + Some(callee) => { + for inst in instructions { + if let MInst::CallExtern { func, arg_count } = inst { + *func = celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG | callee; + *arg_count = 0; + } + } + } + None => { + instructions.retain(|inst| !matches!(inst, MInst::CallExtern { .. })); + for inst in instructions.iter_mut() { + if let MInst::ExternResult { dst } = inst { + *inst = MInst::LoadImm { + dst: *dst, + value: 0, + }; + } + } + // Prevent memory-backed reload recipes: each loaded value must + // survive an overwrite of its source before it is published. + let position = instructions + .iter() + .position(|inst| matches!(inst, MInst::LoadImm { .. })) + .unwrap(); + let MInst::LoadImm { dst: zero, .. } = instructions[position] else { + unreachable!() + }; + instructions.splice( + position + 1..position + 1, + (0..LIVE).map(|index| MInst::Store { + base: BaseReg::SimState, + offset: (input_base + index * 8) as i32, + src: zero, + size: OpSize::S64, + }), + ); + } + } + function +} + +#[test] +fn generated_callee_spills_do_not_overwrite_live_caller_values() { + const STATE_SIZE: usize = 4096; + let mut child = generated_kernel(StateBaseStrategy::R15, 1024, None); + let allocation = regalloc::run_regalloc(&mut child).unwrap(); + assert!(allocation.spill_frame_size > 0, "callee must really spill"); + let plan = SsaDestructionPlan::build(&child, &allocation.assignment).unwrap(); + let child_code = emit_planned( + &child, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &plan, + false, + false, + ) + .unwrap(); + let child_jit = JitCode::new(&child_code.code).unwrap(); + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "caller must retain real spilled values" + ); + assert!( + matches!(emit(&caller, &allocation.assignment, allocation.spill_frame_size), + Err(EmitError::Input(ref error)) if error.rule == "EMIT.NATIVE_CALLEE_ARENA") + ); + let caller_code = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + STATE_SIZE, + &[child_code.required_state_size as usize], + ) + .unwrap(); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [child_jit.fn_ptr as usize]; + let mut state = vec![ + 0u64; + caller_code + .required_state_size + .max(child_code.required_state_size) as usize + / 8 + + 1 + ]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!(unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, 0); + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); +} + +fn compile_generated( + mut function: MFunction, + state_size: usize, + callees: &[usize], + tick_loop: bool, +) -> EmitResult { + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + assert!( + allocation.spill_frame_size > 0, + "every generated level must really spill" + ); + let plan = SsaDestructionPlan::build(&function, &allocation.assignment).unwrap(); + let options = crate::X86BackendOptions::default().with_native_callees(callees.iter().copied()); + let bounds = options.arena_base.into_iter().collect::>(); + emit_planned_with_callees( + &function, + &allocation.assignment, + allocation.spill_frame_size, + state_size, + &plan, + tick_loop, + false, + &bounds, + ) + .unwrap() +} + +#[test] +fn nested_generated_kernels_have_disjoint_arenas_and_propagate_status() { + const STATE_SIZE: usize = 4096; + const COMPLETED: usize = 2048; + let mut strategies = vec![StateBaseStrategy::R15]; + if X86Features::detect().state_base() == StateBaseStrategy::Gs { + strategies.push(StateBaseStrategy::Gs); + } + for strategy in strategies { + for tick_loop in [false, true] { + for status in [0i64, 7, -0x1234_5678_9abc] { + let mut leaf = generated_kernel(strategy, 1024, None); + if status != 0 { + *leaf.blocks[0].insts.last_mut().unwrap() = MInst::ReturnError { code: status }; + } + let leaf_code = compile_generated(leaf, STATE_SIZE, &[], false); + let leaf_jit = JitCode::new(&leaf_code.code).unwrap(); + let middle = generated_kernel(strategy, 512, Some(0)); + let middle_code = compile_generated( + middle, + STATE_SIZE, + &[leaf_code.required_state_size as usize], + false, + ); + let middle_jit = JitCode::new(&middle_code.code).unwrap(); + let mut caller = generated_kernel(strategy, BASE, Some(1)); + let marker = caller.vregs.alloc(); + caller.spill_descs.push(SpillDesc::remat(0x51)); + let instructions = &mut caller.blocks[0].insts; + let end = instructions.len() - 1; + instructions.splice( + end..end, + [ + MInst::LoadImm { + dst: marker, + value: 0x51, + }, + MInst::Store { + base: BaseReg::SimState, + offset: COMPLETED as i32, + src: marker, + size: OpSize::S64, + }, + ], + ); + let caller_code = compile_generated( + caller, + STATE_SIZE, + &[middle_code.required_state_size as usize], + tick_loop, + ); + assert!(middle_code.required_state_size > leaf_code.required_state_size); + assert!(caller_code.required_state_size > middle_code.required_state_size); + let caller_jit = JitCode::new(&caller_code.code).unwrap(); + let table = [leaf_jit.fn_ptr as usize, middle_jit.fn_ptr as usize]; + let mut state = vec![0u64; caller_code.required_state_size as usize / 8 + 1]; + state[celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET / 8] = + table.as_ptr() as u64; + let sequence = 0u64; + state[STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET / 8] = + (&sequence as *const u64) as u64; + state[STATE_HEADER_NATIVE_LOOP_REMAINING_OFFSET / 8] = 1; + let original = (1..=LIVE as u64).collect::>(); + state[BASE / 8..BASE / 8 + LIVE].copy_from_slice(&original); + for i in 0..LIVE { + state[512 / 8 + i] = 1000 + i as u64; + state[1024 / 8 + i] = 0xdead_0000 + i as u64; + } + assert_eq!( + unsafe { (caller_jit.fn_ptr)(state.as_mut_ptr().cast()) }, + status, + "{strategy:?}, tick={tick_loop}" + ); + assert_eq!(state[COMPLETED / 8], if status == 0 { 0x51 } else { 0 }); + if status == 0 { + assert_eq!(&state[BASE / 8 + LIVE..BASE / 8 + 2 * LIVE], &original); + } + } + } + } +} + +#[test] +fn generated_callee_arena_overflow_is_rejected() { + let mut caller = generated_kernel(StateBaseStrategy::R15, BASE, Some(0)); + let allocation = regalloc::run_regalloc(&mut caller).unwrap(); + let result = emit_with_callees( + &caller, + &allocation.assignment, + allocation.spill_frame_size, + 4096, + &[usize::MAX], + ); + assert!( + matches!(result, Err(EmitError::Input(ref error)) if error.rule=="EMIT.NATIVE_ARENA_RANGE") + ); +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/slice.rs index 3f9787c512a..4e96c282003 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/slice.rs @@ -7,6 +7,11 @@ impl ISelContext<'_> { &mut self, inst: &SIRInstruction, ) { + if matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + { + self.reg_addrs.clear(); + } if let Some(write) = inst.memory_write() && write.width != 0 { diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs index 116d86e88b2..591039fb94c 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/slice.rs @@ -140,8 +140,14 @@ fn slice_preserves_loaded_value_across_store() { ); } if overlapping { - // Dynamic stores and commits also invalidate a static load. + // Dynamic stores, commits and opaque kernels invalidate + // a static load before any direct slice reload. for write in [ + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: vec![], + }, SIRInstruction::Store( input, SIROffset::Dynamic(replacement), diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs index cc6c401f0bd..e376073f7f8 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/assignment.rs @@ -98,8 +98,7 @@ pub const ALLOCATABLE_REGS: &[PhysReg] = &[ /// The registers an extern call changes: those a C function need not /// preserve, and RBX, which holds the state pointer during the call sequence. -#[cfg(not(target_os = "windows"))] -const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ +const NATIVE_KERNEL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, PhysReg::RCX, PhysReg::RDX, @@ -111,6 +110,8 @@ const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::R11, PhysReg::RBX, ]; +#[cfg(not(target_os = "windows"))] +const EXTERN_CALL_CLOBBERS: &[PhysReg] = NATIVE_KERNEL_CLOBBERS; #[cfg(target_os = "windows")] const EXTERN_CALL_CLOBBERS: &[PhysReg] = &[ PhysReg::RAX, @@ -223,6 +224,11 @@ pub fn clobbers(inst: &MInst) -> &'static [PhysReg] { // Return. Model the clobber at the allocation boundary instead so // only genuinely live-through values are moved to their homes. MInst::SparseCommitWorklist { .. } => ALLOCATABLE_REGS, + MInst::CallExtern { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + NATIVE_KERNEL_CLOBBERS + } MInst::CallExtern { .. } => EXTERN_CALL_CLOBBERS, _ => &[], } diff --git a/crates/celox-backend-x86/src/lib.rs b/crates/celox-backend-x86/src/lib.rs index 6d35faf9394..91afba2f67c 100644 --- a/crates/celox-backend-x86/src/lib.rs +++ b/crates/celox-backend-x86/src/lib.rs @@ -59,11 +59,25 @@ pub struct X86BackendOptions { pub native_tick_loop: bool, /// Physical state offset where the function's private spill, scratch, /// and save arena begins. `None` places it directly after the semantic - /// state. Functions that may run concurrently need disjoint arenas. + /// state. Functions that may run concurrently or call generated kernels + /// need disjoint arenas. Kernel callers must reserve at least every + /// callee's complete `required_state_size`; use `with_native_callees`. pub arena_base: Option, pub diagnostics: NativeDiagnostics, } +impl X86BackendOptions { + /// Place this function's private arena above all generated callees. + /// Sizes must be their complete emitted `required_state_size`, including + /// reservations for nested callees, rather than the semantic state size. + pub fn with_native_callees(mut self, sizes: impl IntoIterator) -> Self { + if let Some(end) = sizes.into_iter().max() { + self.arena_base = Some(self.arena_base.map_or(end, |base| base.max(end))); + } + self + } +} + impl Default for X86BackendOptions { fn default() -> Self { Self { diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs index b776566c169..6eb245ae5be 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/state_ssa.rs @@ -578,6 +578,29 @@ impl StateSsa { for (instruction_index, instruction) in block.instructions.iter().enumerate() { let mut instruction_effects = InstructionEffects::default(); match instruction { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + // An outlined native callee observes the old state and + // may replace every slot, including pending FF state. + for (slot, fact) in facts.iter_mut().enumerate() { + fact.escapes = true; + fact.has_kill = true; + fact.def_blocks.insert(block_id); + if !defined.contains(&slot) { + fact.upward_use_blocks.insert(block_id); + } + defined.insert(slot); + instruction_effects.uses.push(UseEffect { + slot, + destination: None, + }); + instruction_effects.defs.push(DefEffect { + slot, + kind: DefEffectKind::Kill, + }); + } + } SIRInstruction::Load(destination, addr, offset, width) if addr.region == region => { @@ -1314,6 +1337,72 @@ mod tests { .expect("destination has a StateSSA use") } + #[test] + fn native_kernel_call_observes_and_kills_every_state_region() { + for region in [STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION] { + let addr = address(region, 0); + let eu = unit( + vec![block( + 0, + vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(3u8)), + SIRInstruction::Store( + addr, + SIROffset::Static(0), + 8, + RegisterId(0), + Vec::new(), + Vec::new(), + ), + SIRInstruction::Load(RegisterId(1), addr, SIROffset::Static(0), 8), + SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }, + SIRInstruction::Load(RegisterId(2), addr, SIROffset::Static(0), 8), + ], + SIRTerminator::Return, + )], + (0..3).map(|i| (RegisterId(i), bit(8))), + ); + eu.verify_result().unwrap(); + let cfg = SirCfg::analyze(&eu).unwrap(); + let state = StateSsa::analyze_all_loads(&eu, &cfg, region).unwrap(); + let MemoryAccessKind::Use { + reaching: before, .. + } = use_access(&state, RegisterId(1)).kind + else { + panic!("load") + }; + let MemoryAccessKind::Use { + reaching: after, .. + } = use_access(&state, RegisterId(2)).kind + else { + panic!("load") + }; + assert_ne!(before, after); + assert!(matches!( + state.accesses[after.0].kind, + MemoryAccessKind::Kill { .. } + )); + assert!(state.slots[0].escapes && state.slots[0].has_kill); + assert!( + state + .accesses + .iter() + .any(|access| access.instruction == Some(3) + && matches!( + access.kind, + MemoryAccessKind::Use { + destination: None, + .. + } + )) + ); + } + } + #[test] fn version_snapshots_preserve_versions_across_multiple_checkpoints() { let stable = address(STABLE_REGION, 0); diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs index 066d74dd102..5f020e0d092 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_eliminate_working_round_trip.rs @@ -29,6 +29,19 @@ pub fn eliminate_partial_working_round_trip(eu: &mut ExecutionUnit, partial: bool) { use crate::HashMap; + // An image-local callee can observe or publish any working slot. Its + // contents are outside this function's proof of independent publication. + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + return; + } // Phase 1: Scan — collect info about each WORKING variable struct VarInfo { diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs index 53d462dd880..7036ac44bc9 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_global_store_load_forwarding.rs @@ -865,6 +865,19 @@ pub(crate) fn promote_eval_apply_working_round_trips_with_mode( eu: &mut ExecutionUnit, two_state: bool, ) -> bool { + if eu + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!(inst, SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some()) + }) + { + // The callee can consume pending values or publish working state. + // Keep this function's memory form until StateSSA models that callee. + return false; + } let Ok(cfg) = SirCfg::analyze(eu) else { return false; }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs index b9254cab4e3..7379d0dc3f1 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_store_load_forwarding.rs @@ -140,6 +140,11 @@ fn forward_and_simplify( // are always inserted after this rewrite, so one lookup is sufficient. apply_aliases_to_inst(inst, &aliases); match inst { + SIRInstruction::ExternCall { func, .. } + if celox_sir::extern_abi::native_kernel_index(*func).is_some() => + { + known_stores.clear(); + } SIRInstruction::Store(addr, offset, width, src, _triggers, _) if offset.constant_bit_offset().is_some() => { @@ -469,6 +474,64 @@ mod tests { } } + #[test] + fn native_kernel_call_invalidates_prior_state_stores() { + let mut builder = celox_sir::SIRBuilder::new(); + let before = builder.alloc_bit(8, false); + let after = builder.alloc_bit(8, false); + builder.emit(SIRInstruction::Imm(before, SIRValue::new(42u8))); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(0), + 8, + before, + Vec::new(), + Vec::new(), + )); + builder.emit(SIRInstruction::ExternCall { + dst: None, + func: celox_sir::extern_abi::NATIVE_KERNEL_CALL_TAG, + args: Vec::new(), + }); + builder.emit(SIRInstruction::Load( + after, + address(), + SIROffset::Static(0), + 8, + )); + builder.emit(SIRInstruction::Store( + address(), + SIROffset::Static(8), + 8, + after, + Vec::new(), + Vec::new(), + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + }; + StoreLoadForwardingPass.run(&mut unit, &PassOptions::default()); + unit.verify_result().unwrap(); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .any(|inst| matches!(inst, SIRInstruction::Load(dst, ..) if *dst == after)) + ); + let saved = unit.clone(); + super::super::pass_eliminate_working_round_trip::eliminate_working_round_trip( + &mut unit, + &[], + ); + assert_eq!(unit.blocks, saved.blocks); + assert!(!super::super::pass_global_store_load_forwarding::promote_eval_apply_working_round_trips(&mut unit)); + assert_eq!(unit.blocks, saved.blocks); + } + #[test] fn removes_deep_dead_producer_chain_and_preserves_live_store() { let mut instructions = vec![ diff --git a/crates/celox-sir/src/extern_abi.rs b/crates/celox-sir/src/extern_abi.rs index 8956d1f4b86..61474070b68 100644 --- a/crates/celox-sir/src/extern_abi.rs +++ b/crates/celox-sir/src/extern_abi.rs @@ -17,6 +17,21 @@ use crate::RegisterType; /// user extern function table. pub const HEAP_HELPER_ID: u32 = u32::MAX - 1; +/// Native-only call to another compiled function in the same image. The low +/// 30 bits index the extern address table. It takes the implicit state pointer, +/// no explicit arguments or result, and propagates a nonzero status to its +/// caller. The callee may read and write arbitrary simulation state. +pub const NATIVE_KERNEL_CALL_TAG: u32 = 0x8000_0000; + +/// Decode a native kernel call, excluding the heap and floating-point helpers. +pub const fn native_kernel_index(function: u32) -> Option { + if function & 0xc000_0000 == NATIVE_KERNEL_CALL_TAG { + Some(function & 0x3fff_ffff) + } else { + None + } +} + /// The number of arguments of an extern call to [`HEAP_HELPER_ID`]. pub const HEAP_HELPER_ARGUMENTS: usize = 4; diff --git a/crates/celox-sir/src/verify.rs b/crates/celox-sir/src/verify.rs index b5d4acd8c0d..82d442b791a 100644 --- a/crates/celox-sir/src/verify.rs +++ b/crates/celox-sir/src/verify.rs @@ -632,6 +632,16 @@ fn verify_instruction_types( same_width(*old, *new, "TYPE.CAPTURE_COMPARE_OPERANDS")?; } SIRInstruction::ExternCall { dst, func, args } => { + if crate::extern_abi::native_kernel_index(*func).is_some() + && (dst.is_some() || !args.is_empty()) + { + return Err(SirVerifyError::instruction( + "TYPE.NATIVE_KERNEL_CALL_SIGNATURE", + block, + index, + "a native kernel call has only an implicit state pointer", + )); + } if *func == crate::extern_abi::HEAP_HELPER_ID && args.len() != crate::extern_abi::HEAP_HELPER_ARGUMENTS {