vulkane-kernel-text 0.31.1

The shared text walker for Vulkane's kernel emitters: lowers an Unpopped kernel-layer KernelFn to C-like shader source through a per-language Dialect (GLSL, WGSL). Vulkane owns the text targets.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Statements and structured control flow.
//!
//! `If` and `While` map to the native statements; a `While` condition that needs hoisted temporaries
//! is written `while (true) { temps; if (!cond) { break; } body }` so they run every pass. `For` is a
//! native `for (init; test; update)` inside its own scope that declares the bounds once, so a
//! `continue` still runs the update. Statements after a `Break`, `Continue` or `Return` in a block
//! are dead and are not written.

use unpopped::backend::LowerError;
use unpopped::ir::ScalarExpr;
use unpopped::kernel::{BarrierKind, Block, CollectiveKind, KernelFn, ParamKind, Place, Stmt};
use unpopped::types::{Ty, infer_ty_in};
use unpopped_vocab::ElementKind;

use crate::dialect::{Dialect, SubgroupCollective};
use crate::expr;
use crate::scope::{Scope, place_name, place_ok, refuse};

mod atomic;

/// The text being written.
struct W<'a> {
    d: &'a dyn Dialect,
    kernel: &'a KernelFn,
    sc: &'a Scope,
    out: &'a mut String,
    depth: usize,
    loops: u32,
    pins: u32,
}

/// Write the body of `kernel` at one level of indentation.
/// Whether `block` holds a `Collective` at any depth.
pub(crate) fn uses_collective(block: &Block) -> bool {
    block.0.iter().any(|s| match s {
        Stmt::Collective { .. } => true,
        Stmt::If { then, els, .. } => uses_collective(then) || uses_collective(els),
        Stmt::For { body, .. } | Stmt::While { body, .. } => uses_collective(body),
        _ => false,
    })
}

pub(crate) fn emit_body(
    d: &dyn Dialect,
    kernel: &KernelFn,
    sc: &Scope,
    out: &mut String,
) -> Result<(), LowerError> {
    let mut w = W {
        d,
        kernel,
        sc,
        out,
        depth: 1,
        loops: 0,
        pins: 0,
    };
    w.block(&kernel.body).map(drop)
}

/// The variant name of a statement: the `Debug` text up to the first non-identifier character.
fn stmt_name(s: &Stmt) -> String {
    let text = format!("{s:?}");
    text.chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect()
}

