wings-codegen 0.0.4

Cranelift AOT machine-code backend for Wings VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use cranelift_codegen::ir::{
    AbiParam, Block, InstBuilder, MemFlags, Value, condcodes::IntCC, types,
};
use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
use cranelift_module::{Linkage, Module};
use cranelift_object::ObjectModule;
use wings_abi::{DirectScalarIo, STATUS_BUDGET_EXHAUSTED, STATUS_CANCELLED};
use wings_ir::{Function, Operation};

use crate::emit::{ScalarParams, emit_pure_scalar, is_pure_scalar};
use crate::sra::RecordAnalysis;

#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct DirectSummary {
    pub(super) eligible: bool,
    pub(super) uses_heap: bool,
    pub(super) uses_inline_effects: bool,
    pub(super) base_steps: u64,
    pub(super) state_byte_copies: u64,
    pub(super) record_allocs: u64,
    pub(super) max_stack_bytes: u32,
}

impl DirectSummary {
    pub(super) fn encode(self) -> (u64, u64) {
        if !self.eligible
            || self.base_steps == 0
            || self.max_stack_bytes > 32 * 1024
            || self.state_byte_copies > u64::from(u16::MAX)
            || self.record_allocs > u64::from(u16::MAX)
        {
            return (0, 0);
        }
        let flags = u64::from(self.uses_heap)
            | (self.state_byte_copies << 1)
            | (self.record_allocs << 17)
            | (u64::from(self.uses_inline_effects) << 33);
        (self.base_steps, flags)
    }
}

pub(super) fn summarize_direct_function(
    function: &Function,
    own_frame_bytes: u32,
    callees: &[DirectSummary],
    analysis: &RecordAnalysis,
) -> DirectSummary {
    let mut base_steps = 1u64;
    let mut uses_heap = false;
    let mut uses_inline_effects = false;
    let mut state_byte_copies = 0u64;
    let mut record_allocs = 0u64;
    let mut max_callee_stack = 0u32;
    for (index, instruction) in function.instructions.iter().enumerate() {
        if analysis.is_no_op_heap(index) {
            let Some(next) = base_steps.checked_add(1) else {
                return DirectSummary::default();
            };
            base_steps = next;
            continue;
        }
        match instruction.operation {
            Operation::Constant(_)
            | Operation::NullPid
            | Operation::State
            | Operation::Argument(_)
            | Operation::Negate(_)
            | Operation::Compare(_, _, _)
            | Operation::Binary(_, _, _)
            | Operation::If(_)
            | Operation::Else(_)
            | Operation::EndIf(_)
            | Operation::PhiValue(_) => {
                let Some(next) = base_steps.checked_add(1) else {
                    return DirectSummary::default();
                };
                base_steps = next;
            }
            Operation::Call {
                function: callee_idx,
                ..
            } => {
                let Some(callee) = callees.get(callee_idx).copied() else {
                    return DirectSummary::default();
                };
                if !callee.eligible {
                    return DirectSummary::default();
                }
                let Some(next) = base_steps
                    .checked_add(1)
                    .and_then(|steps| steps.checked_add(callee.base_steps))
                else {
                    return DirectSummary::default();
                };
                base_steps = next;
                uses_heap |= callee.uses_heap;
                uses_inline_effects |= callee.uses_inline_effects;
                state_byte_copies = state_byte_copies.saturating_add(callee.state_byte_copies);
                record_allocs = record_allocs.saturating_add(callee.record_allocs);
                max_callee_stack = max_callee_stack.max(callee.max_stack_bytes);
            }
            Operation::BytesLen(_)
            | Operation::StringLen(_)
            | Operation::ByteAt(_, _)
            | Operation::ReadI64Be(_, _)
            | Operation::IsEmptyInts(_)
            | Operation::HeadInt(_)
            | Operation::TailInts(_)
            | Operation::RecordField { .. } => {
                uses_heap = true;
                let Some(next) = base_steps.checked_add(2) else {
                    return DirectSummary::default();
                };
                base_steps = next;
            }
            Operation::EmptyInts | Operation::PrependInt(_, _) | Operation::RecordNew { .. } => {
                uses_heap = true;
                let Some(next) = base_steps.checked_add(2) else {
                    return DirectSummary::default();
                };
                base_steps = next;
                record_allocs = record_allocs.saturating_add(1);
            }
            Operation::ReplaceByte([source, _, _]) | Operation::ReplaceI64Be([source, _, _]) => {
                if !function
                    .instructions
                    .get(source)
                    .is_some_and(|origin| matches!(origin.operation, Operation::State))
                {
                    return DirectSummary::default();
                }
                uses_heap = true;
                let Some(next) = base_steps.checked_add(2) else {
                    return DirectSummary::default();
                };
                base_steps = next;
                state_byte_copies = state_byte_copies.saturating_add(1);
            }
            Operation::SelfPid => {
                uses_inline_effects = true;
                let Some(next) = base_steps.checked_add(2) else {
                    return DirectSummary::default();
                };
                base_steps = next;
            }
            Operation::SendSelf { ref arguments, .. } | Operation::Send { ref arguments, .. } => {
                if arguments
                    .iter()
                    .any(|&reg| function.instructions[reg].ty.is_reference())
                {
                    return DirectSummary::default();
                }
                uses_inline_effects = true;
                let Some(next) = base_steps.checked_add(2) else {
                    return DirectSummary::default();
                };
                base_steps = next;
            }
            _ => return DirectSummary::default(),
        }
    }
    let Some(max_stack_bytes) = own_frame_bytes.checked_add(max_callee_stack) else {
        return DirectSummary::default();
    };
    DirectSummary {
        eligible: true,
        uses_heap,
        uses_inline_effects,
        base_steps,
        state_byte_copies,
        record_allocs,
        max_stack_bytes,
    }
}

