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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use super::*;
use cranelift_frontend::Variable;

/// Register-resident effective step budget (`min(remaining_steps, slice_remaining)`).
///
/// Both `ScalarContext::remaining_steps` and `ScalarContext::slice_remaining`
/// decrement by the exact same step count between runtime callbacks, so keeping
/// their minimum in a Cranelift SSA `Variable` (mapped to a physical register)
/// eliminates per-safepoint and per-loop-iteration memory loads/stores to
/// `ScalarContext`. The delta `synced - current` is flushed back only at
/// runtime callbacks, managed calls, slow-path checks, and function exits.
#[derive(Clone, Copy)]
pub(super) struct BudgetVars {
    pub(super) current: Variable,
    pub(super) synced: Variable,
}

/// Shrink-wrapped `ShadowFrame` descriptor whose linkage into `ScalarContext::roots`
/// is deferred until the first non-empty `publish_roots` site on a path.
#[derive(Clone, Copy)]
pub(super) struct ShadowRoots {
    pub(super) context_ptr: Value,
    pub(super) frame: Value,
    pub(super) slots: Value,
    pub(super) previous: Variable,
    pub(super) linked: Variable,
}

pub(super) fn init_budget(builder: &mut FunctionBuilder<'_>, context: Value) -> BudgetVars {
    let current = Variable::from_u32(0);
    let synced = Variable::from_u32(1);
    builder.declare_var(current, types::I64);
    builder.declare_var(synced, types::I64);
    let budget = BudgetVars { current, synced };
    reload_budget(builder, context, budget);
    budget
}

pub(super) fn reload_budget(builder: &mut FunctionBuilder<'_>, context: Value, budget: BudgetVars) {
    let remaining = builder.ins().load(
        types::I64,
        MemFlags::new(),
        context,
        std::mem::offset_of!(ScalarContext, remaining_steps) as i32,
    );
    let slice = builder.ins().load(
        types::I64,
        MemFlags::new(),
        context,
        std::mem::offset_of!(ScalarContext, slice_remaining) as i32,
    );
    let effective = builder.ins().umin(remaining, slice);
    builder.def_var(budget.current, effective);
    builder.def_var(budget.synced, effective);
}

pub(super) fn flush_budget(
    builder: &mut FunctionBuilder<'_>,
    context: Value,
    budget: BudgetVars,
) -> Value {
    let cur = builder.use_var(budget.current);
    let synced = builder.use_var(budget.synced);
    let consumed = builder.ins().isub(synced, cur);
    let remaining = builder.ins().load(
        types::I64,
        MemFlags::new(),
        context,
        std::mem::offset_of!(ScalarContext, remaining_steps) as i32,
    );
    let next_remaining = builder.ins().isub(remaining, consumed);
    builder.ins().store(
        MemFlags::new(),
        next_remaining,
        context,
        std::mem::offset_of!(ScalarContext, remaining_steps) as i32,
    );
    let slice = builder.ins().load(
        types::I64,
        MemFlags::new(),
        context,
        std::mem::offset_of!(ScalarContext, slice_remaining) as i32,
    );
    let next_slice = builder.ins().isub(slice, consumed);
    builder.ins().store(
        MemFlags::new(),
        next_slice,
        context,
        std::mem::offset_of!(ScalarContext, slice_remaining) as i32,
    );
    builder.def_var(budget.synced, cur);
    next_remaining
}

pub(super) fn is_pure_scalar(operation: &Operation) -> bool {
    matches!(
        operation,
        Operation::Constant(_)
            | Operation::NullPid
            | Operation::State
            | Operation::Argument(_)
            | Operation::Negate(_)
            | Operation::Compare(_, _, _)
            | Operation::Binary(_, _, _)
    )
}