impl W<'_> {
    fn line(&mut self, text: &str) {
        for _ in 0..self.depth {
            self.out.push_str("    ");
        }
        self.out.push_str(text);
        self.out.push('\n');
    }

    /// [`Self::line`] as a statement result.
    fn emit(&mut self, text: &str) -> Result<(), LowerError> {
        self.line(text);
        Ok(())
    }

    fn no(&self, what: impl std::fmt::Display) -> LowerError {
        refuse(self.sc.backend, self.kernel, what)
    }

    /// The root spelling of `e`, its hoisted declarations written first.
    fn expr(&mut self, e: &ScalarExpr) -> Result<String, LowerError> {
        let (prelude, root) = expr::lower(self.d, self.kernel, self.sc, e)?;
        for p in prelude.iter().filter(|p| !p.is_empty()) {
            self.line(p);
        }
        Ok(root)
    }

    /// In a float kernel, `value` held in a temporary no compiler may fuse the operations of (a
    /// stored `a * b + a` must round twice, as the oracle does); otherwise `value` itself.
    fn pinned(&mut self, value: String, place: &Place) -> Result<String, LowerError> {
        if !self.sc.float {
            return Ok(value);
        }
        // The value has the element type of the place it is stored to.
        let elem = match place {
            Place::Logical { buffer, .. } => {
                match &self.kernel.params[usize::try_from(*buffer).expect("buffer id fits usize")]
                    .kind
                {
                    ParamKind::Buffer { elem, .. } => *elem,
                    _ => self.kernel.compute,
                }
            }
            _ => self.kernel.compute,
        };
        self.pinned_elem(value, elem)
    }

    /// `value`, of element type `elem`, held in a temporary (see [`Self::pinned`]).
    fn pinned_elem(&mut self, value: String, elem: ElementKind) -> Result<String, LowerError> {
        let ty = self.d.type_name(elem);
        let Some(ty) = ty else {
            return Err(self.no("a float kernel needs a float type name"));
        };
        let name = format!("p{}", self.pins);
        self.pins += 1;
        let decl = self.d.temp_typed(&ty, &name, &value);
        self.line(&decl);
        Ok(name)
    }

    /// The element type of `e` in this kernel.
    fn elem_of(&self, e: &ScalarExpr) -> Result<ElementKind, LowerError> {
        let tys: Vec<Ty> = self.kernel.locals.iter().map(|l| l.ty()).collect();
        match infer_ty_in(e, self.kernel.compute, &tys) {
            Ok(Ty::Scalar(t)) => Ok(t),
            _ => Err(self.no("a condition whose type cannot be inferred")),
        }
    }

    /// The boolean text of `cond != 0`. A float kernel's condition is a float (pinned first, so its
    /// multiplies and adds are not fused) or an integer leaf (a loop counter, an execution id).
    fn condition(&mut self, cond: &ScalarExpr) -> Result<String, LowerError> {
        let c = self.expr(cond)?;
        if !self.sc.float {
            return Ok(self.d.truthy(&c, self.sc.signed));
        }
        let elem = self.elem_of(cond)?;
        let c = if matches!(elem, ElementKind::F32 | ElementKind::F64) {
            self.pinned_elem(c, elem)?
        } else {
            c
        };
        Ok(self.d.truthy_of(&c, elem))
    }

    /// Lower a block; `true` when it ended in a terminator.
    fn block(&mut self, block: &Block) -> Result<bool, LowerError> {
        for s in &block.0 {
            self.stmt(s)?;
            if matches!(s, Stmt::Break | Stmt::Continue | Stmt::Return) {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// `body` one level deeper.
    fn nested(&mut self, body: &Block) -> Result<(), LowerError> {
        self.depth += 1;
        let r = self.block(body);
        self.depth -= 1;
        r.map(drop)
    }

    fn stmt(&mut self, s: &Stmt) -> Result<(), LowerError> {
        match s {
            Stmt::Let { .. } | Stmt::Assign { .. } | Stmt::Load { .. } | Stmt::Store { .. } => self.data(s),
            Stmt::MaskedLoad { .. } | Stmt::MaskedStore { .. } => self.masked(s),
            Stmt::Barrier { .. } | Stmt::Fence { .. } => self.sync(s),
            Stmt::AtomicRmw { .. } | Stmt::AtomicCas { .. } => self.atomic(s),
            Stmt::Collective { .. } => self.collective(s),
            Stmt::If { .. } | Stmt::For { .. } | Stmt::While { .. } => self.control(s),
            Stmt::Break => self.emit("break;"),
            Stmt::Continue => self.emit("continue;"),
            Stmt::Return => self.emit("return;"),
            other => Err(self.no(format!(
                "`Stmt::{}` is not lowered (v1: Let, Load, Assign, Store, MaskedLoad, MaskedStore, Barrier, Fence, atomics where the dialect spells them, control flow){}",
                stmt_name(other),
                crate::coverage::not_lowered_note(other).map_or_else(String::new, |n| format!(": {n}"))
            ))),
        }
    }

    /// The element `place` names, as an lvalue or rvalue.
    fn element(&mut self, place: &Place) -> Result<String, LowerError> {
        if !place_ok(place) {
            return Err(self.no(format!(
                "place {place:?} is not lowered (v1: one-coordinate buffer or shared element)"
            )));
        }
        let (name, idx, is_buffer) = match place {
            Place::Logical { buffer, coords } => (format!("b{buffer}"), &coords[0], true),
            Place::Alloc { alloc, index } => (format!("a{alloc}"), index, false),
            _ => unreachable!("place_ok admits two forms"),
        };
        let idx = self.expr(idx)?;
        Ok(self.d.index(&name, &idx, is_buffer))
    }

    /// Whether `place` addresses an atomically typed buffer or array.
    fn is_atomic(&self, place: &Place) -> bool {
        place_name(place).is_some_and(|n| self.sc.atomic.contains(&n))
    }

    /// The read of `elem`: itself, or the dialect's atomic load when the buffer is atomically typed.
    fn read_of(&self, place: &Place, elem: String) -> Result<String, LowerError> {
        if !self.is_atomic(place) {
            return Ok(elem);
        }
        self.d
            .atomic_load(&elem)
            .ok_or_else(|| self.no("an atomically typed buffer has no atomic load here"))
    }

    /// The write of `value` to `elem`: a plain assignment, or the dialect's atomic store.
    fn write_of(&self, place: &Place, elem: &str, value: &str) -> Result<String, LowerError> {
        if !self.is_atomic(place) {
            return Ok(format!("{elem} = {value};"));
        }
        self.d
            .atomic_store(elem, value)
            .ok_or_else(|| self.no("an atomically typed buffer has no atomic store here"))
    }

    fn data(&mut self, s: &Stmt) -> Result<(), LowerError> {
        match s {
            Stmt::Let { local, init: v } | Stmt::Assign { local, value: v } => {
                let v = self.expr(v)?;
                self.emit(&format!("l{local} = {v};"))
            }
            Stmt::Load { local, place } => {
                let e = self.element(place)?;
                let e = self.read_of(place, e)?;
                self.emit(&format!("l{local} = {e};"))
            }
            Stmt::Store { place, value } => {
                let e = self.element(place)?;
                let v = self.expr(value)?;
                let v = self.pinned(v, place)?;
                let text = self.write_of(place, &e, &v)?;
                self.emit(&text)
            }
            _ => unreachable!("`stmt` routes only data statements here"),
        }
    }

    /// Predicated access (ROADMAP 9e): a guarded plain access, so the memory is not touched where the mask is false
    /// (no bounds check, no race record: exactly the IR's meaning). `MaskedLoad` is
    /// `if (mask) { l = element; } else { l = fill; }`, `MaskedStore` is `if (mask) { element = value; }`; each goes
    /// through the plain `Load` / `Store` path, so an atomically typed buffer and a pinned float value behave as there.
    fn masked(&mut self, s: &Stmt) -> Result<(), LowerError> {
        match s {
            Stmt::MaskedLoad {
                local,
                place,
                mask,
                fill,
            } => {
                let t = self.condition(mask)?;
                self.line(&format!("if {t} {{"));
                self.guarded(&Stmt::Load {
                    local: *local,
                    place: place.clone(),
                })?;
                self.line("} else {");
                self.guarded(&Stmt::Assign {
                    local: *local,
                    value: fill.clone(),
                })?;
                self.emit("}")
            }
            Stmt::MaskedStore { place, value, mask } => {
                let t = self.condition(mask)?;
                self.line(&format!("if {t} {{"));
                self.guarded(&Stmt::Store {
                    place: place.clone(),
                    value: value.clone(),
                })?;
                self.emit("}")
            }
            _ => unreachable!("`stmt` routes only masked statements here"),
        }
    }

    /// One data statement one level deeper (the depth is restored on an error too).
    fn guarded(&mut self, s: &Stmt) -> Result<(), LowerError> {
        self.depth += 1;
        let r = self.data(s);
        self.depth -= 1;
        r
    }

    fn sync(&mut self, s: &Stmt) -> Result<(), LowerError> {
        let text = match s {
            Stmt::Barrier {
                scope,
                kind: BarrierKind::Full,
            } => self.d.barrier(*scope),
            Stmt::Fence { scope, order } => self.d.fence(*scope, *order),
            _ => None,
        };
        let Some(text) = text else {
            return Err(self.no(format!(
                "`Stmt::{}` at this scope or kind has no {} spelling",
                stmt_name(s),
                self.d.name()
            )));
        };
        self.emit(&text)
    }

    /// A ruled subgroup collective (board 506 "A"): the dialect spells the expression, the walker assigns it to the statement's result
    /// local. Reached only for a dialect that [`Dialect::subgroup_collectives`] and a kind of [`crate::collective_is_ruled`]; the by-name decline
    /// has already refused every other `Collective`, and `check_kernel` every divergent placement.
    fn collective(&mut self, s: &Stmt) -> Result<(), LowerError> {
        let Stmt::Collective {
            kind,
            value,
            result,
            scope,
        } = s
        else {
            unreachable!("`stmt` routes only collectives here");
        };
        if !self.d.subgroup_collectives() || !crate::collective_is_ruled(kind, *scope) {
            return Err(self.no(format!(
                "`Stmt::Collective` ({kind:?} at {scope:?}) is not lowered by this dialect"
            )));
        }
        let value_elem = self.elem_of(value)?;
        let value = self.expr(value)?;
        let operand_expr = match kind {
            CollectiveKind::Shuffle { operand, .. } => Some(operand),
            CollectiveKind::Broadcast { lane } => Some(lane),
            _ => None,
        };
        let (operand, operand_const) = match operand_expr {
            Some(e) => {
                let text = self.expr(e)?;
                let constant = match e {
                    ScalarExpr::ConstInt(v, _) => Some(*v),
                    _ => None,
                };
                (Some(text), constant)
            }
            None => (None, None),
        };
        let subgroup = self
            .kernel
            .launch
            .and_then(|l| l.subgroup)
            .map(|g| (g.min, g.max));
        let call = SubgroupCollective {
            kind,
            value,
            value_elem,
            operand,
            operand_const,
            signed: self.sc.signed,
            subgroup,
        };
        let rhs = self
            .d
            .subgroup_collective(&call)
            .map_err(|why| self.no(format!("`Stmt::Collective` ({kind:?}): {why}")))?;
        self.emit(&format!("l{result} = {rhs};"))
    }

    fn control(&mut self, s: &Stmt) -> Result<(), LowerError> {
        match s {
            Stmt::If { cond, then, els } => self.lower_if(cond, then, els),
            Stmt::While { cond, body } => self.lower_while(cond, body),
            Stmt::For {
                local,
                start,
                end,
                step,
                body,
                ..
            } => self.lower_for(*local, [start, end, step], body),
            _ => unreachable!("`stmt` routes only control statements here"),
        }
    }

    fn lower_if(&mut self, cond: &ScalarExpr, then: &Block, els: &Block) -> Result<(), LowerError> {
        let t = self.condition(cond)?;
        self.line(&format!("if {t} {{"));
        self.nested(then)?;
        if !els.0.is_empty() {
            self.line("} else {");
            self.nested(els)?;
        }
        self.emit("}")
    }

    fn lower_while(&mut self, cond: &ScalarExpr, body: &Block) -> Result<(), LowerError> {
        self.line("while (true) {");
        self.depth += 1;
        let c = self.condition(cond);
        let r = c.and_then(|t| {
            self.line(&format!("if (!{t}) {{ break; }}"));
            self.block(body).map(drop)
        });
        self.depth -= 1;
        r?;
        self.emit("}")
    }

    /// The loop test: `i < end` for a positive step, `i > end` for a negative one (`I32` only); a
    /// zero step is false.
    fn counted_test(&self, i: &str, e: &str, s: &str, signed: bool) -> String {
        let zero = if self.sc.float {
            // A float kernel's counter is an integer local, not the compute dtype.
            if signed { "0" } else { "0u" }.to_string()
        } else {
            self.d.lit(0, signed)
        };
        if signed {
            format!("(({s} > {zero} && {i} < {e}) || ({s} < {zero} && {i} > {e}))")
        } else {
            format!("({s} != {zero} && {i} < {e})")
        }
    }

    fn lower_for(
        &mut self,
        local: u32,
        [start, end, step]: [&ScalarExpr; 3],
        body: &Block,
    ) -> Result<(), LowerError> {
        let n = self.loops;
        self.loops += 1;
        self.line("{");
        self.depth += 1;
        let r = self.for_in_scope(local, n, [start, end, step], body);
        self.depth -= 1;
        r?;
        self.emit("}")
    }

    /// The counter local's element type and whether it is signed: the compute dtype's own, except in
    /// a float kernel, whose counters are `I32`/`U32` locals.
    fn counter(&self, local: u32) -> (ElementKind, bool) {
        if !self.sc.float {
            return (self.kernel.compute, self.sc.signed);
        }
        let kind = self.kernel.locals[usize::try_from(local).expect("local id fits usize")].elem;
        (kind, kind == ElementKind::I32)
    }

    fn for_in_scope(
        &mut self,
        local: u32,
        n: u32,
        [start, end, step]: [&ScalarExpr; 3],
        body: &Block,
    ) -> Result<(), LowerError> {
        let (kind, signed) = self.counter(local);
        let (start, end, step) = (self.expr(start)?, self.expr(end)?, self.expr(step)?);
        let (eb, sb) = (format!("e{n}"), format!("s{n}"));
        let (end_decl, step_decl) = if self.sc.float {
            let ty = self.d.type_name(kind).unwrap_or_default();
            (
                self.d.temp_typed(&ty, &eb, &end),
                self.d.temp_typed(&ty, &sb, &step),
            )
        } else {
            (
                self.d.bound(&eb, &end, signed),
                self.d.bound(&sb, &step, signed),
            )
        };
        self.line(&end_decl);
        self.line(&step_decl);
        let (i, e, s) = (format!("l{local}"), format!("e{n}"), format!("s{n}"));
        let test = self.counted_test(&i, &e, &s, signed);
        self.line(&format!(
            "for ({i} = {start}; {test}; {i} = ({i} + {s})) {{"
        ));
        self.nested(body)?;
        self.emit("}")
    }
}