fn is_direct_scalar_op(operation: &Operation) -> bool {
    is_pure_scalar(operation)
        || matches!(
            operation,
            Operation::If(_) | Operation::Else(_) | Operation::EndIf(_) | Operation::PhiValue(_)
        )
}

/// Compiles a specialized zero-context direct entry for pure-scalar acyclic
/// DAG handlers (straight-line and structured `if`/`else` branches)
/// (`DirectScalarEntry`).
///
/// Compared to `wings_scalar_handler_N`, this entry:
/// - avoids `ScalarContext` construction (112 bytes),
/// - performs a single `atomic_load` on `cancellation` (no `yield_request`),
/// - maintains a single `budget` value instead of `remaining_steps` +
///   `slice_remaining` with exact per-branch step accounting, and
/// - omits `ShadowFrame` setup and native stack-limit checks (already proven
///   bounded by `DirectSummary`).
pub(super) fn try_compile_direct_scalar(
    module: &mut ObjectModule,
    symbol: &str,
    function: &Function,
    analysis: &RecordAnalysis,
) -> Result<bool, String> {
    let pure_scalar_dag = function
        .instructions
        .iter()
        .enumerate()
        .all(|(index, inst)| is_direct_scalar_op(&inst.operation) || analysis.is_no_op_heap(index));
    if !pure_scalar_dag {
        return Ok(false);
    }

    let pointer_type = module.target_config().pointer_type();
    let mut context = module.make_context();
    context.func.signature.params = vec![
        AbiParam::new(types::I64),
        AbiParam::new(types::I64),
        AbiParam::new(types::I64),
        AbiParam::new(types::I64),
        AbiParam::new(pointer_type),
        AbiParam::new(pointer_type),
    ];
    context.func.signature.returns = vec![AbiParam::new(types::I32)];
    let identifier = module
        .declare_function(symbol, Linkage::Export, &context.func.signature)
        .map_err(|error| error.to_string())?;

    let mut builder_context = FunctionBuilderContext::new();
    let mut builder = FunctionBuilder::new(&mut context.func, &mut builder_context);
    let entry = builder.create_block();
    builder.append_block_params_for_function_params(entry);
    builder.switch_to_block(entry);
    let params = builder.block_params(entry).to_vec();
    let state_param = params[0];
    let inline_args = [params[1], params[2], params[3]];
    let cancellation_ptr = params[4];
    let io_ptr = params[5];
    let budget_offset = std::mem::offset_of!(DirectScalarIo, budget) as i32;
    let output_offset = std::mem::offset_of!(DirectScalarIo, output) as i32;
    let args_ptr_offset = std::mem::offset_of!(DirectScalarIo, args_ptr) as i32;

    let exit = builder.create_block();
    builder.append_block_param(exit, types::I32);

    let cancelled_val = builder
        .ins()
        .load(types::I32, MemFlags::new(), cancellation_ptr, 0);
    let is_cancelled = builder.ins().icmp_imm(IntCC::NotEqual, cancelled_val, 0);
    let cancel_block = builder.create_block();
    builder.set_cold_block(cancel_block);
    let check_budget = builder.create_block();
    builder
        .ins()
        .brif(is_cancelled, cancel_block, &[], check_budget, &[]);

    builder.switch_to_block(cancel_block);
    let cancel_status = builder
        .ins()
        .iconst(types::I32, i64::from(STATUS_CANCELLED));
    builder.ins().jump(exit, &[cancel_status]);

    builder.switch_to_block(check_budget);
    let has_branches = function
        .instructions
        .iter()
        .any(|inst| matches!(inst.operation, Operation::If(_)));
    let total_steps = (function.instructions.len() + 1) as i64;
    let budget = builder
        .ins()
        .load(types::I64, MemFlags::new(), io_ptr, budget_offset);
    let body_block = builder.create_block();
    let exhausted_block = builder.create_block();
    builder.set_cold_block(exhausted_block);
    if has_branches {
        let has_any = builder.ins().icmp_imm(IntCC::NotEqual, budget, 0);
        builder
            .ins()
            .brif(has_any, body_block, &[], exhausted_block, &[]);
    } else {
        let has_budget =
            builder
                .ins()
                .icmp_imm(IntCC::UnsignedGreaterThanOrEqual, budget, total_steps);
        builder
            .ins()
            .brif(has_budget, body_block, &[], exhausted_block, &[]);
    }

    builder.switch_to_block(exhausted_block);
    let zero = builder.ins().iconst(types::I64, 0);
    builder
        .ins()
        .store(MemFlags::new(), zero, io_ptr, budget_offset);
    let exhausted_status = builder
        .ins()
        .iconst(types::I32, i64::from(STATUS_BUDGET_EXHAUSTED));
    builder.ins().jump(exit, &[exhausted_status]);

    builder.switch_to_block(body_block);
    let needs_args_ptr = function
        .instructions
        .iter()
        .any(|inst| matches!(inst.operation, Operation::Argument(idx) if idx >= 3));
    let args_ptr = if needs_args_ptr {
        builder.ins().load(
            pointer_type,
            MemFlags::new().with_readonly(),
            io_ptr,
            args_ptr_offset,
        )
    } else {
        io_ptr
    };
    let mut registers = Vec::with_capacity(function.instructions.len());
    let mut branches: Vec<(Block, Block, Value)> = Vec::new();
    let mut rem_budget = budget;
    let mut segment_steps: i64 = 0;
    let mut index = 0;
    while index < function.instructions.len() {
        let instruction = &function.instructions[index];
        if let Some(target) = analysis.forwarded[index] {
            registers.push(registers[target]);
            segment_steps += 1;
            index += 1;
            continue;
        }
        if analysis.elided[index] {
            registers.push(builder.ins().iconst(types::I64, 0));
            segment_steps += 1;
            index += 1;
            continue;
        }
        match instruction.operation {
            Operation::If(condition) => {
                rem_budget = builder.ins().iadd_imm(rem_budget, -(segment_steps + 1));
                segment_steps = 0;
                let then_block = builder.create_block();
                let else_block = builder.create_block();
                let merge_block = builder.create_block();
                builder
                    .ins()
                    .brif(registers[condition], then_block, &[], else_block, &[]);
                builder.switch_to_block(then_block);
                branches.push((else_block, merge_block, rem_budget));
                registers.push(builder.ins().iconst(types::I64, 0));
                index += 1;
            }
            Operation::Else(ref values) => {
                let (else_block, merge_block, budget_before_if) =
                    *branches.last().ok_or("missing validated branch")?;
                let then_budget = builder.ins().iadd_imm(rem_budget, -(segment_steps + 1));
                segment_steps = 0;
                for _ in 0..values.len() {
                    builder.append_block_param(merge_block, types::I64);
                }
                builder.append_block_param(merge_block, types::I64);
                let mut args: Vec<Value> = values.iter().map(|&reg| registers[reg]).collect();
                args.push(then_budget);
                builder.ins().jump(merge_block, &args);
                builder.switch_to_block(else_block);
                rem_budget = budget_before_if;
                registers.push(builder.ins().iconst(types::I64, 0));
                index += 1;
            }
            Operation::EndIf(ref values) => {
                let (_, merge_block, _) = branches.pop().ok_or("missing validated branch")?;
                let else_budget = if segment_steps > 0 {
                    builder.ins().iadd_imm(rem_budget, -segment_steps)
                } else {
                    rem_budget
                };
                let mut args: Vec<Value> = values.iter().map(|&reg| registers[reg]).collect();
                args.push(else_budget);
                builder.ins().jump(merge_block, &args);
                builder.switch_to_block(merge_block);
                let merge_params = builder.block_params(merge_block).to_vec();
                rem_budget = merge_params[values.len()];
                segment_steps = 1;
                if values.is_empty() {
                    registers.push(builder.ins().iconst(types::I64, 0));
                    index += 1;
                } else {
                    registers.extend_from_slice(&merge_params[..values.len()]);
                    index += values.len();
                }
            }
            Operation::PhiValue(_) => {
                return Err("unexpected standalone phi value in direct scalar DAG".into());
            }
            _ => {
                let fault_exit = builder.create_block();
                builder.set_cold_block(fault_exit);
                builder.append_block_param(fault_exit, types::I32);
                let value = emit_pure_scalar(
                    &mut builder,
                    &instruction.operation,
                    ScalarParams::Handler {
                        state: state_param,
                        inline_args,
                        args_ptr,
                    },
                    &registers,
                    fault_exit,
                );
                let next_block = builder.create_block();
                builder.ins().jump(next_block, &[]);

                builder.switch_to_block(fault_exit);
                let fault_status = builder.block_params(fault_exit)[0];
                let next_budget = builder.ins().iadd_imm(rem_budget, -(segment_steps + 1));
                if has_branches {
                    let consumed = builder.ins().isub(budget, next_budget);
                    let enough =
                        builder
                            .ins()
                            .icmp(IntCC::UnsignedGreaterThanOrEqual, budget, consumed);
                    let commit_fault = builder.create_block();
                    builder
                        .ins()
                        .brif(enough, commit_fault, &[], exhausted_block, &[]);
                    builder.switch_to_block(commit_fault);
                }
                builder
                    .ins()
                    .store(MemFlags::new(), next_budget, io_ptr, budget_offset);
                builder.ins().jump(exit, &[fault_status]);

                builder.switch_to_block(next_block);
                segment_steps += 1;
                registers.push(value);
                index += 1;
            }
        }
    }
    if !branches.is_empty() {
        return Err("unclosed branch in direct scalar DAG".into());
    }

    let remaining = builder.ins().iadd_imm(rem_budget, -(segment_steps + 1));
    if has_branches {
        let consumed = builder.ins().isub(budget, remaining);
        let enough = builder
            .ins()
            .icmp(IntCC::UnsignedGreaterThanOrEqual, budget, consumed);
        let commit_ok = builder.create_block();
        builder
            .ins()
            .brif(enough, commit_ok, &[], exhausted_block, &[]);
        builder.switch_to_block(commit_ok);
    }
    builder
        .ins()
        .store(MemFlags::new(), remaining, io_ptr, budget_offset);
    builder.ins().store(
        MemFlags::new(),
        registers[function.state],
        io_ptr,
        output_offset,
    );
    builder.ins().store(
        MemFlags::new(),
        registers[function.reply],
        io_ptr,
        output_offset + 8,
    );
    let ok_status = builder.ins().iconst(types::I32, 0);
    builder.ins().jump(exit, &[ok_status]);

    builder.switch_to_block(exit);
    let status = builder.block_params(exit)[0];
    builder.ins().return_(&[status]);
    builder.seal_all_blocks();
    builder.finalize();

    module
        .define_function(identifier, &mut context)
        .map_err(|error| error.to_string())?;
    Ok(true)
}