/// Operations that fold their step charge forward into the next polling
/// instruction instead of emitting a standalone safepoint each.
///
/// `Loop` and `While` defer into the mandatory `EndLoop` back-edge poll, so a
/// loop iteration pays exactly one safepoint instead of three. Iteration
/// accounting stays exact: each pass through the back edge charges the full
/// deferred static count again, and only the final exit iteration skips a
/// couple of steps, bounded like any other deferral window.
pub(super) fn is_deferrable_op(operation: &Operation) -> bool {
    !is_pure_scalar(operation)
        && !matches!(
            operation,
            Operation::Call { .. }
                | Operation::EndLoop(_)
                | Operation::If(_)
                | Operation::Else(_)
                | Operation::EndIf(_)
                | Operation::PhiValue(_)
        )
}

/// Operations that may allocate, invoke GC, call another managed function, or
/// suspend via runtime callbacks, and therefore require live references to be
/// published into the `ShadowFrame` before execution. Pure O(1) read-only heap
/// operations never allocate or checkpoint and skip `publish_roots`.
pub(super) fn needs_inline_roots(operation: &Operation) -> bool {
    (is_deferrable_op(operation) || matches!(operation, Operation::Call { .. }))
        && !matches!(
            operation,
            Operation::Loop(_)
                | Operation::While(_, _)
                | Operation::RecordField { .. }
                | Operation::HeadInt(_)
                | Operation::TailInts(_)
                | Operation::IsEmptyInts(_)
                | Operation::BytesLen(_)
                | Operation::StringLen(_)
                | Operation::ByteAt(_, _)
                | Operation::ReadI64Be(_, _)
        )
}

pub(super) enum ScalarParams<'a> {
    Handler {
        state: Value,
        inline_args: [Value; 3],
        args_ptr: Value,
    },
    Procedure(&'a [Value]),
}

pub(super) fn emit_pure_scalar(
    builder: &mut FunctionBuilder<'_>,
    operation: &Operation,
    parameters: ScalarParams<'_>,
    registers: &[Value],
    exit: Block,
) -> Value {
    match *operation {
        Operation::Constant(value) => builder.ins().iconst(types::I64, value),
        Operation::NullPid => builder.ins().iconst(types::I64, 0),
        Operation::State => match parameters {
            ScalarParams::Handler { state, .. } => state,
            ScalarParams::Procedure(_) => unreachable!("procedures cannot read actor state"),
        },
        Operation::Argument(index) => match parameters {
            ScalarParams::Handler {
                inline_args,
                args_ptr,
                ..
            } => {
                if index < inline_args.len() {
                    inline_args[index]
                } else {
                    builder
                        .ins()
                        .load(types::I64, MemFlags::new(), args_ptr, (index * 8) as i32)
                }
            }
            ScalarParams::Procedure(args) => args[index],
        },
        Operation::Negate(value) => {
            let zero = builder.ins().iconst(types::I64, 0);
            let (result, overflow) = builder.ins().ssub_overflow(zero, registers[value]);
            fail_if_to(builder, overflow, STATUS_OVERFLOW, exit);
            result
        }
        Operation::Compare(comparison, left, right) => {
            let condition = match comparison {
                Comparison::Equal => IntCC::Equal,
                Comparison::NotEqual => IntCC::NotEqual,
                Comparison::Less => IntCC::SignedLessThan,
                Comparison::LessEqual => IntCC::SignedLessThanOrEqual,
                Comparison::Greater => IntCC::SignedGreaterThan,
                Comparison::GreaterEqual => IntCC::SignedGreaterThanOrEqual,
            };
            let result = builder
                .ins()
                .icmp(condition, registers[left], registers[right]);
            builder.ins().uextend(types::I64, result)
        }
        Operation::Binary(operator, left, right) => {
            let left = registers[left];
            let right = registers[right];
            match operator {
                Operator::Divide | Operator::Remainder => {
                    let zero = builder.ins().icmp_imm(IntCC::Equal, right, 0);
                    fail_if_to(builder, zero, STATUS_DIVISION_BY_ZERO, exit);
                    let minimum = builder.ins().icmp_imm(IntCC::Equal, left, i64::MIN);
                    let negative_one = builder.ins().icmp_imm(IntCC::Equal, right, -1);
                    let overflow = builder.ins().band(minimum, negative_one);
                    fail_if_to(builder, overflow, STATUS_OVERFLOW, exit);
                    if matches!(operator, Operator::Divide) {
                        builder.ins().sdiv(left, right)
                    } else {
                        builder.ins().srem(left, right)
                    }
                }
                _ => {
                    let (result, overflow) = match operator {
                        Operator::Add => builder.ins().sadd_overflow(left, right),
                        Operator::Subtract => builder.ins().ssub_overflow(left, right),
                        Operator::Multiply => builder.ins().smul_overflow(left, right),
                        Operator::Divide | Operator::Remainder => unreachable!(),
                    };
                    fail_if_to(builder, overflow, STATUS_OVERFLOW, exit);
                    result
                }
            }
        }
        _ => unreachable!("expected pure scalar operation"),
    }
}

