1
//! P11 — effect-preserving static unrolling of `DO` / `DO*` (0014 Stage 2).
2
//!
3
//! A loop whose control is constant — every init, step and end test is
4
//! fold-safe and no body form stores to a loop variable — is unrolled: each
5
//! iteration's body is *compiled*, not evaluated, in the live context with
6
//! the loop variables bound as constant data for that iteration, so a
7
//! store, a definition, a condition or a macro expansion in the body is
8
//! emitted once per iteration in loop order. The iterations and the bytes
9
//! they emit are charged against the work budget; a loop that exhausts it
10
//! is a resource error, never a silent switch to the runtime loop.
11
//!
12
//! Unrolling is required when the body uses a macro or makes a definition
13
//! (the runtime loop cannot bind the variable as the datum a macro reads,
14
//! nor commit a definition statically); any other constant-control loop
15
//! unrolls when a simulation finds it terminates within
16
//! `MAX_STATIC_LOOP_ITERS` and otherwise runs at runtime, with identical
17
//! behaviour. A loop whose control is not constant compiles as a runtime
18
//! loop.
19

            
20
use crate::ast::{Expr, WasmType};
21
use crate::compiler::context::CompileContext;
22
use crate::compiler::emit::FunctionEmitter;
23
use crate::compiler::expr::{
24
    compile_body, compile_body_for_stack, compile_for_effect, compile_nil, fold_safe_under,
25
    fold_value, member_value,
26
};
27
use crate::error::{Error, Result};
28
use crate::runtime::{Head, Symbol, SymbolKind, SymbolTable};
29

            
30
use super::super::binding::shared::needs_cell_stepped;
31
use super::super::setf_scan::collect_setf_targets;
32
use super::common::{
33
    DoLoop, MAX_STATIC_LOOP_ITERS, parse_do_vars, parse_end_clause, static_loop_iterations,
34
};
35
use super::runtime::{
36
    compile_do_runtime, compile_do_runtime_for_effect, compile_do_runtime_for_stack, loop_scope,
37
};
38

            
39
/// Where the loop's value goes.
40
#[derive(Clone, Copy)]
41
pub(super) enum Pos {
42
    /// Written to the output.
43
    Value,
44
    /// Dropped.
45
    Effect,
46
    /// Left on the operand stack.
47
    Stack,
48
}
49

            
50
/// Compiles a DO / DO* loop in `pos`: unrolled when P11 applies, at runtime
51
/// otherwise. The stack type is reported only for [`Pos::Stack`].
52
112031
pub(super) fn compile_loop(
53
112031
    ctx: &mut CompileContext,
54
112031
    emit: &mut FunctionEmitter,
55
112031
    symbols: &mut SymbolTable,
56
112031
    dl: &DoLoop<'_>,
57
112031
    pos: Pos,
58
112031
) -> Result<Option<WasmType>> {
59
112031
    if let Some((inits, iterations)) = constant_control(symbols, dl)? {
60
10677
        return unroll(ctx, emit, symbols, dl, inits, iterations, pos).map(Some);
61
101354
    }
62
101354
    match pos {
63
16573
        Pos::Value => compile_do_runtime(ctx, emit, symbols, dl).map(|()| None),
64
11047
        Pos::Effect => compile_do_runtime_for_effect(ctx, emit, symbols, dl).map(|()| None),
65
73734
        Pos::Stack => compile_do_runtime_for_stack(ctx, emit, symbols, dl).map(Some),
66
    }
67
112031
}
68

            
69
/// The initial values of the `DO` / `DO*` form `(head . args)` when P11
70
/// unrolls it, or `None` when it runs at runtime.
71
178556
pub(in crate::compiler::special) fn unrolled_inits(
72
178556
    symbols: &mut SymbolTable,
73
178556
    head: &str,
74
178556
    args: &[Expr],
75
178556
) -> Result<Option<Vec<Expr>>> {
76
178556
    let (Some(vars), Some(end), Some(body)) = (args.first(), args.get(1), args.get(2..)) else {
77
208
        return Ok(None);
78
    };
79
178348
    let vars = parse_do_vars(symbols, head, vars)?;
80
178348
    let (end_test, result_forms) = parse_end_clause(head, end)?;
81
178348
    let dl = DoLoop {
82
178348
        vars: &vars,
83
178348
        end_test,
84
178348
        result_forms,
85
178348
        body,
86
178348
        sequential: head == "DO*",
87
178348
        keys: &[],
88
178348
    };
89
178348
    constant_control(symbols, &dl).map(|control| control.map(|(inits, _)| inits))
90
178556
}
91

            
92
/// Whether the eval surface must leave `(head . args)` to codegen's runtime
93
/// loop: a macro body runs the loop for real, anywhere else it only peeks at
94
/// the type codegen emits.
95
195181
pub(super) fn left_to_runtime_loop(
96
195181
    symbols: &SymbolTable,
97
195181
    head: &str,
98
195181
    args: &[Expr],
99
195181
) -> Result<bool> {
100
195181
    if symbols.is_macro_expansion() {
101
82244
        return Ok(false);
102
112937
    }
103
112937
    unrolled_inits(&mut symbols.clone(), head, args).map(|inits| inits.is_none())
104
195181
}
105

            
106
/// The initial values of a loop that P11 unrolls, or `None` when the loop
107
/// runs at runtime.
108
290379
fn constant_control(
109
290379
    symbols: &mut SymbolTable,
110
290379
    dl: &DoLoop<'_>,
111
290379
) -> Result<Option<(Vec<Expr>, usize)>> {
112
440130
    let names: Vec<&str> = dl.vars.iter().map(|v| v.name.as_str()).collect();
113
408768
    let stores_to_a_variable = |form: &Expr| {
114
408768
        let targets = collect_setf_targets(std::slice::from_ref(form));
115
408768
        targets
116
408768
            .iter()
117
107517
            .any(|(target, _)| names.contains(&target.as_str()))
118
408768
    };
119
290379
    if dl
120
290379
        .body
121
290379
        .iter()
122
290379
        .chain(dl.result_forms)
123
290379
        .any(stores_to_a_variable)
124
    {
125
1985
        return Ok(None);
126
288394
    }
127
288394
    let steps_and_test = dl
128
288394
        .vars
129
288394
        .iter()
130
434898
        .filter_map(|v| v.step.as_ref())
131
288394
        .chain(std::iter::once(dl.end_test));
132
288394
    if !steps_and_test
133
288394
        .into_iter()
134
582830
        .all(|form| fold_safe_under(symbols, &names, form))
135
    {
136
229083
        return Ok(None);
137
59311
    }
138
59311
    let Some(inits) = initial_values(symbols, dl)? else {
139
5930
        return Ok(None);
140
    };
141
53381
    for (at, v) in dl.vars.iter().enumerate() {
142
66023
        if needs_cell_stepped(symbols, &v.name, v.step.is_some(), loop_scope(dl, at))? {
143
12
            return Ok(None);
144
66011
        }
145
    }
146
53369
    let stepped: Vec<(String, Option<Expr>)> = dl
147
53369
        .vars
148
53369
        .iter()
149
66011
        .map(|v| (v.name.clone(), v.step.clone()))
150
        .collect();
151
53369
    let forced = body_needs_unrolling(symbols, dl.body);
152
53369
    let max_iterations = match forced {
153
8681
        true => affordable_iterations(symbols, dl)?,
154
44688
        false => MAX_STATIC_LOOP_ITERS,
155
    };
156
53369
    symbols.push_scope();
157
53369
    for (v, init) in dl.vars.iter().zip(&inits) {
158
66011
        symbols.define_scoped(Symbol::new(&v.name, SymbolKind::Variable).with_value(init.clone()));
159
    }
160
53369
    let iterations = static_loop_iterations(
161
53369
        symbols,
162
53369
        dl.end_test,
163
53369
        &stepped,
164
53369
        dl.sequential,
165
53369
        max_iterations,
166
53369
    );
167
53369
    symbols.pop_scope()?;
168
53369
    Ok(iterations.map(|iterations| (inits, iterations)))
169
290379
}
170

            
171
/// Emitted bytes per node of the body, a generous estimate of an unrolled
172
/// iteration's charge.
173
const BYTES_PER_NODE: u64 = 8;
174

            
175
/// How many times the evaluator and the codegen pass each nested loop's body
176
/// run for one iteration of the loop around it.
177
const NESTED_PASSES: u64 = 3;
178

            
179
/// The work units one of `iterations` iterations of a loop unrolled here may
180
/// leave to the loops nested in it.
181
109933
pub(super) fn iteration_share(symbols: &SymbolTable, iterations: usize) -> u64 {
182
109933
    symbols.unroll_allowance() / ((iterations as u64).max(1) * NESTED_PASSES)
183
109933
}
184

            
185
/// The iterations a loop that must unroll may take before its unrolled body
186
/// exhausts its share of the work budget; a longer loop runs at runtime instead.
187
8681
fn affordable_iterations(symbols: &SymbolTable, dl: &DoLoop<'_>) -> Result<usize> {
188
8681
    let mut nodes = 0_u64;
189
8681
    for form in dl.body {
190
15576
        nodes = nodes.saturating_add(crate::compiler::datum::cost(form)?);
191
    }
192
8681
    let per_iteration = 1 + nodes.saturating_mul(BYTES_PER_NODE);
193
8681
    let affordable = symbols.unroll_allowance() / per_iteration;
194
8681
    Ok(usize::try_from(affordable).unwrap_or(usize::MAX))
195
8681
}
196

            
197
/// Each init folded in order; a DO* init sees the variables before it. `None`
198
/// when an init is not a fold-safe constant.
199
59311
fn initial_values(symbols: &mut SymbolTable, dl: &DoLoop<'_>) -> Result<Option<Vec<Expr>>> {
200
59311
    let mut bound: Vec<&str> = Vec::with_capacity(dl.vars.len());
201
59311
    let mut inits: Vec<Expr> = Vec::with_capacity(dl.vars.len());
202
59311
    for v in dl.vars {
203
72821
        let value = match &v.init {
204
            None => Expr::Nil,
205
72821
            Some(init) if dl.sequential => {
206
4246
                if !fold_safe_under(symbols, &bound, init) {
207
851
                    return Ok(None);
208
3395
                }
209
                // A DO* init reads the variables before it: fold it with them
210
                // bound in a frame, so the live table is as it was afterwards.
211
3395
                symbols.push_scope();
212
3395
                for (name, value) in bound.iter().zip(&inits) {
213
1264
                    symbols.define_scoped(
214
1264
                        Symbol::new(*name, SymbolKind::Variable).with_value(value.clone()),
215
1264
                    );
216
                }
217
3395
                let folded = fold_value(symbols, init);
218
3395
                symbols.pop_scope()?;
219
3395
                match folded? {
220
3395
                    Some(value) => value,
221
                    None => return Ok(None),
222
                }
223
            }
224
68575
            Some(init) => match fold_value(symbols, init)? {
225
63496
                Some(value) => value,
226
5079
                None => return Ok(None),
227
            },
228
        };
229
66891
        inits.push(value);
230
66891
        bound.push(v.name.as_str());
231
    }
232
53381
    Ok(Some(inits))
233
59311
}
234

            
235
/// Whether the body uses a macro or makes a definition anywhere in its text.
236
53369
fn body_needs_unrolling(symbols: &SymbolTable, body: &[Expr]) -> bool {
237
53369
    let mut pending: Vec<&Expr> = body.iter().collect();
238
292334
    while let Some(form) = pending.pop() {
239
247646
        let Expr::List(elems) = form else {
240
163936
            continue;
241
        };
242
83710
        if let Some(Expr::Symbol(head)) = elems.first() {
243
80792
            if head.eq_ignore_ascii_case("QUOTE") {
244
                continue;
245
80792
            }
246
80792
            let upper = head.to_ascii_uppercase();
247
80792
            if DEFINITIONS.contains(&upper.as_str())
248
80777
                || matches!(symbols.resolve_head(head), Head::Macro(..))
249
            {
250
8681
                return true;
251
72111
            }
252
2918
        }
253
75029
        pending.extend(elems);
254
    }
255
44688
    false
256
53369
}
257

            
258
const DEFINITIONS: &[&str] = &["DEFUN", "DEFMACRO", "DEFVAR", "DEFPARAMETER", "DEFSTRUCT"];
259

            
260
/// Binds a loop variable in the open frame, which restores its value cell.
261
406368
fn bind(symbols: &mut SymbolTable, name: &str, value: Expr) {
262
406368
    symbols.define_scoped(
263
406368
        Symbol::new(name, SymbolKind::Variable)
264
406368
            .with_value(member_value(value))
265
406368
            .loop_constant(),
266
406368
    );
267
406368
}
268

            
269
10677
fn unroll(
270
10677
    ctx: &mut CompileContext,
271
10677
    emit: &mut FunctionEmitter,
272
10677
    symbols: &mut SymbolTable,
273
10677
    dl: &DoLoop<'_>,
274
10677
    inits: Vec<Expr>,
275
10677
    iterations: usize,
276
10677
    pos: Pos,
277
10677
) -> Result<WasmType> {
278
10677
    let share = iteration_share(symbols, iterations);
279
10677
    symbols.with_scope(|symbols| unroll_bound(ctx, emit, symbols, dl, inits, share, pos))
280
10677
}
281

            
282
10677
fn unroll_bound(
283
10677
    ctx: &mut CompileContext,
284
10677
    emit: &mut FunctionEmitter,
285
10677
    symbols: &mut SymbolTable,
286
10677
    dl: &DoLoop<'_>,
287
10677
    inits: Vec<Expr>,
288
10677
    share: u64,
289
10677
    pos: Pos,
290
10677
) -> Result<WasmType> {
291
10677
    for (v, init) in dl.vars.iter().zip(inits) {
292
13333
        bind(symbols, &v.name, init);
293
    }
294
    loop {
295
396971
        if !constant(symbols, dl.end_test)?.is_nil() {
296
10459
            return finish(ctx, emit, symbols, dl.result_forms, pos);
297
386512
        }
298
386512
        let before = emit.bytes_ref().len();
299
386512
        symbols.charge_work(1)?;
300
386512
        symbols.with_unroll_allowance(share, |symbols| {
301
386512
            dl.body
302
386512
                .iter()
303
375564
                .try_for_each(|form| compile_for_effect(ctx, emit, symbols, form))
304
386512
        })?;
305
386294
        symbols.charge_work(emit.bytes_ref().len().saturating_sub(before) as u64)?;
306
386294
        step(symbols, dl)?;
307
    }
308
10677
}
309

            
310
/// A control form's value under the loop variables' current bindings; its
311
/// fold safety was established before the first iteration was emitted, so
312
/// a failure here is the form's own evaluation error.
313
790006
fn constant(symbols: &mut SymbolTable, form: &Expr) -> Result<Expr> {
314
790006
    fold_value(symbols, form)?.ok_or_else(|| {
315
        Error::Compile(format!(
316
            "DO: the control form {} does not evaluate under constant loop variables",
317
            crate::compiler::expr::format_expr(form)
318
        ))
319
    })
320
790006
}
321

            
322
386294
fn step(symbols: &mut SymbolTable, dl: &DoLoop<'_>) -> Result<()> {
323
386294
    if dl.sequential {
324
1936
        for v in dl.vars {
325
3236
            if let Some(step) = &v.step {
326
3236
                let value = constant(symbols, step)?;
327
3236
                bind(symbols, &v.name, value);
328
            }
329
        }
330
1936
        return Ok(());
331
384358
    }
332
384358
    let stepped: Vec<(&str, Expr)> = dl
333
384358
        .vars
334
384358
        .iter()
335
513982
        .filter_map(|v| v.step.as_ref().map(|step| (v.name.as_str(), step)))
336
389799
        .map(|(name, step)| constant(symbols, step).map(|value| (name, value)))
337
        .collect::<Result<_>>()?;
338
384358
    for (name, value) in stepped {
339
389799
        bind(symbols, name, value);
340
    }
341
384358
    Ok(())
342
386294
}
343

            
344
/// The result forms in `pos`, with the loop variables still bound.
345
10459
fn finish(
346
10459
    ctx: &mut CompileContext,
347
10459
    emit: &mut FunctionEmitter,
348
10459
    symbols: &mut SymbolTable,
349
10459
    result_forms: &[Expr],
350
10459
    pos: Pos,
351
10459
) -> Result<WasmType> {
352
10459
    match pos {
353
3777
        Pos::Value if result_forms.is_empty() => compile_nil(ctx, emit).map(|()| WasmType::Bool),
354
3149
        Pos::Value => compile_body(ctx, emit, symbols, result_forms).map(|()| WasmType::Bool),
355
        Pos::Effect => {
356
4240
            for form in result_forms {
357
2918
                compile_for_effect(ctx, emit, symbols, form)?;
358
            }
359
4240
            Ok(WasmType::Bool)
360
        }
361
2442
        Pos::Stack if result_forms.is_empty() => {
362
725
            emit.i32_const(0);
363
725
            Ok(WasmType::Bool)
364
        }
365
1717
        Pos::Stack => compile_body_for_stack(ctx, emit, symbols, result_forms),
366
    }
367
10459
}
368

            
369
#[cfg(test)]
370
#[path = "unroll_tests.rs"]
371
mod tests;