/// Emits one safepoint covering `steps` sequential instruction polls. The
/// caller folds the cost of straight-line operations that carry no safepoint
/// of their own into this single charge; the budget accounting below is
/// exactly equivalent to `steps` consecutive one-step polls: on the fast path
/// both budgets drop by `steps`, and a starved poll grants whatever budget is
/// left before looping the outstanding remainder through the slow path.
#[allow(clippy::too_many_arguments)]
pub(super) fn poll_control(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    context: Value,
    control_ptr: Value,
    budget: BudgetVars,
    slow_signature: SigRef,
    exit: Block,
    roots: Option<ShadowRoots>,
    live: &[usize],
    registers: &[Value],
    steps: i64,
) {
    debug_assert!(steps > 0);
    let readonly = MemFlags::new().with_readonly();
    let poll = builder.create_block();
    builder.append_block_param(poll, types::I64);
    let continuation = builder.create_block();
    let slow_check = builder.create_block();
    builder.set_cold_block(slow_check);
    let reload_block = builder.create_block();
    builder.set_cold_block(reload_block);
    let initial_owed = builder.ins().iconst(types::I64, steps);
    builder.ins().jump(poll, &[initial_owed]);

    builder.switch_to_block(poll);
    let owed = builder.block_params(poll)[0];
    // Single aligned 32-bit control-word load (`CONTROL_CANCELLED | CONTROL_YIELD_REQUESTED`):
    // single-copy atomic on x86-64 and AArch64 without `ldar` barriers on the hot path.
    let control_word = builder
        .ins()
        .load(types::I32, MemFlags::new(), control_ptr, 0);
    let effective = builder.use_var(budget.current);
    let clean_flags = builder.ins().icmp_imm(IntCC::Equal, control_word, 0);
    let has_budget = builder
        .ins()
        .icmp(IntCC::UnsignedGreaterThanOrEqual, effective, owed);
    let can_continue = builder.ins().band(clean_flags, has_budget);
    builder
        .ins()
        .brif(can_continue, continuation, &[], slow_check, &[]);

    builder.switch_to_block(slow_check);
    let cancel_bit = builder
        .ins()
        .band_imm(control_word, i64::from(wings_abi::CONTROL_CANCELLED));
    let cancelled = builder.ins().icmp_imm(IntCC::NotEqual, cancel_bit, 0);
    fail_if_to(builder, cancelled, STATUS_CANCELLED, exit);
    // Sequential polls would grant every step the remaining budget can pay
    // for before reporting exhaustion or invoking the slow path, so grant
    // `min(owed, effective)` here and carry the unpaid rest into the repoll.
    let grant = builder.ins().umin(effective, owed);
    let granted_effective = builder.ins().isub(effective, grant);
    builder.def_var(budget.current, granted_effective);
    let granted_remaining = flush_budget(builder, context, budget);
    let next_owed = builder.ins().isub(owed, grant);
    let exhausted = builder.ins().icmp_imm(IntCC::Equal, granted_remaining, 0);
    fail_if_to(builder, exhausted, STATUS_BUDGET_EXHAUSTED, exit);
    publish_roots(builder, pointer_type, roots, live, registers);
    let callback = builder.ins().load(
        pointer_type,
        readonly,
        context,
        std::mem::offset_of!(ScalarContext, slow_path) as i32,
    );
    let missing = builder.ins().icmp_imm(IntCC::Equal, callback, 0);
    fail_if_to(builder, missing, STATUS_INVALID_CONTROL, exit);
    let call = builder
        .ins()
        .call_indirect(slow_signature, callback, &[context]);
    let status = builder.inst_results(call)[0];
    let success = builder.ins().icmp_imm(IntCC::Equal, status, 0);
    builder
        .ins()
        .brif(success, reload_block, &[], exit, &[status]);

    builder.switch_to_block(reload_block);
    reload_budget(builder, context, budget);
    builder.ins().jump(poll, &[next_owed]);

    builder.switch_to_block(continuation);
    let next_effective = builder.ins().isub(effective, owed);
    builder.def_var(budget.current, next_effective);
}

pub(super) fn publish_roots(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    roots: Option<ShadowRoots>,
    live: &[usize],
    registers: &[Value],
) {
    publish_roots_incremental(builder, pointer_type, roots, live, None, registers);
}

/// Publishes live reference registers into the function's `ShadowFrame`,
/// lazily linking the frame into `ScalarContext::roots` on first non-empty
/// publication and skipping redundant prefix stores along straight-line blocks.
pub(super) fn publish_roots_incremental(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    roots: Option<ShadowRoots>,
    live: &[usize],
    previously_published: Option<&[usize]>,
    registers: &[Value],
) {
    let Some(roots) = roots else {
        return;
    };
    if previously_published == Some(live) {
        return;
    }
    if live.is_empty() {
        let is_linked = builder.use_var(roots.linked);
        let clear_block = builder.create_block();
        builder.set_cold_block(clear_block);
        let done_block = builder.create_block();
        builder
            .ins()
            .brif(is_linked, clear_block, &[], done_block, &[]);
        builder.switch_to_block(clear_block);
        let zero = builder.ins().iconst(pointer_type, 0);
        builder.ins().store(
            MemFlags::new(),
            zero,
            roots.frame,
            std::mem::offset_of!(ShadowFrame, count) as i32,
        );
        builder.ins().jump(done_block, &[]);
        builder.switch_to_block(done_block);
        return;
    }
    let common_prefix = previously_published
        .map(|prev| {
            prev.iter()
                .zip(live.iter())
                .take_while(|(a, b)| a == b)
                .count()
        })
        .unwrap_or(0);
    for (index, register) in live.iter().enumerate().skip(common_prefix) {
        builder.ins().store(
            MemFlags::new(),
            registers[*register],
            roots.slots,
            (index * 8) as i32,
        );
    }
    if previously_published.map(<[usize]>::len) != Some(live.len()) {
        let count = builder.ins().iconst(pointer_type, live.len() as i64);
        builder.ins().store(
            MemFlags::new(),
            count,
            roots.frame,
            std::mem::offset_of!(ShadowFrame, count) as i32,
        );
    }
    if previously_published.is_some_and(|prev| !prev.is_empty()) {
        return;
    }
    let is_linked = builder.use_var(roots.linked);
    let link_block = builder.create_block();
    let after_link = builder.create_block();
    builder
        .ins()
        .brif(is_linked, after_link, &[], link_block, &[]);
    builder.switch_to_block(link_block);
    let prev = builder.ins().load(
        pointer_type,
        MemFlags::new(),
        roots.context_ptr,
        std::mem::offset_of!(ScalarContext, roots) as i32,
    );
    builder.ins().store(
        MemFlags::new(),
        prev,
        roots.frame,
        std::mem::offset_of!(ShadowFrame, previous) as i32,
    );
    builder.ins().store(
        MemFlags::new(),
        roots.slots,
        roots.frame,
        std::mem::offset_of!(ShadowFrame, slots) as i32,
    );
    builder.ins().store(
        MemFlags::new(),
        roots.frame,
        roots.context_ptr,
        std::mem::offset_of!(ScalarContext, roots) as i32,
    );
    builder.def_var(roots.previous, prev);
    let one = builder.ins().iconst(types::I8, 1);
    builder.def_var(roots.linked, one);
    builder.ins().jump(after_link, &[]);
    builder.switch_to_block(after_link);
}

#[allow(clippy::too_many_arguments)]
pub(super) fn call_heap(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    context: Value,
    budget: BudgetVars,
    signature: SigRef,
    operation: u32,
    argument: Value,
    output: Value,
    exit: Block,
) -> Value {
    let callback = builder.ins().load(
        pointer_type,
        MemFlags::new().with_readonly(),
        context,
        std::mem::offset_of!(ScalarContext, heap_call) as i32,
    );
    let missing = builder.ins().icmp_imm(IntCC::Equal, callback, 0);
    fail_if_to(builder, missing, STATUS_INVALID_CONTROL, exit);
    flush_budget(builder, context, budget);
    let operation = builder.ins().iconst(types::I32, i64::from(operation));
    let call =
        builder
            .ins()
            .call_indirect(signature, callback, &[context, operation, argument, output]);
    let status = builder.inst_results(call)[0];
    let success = builder.ins().icmp_imm(IntCC::Equal, status, 0);
    let continuation = builder.create_block();
    builder
        .ins()
        .brif(success, continuation, &[], exit, &[status]);
    builder.switch_to_block(continuation);
    reload_budget(builder, context, budget);
    builder.ins().load(types::I64, MemFlags::new(), output, 0)
}

pub(super) fn fail_if_to(
    builder: &mut FunctionBuilder<'_>,
    condition: Value,
    status: u32,
    exit: Block,
) {
    let continuation = builder.create_block();
    let status = builder.ins().iconst(types::I32, i64::from(status));
    builder
        .ins()
        .brif(condition, exit, &[status], continuation, &[]);
    builder.switch_to_block(continuation);
}

pub(super) fn fail_if(builder: &mut FunctionBuilder<'_>, condition: Value, status: u32) {
    let failure = builder.create_block();
    builder.set_cold_block(failure);
    let continuation = builder.create_block();
    builder
        .ins()
        .brif(condition, failure, &[], continuation, &[]);
    builder.switch_to_block(failure);
    let status = builder.ins().iconst(types::I32, i64::from(status));
    builder.ins().return_(&[status]);
    builder.switch_to_block(continuation);
}

/// Maps loop-header phi roots (`header..header + initials.len()`) back to their
/// pre-loop `initials` so a pre-header poll publishes only registers defined
/// before the loop block.
pub(super) fn remap_pre_loop_roots(
    live: &[usize],
    header: usize,
    initials: &[usize],
) -> Vec<usize> {
    let mut mapped: Vec<usize> = live
        .iter()
        .map(|&r| {
            r.checked_sub(header)
                .and_then(|s| initials.get(s).copied())
                .unwrap_or(r)
        })
        .collect();
    mapped.sort_unstable();
    mapped.dedup();
    mapped
}

/// Emits a zero-call inline fast path for reading inline fields (`0` or `1`) of
/// a 32-byte `#[repr(C)]` `RecordHeap::Slot` directly from `ScalarContext::heap_slots`,
/// falling back to `slow_fallback` on any invalid reference, layout mismatch,
/// or absent slot table.
pub(super) use super::emit_heap::{emit_heap_op, is_inline_alloc_op};