Skip to main content

vulkane_kernel_text/
coverage.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Where every [`Stmt`] variant stands in this repository's emitters (ROADMAP row 9f).
3
4use unpopped::kernel::Stmt;
5
6use crate::decline::collective_is_ruled;
7
8/// What the emitters of this repository do with a statement.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub enum Coverage {
11    /// Lowered by the shared walker and by the SPIR-V emitter (`Assume` by omission: it emits nothing).
12    Lowered,
13    /// Not lowered yet, and a ROADMAP row says what it waits for (the text).
14    Row(&'static str),
15    /// Refused by name for possible patent exposure (board 434 C, its extension, and board 539): see `declined_by_name`.
16    Patent,
17    /// An NVIDIA-specific operation with no spelling in the target languages of this repository; the reason.
18    Nvidia(&'static str),
19}
20
21/// The coverage of `stmt` for an emitter that lowers the ruled subgroup collectives (`lift_subgroup`, the answer of
22/// `Dialect::subgroup_collectives()`: WGSL and MSL since #186) or not (every other emitter). It is [`coverage`] except for a
23/// `Stmt::Collective` that [`collective_is_ruled`] admits, which a lifting emitter LOWERS: [`coverage`] alone says "refused for
24/// exposure" (ROADMAP row 8w). It calls `collective_is_ruled` exactly, so what counts as lowered cannot widen here without
25/// widening there; the unruled kinds and scopes, and `CollectiveTuple`, stay [`Coverage::Patent`] for every emitter.
26///
27/// `Lowered` here answers the exposure question (is it refused by name?), not "does every emitter lower every form": MSL still
28/// declines `Vote(Ballot)` as an unmeasured conversion, a different refusal that its own test pins.
29#[must_use]
30pub fn coverage_in(lift_subgroup: bool, stmt: &Stmt) -> Coverage {
31    if lift_subgroup {
32        if let Stmt::Collective { kind, scope, .. } = stmt {
33            if collective_is_ruled(kind, *scope) {
34                return Coverage::Lowered;
35            }
36        }
37    }
38    coverage(stmt)
39}
40
41/// The coverage of `stmt`, **dialect-agnostic**: an emitter that lowers the ruled subgroup collectives (WGSL, MSL) lowers more
42/// than this says for a `Collective`, so ask [`coverage_in`] with its `subgroup_collectives()`. **This match has no wildcard arm on
43/// purpose**: it names every [`Stmt`] variant, so a new
44/// statement in `unpopped` fails to compile here until someone decides which of the four it is.
45#[must_use]
46pub fn coverage(stmt: &Stmt) -> Coverage {
47    match stmt {
48        Stmt::Let { .. }
49        | Stmt::Load { .. }
50        | Stmt::Assign { .. }
51        | Stmt::Store { .. }
52        | Stmt::MaskedLoad { .. }
53        | Stmt::MaskedStore { .. }
54        | Stmt::If { .. }
55        | Stmt::For { .. }
56        | Stmt::While { .. }
57        | Stmt::Break
58        | Stmt::Continue
59        | Stmt::Return
60        | Stmt::Barrier { .. }
61        | Stmt::Fence { .. }
62        | Stmt::AtomicRmw { .. }
63        | Stmt::AtomicCas { .. }
64        // Lowered BY OMISSION (unpopped 0.64, U50): a value fact that reads and writes nothing; no emitted text.
65        | Stmt::Assume { .. }
66        // Lowered BY OMISSION (unpopped 0.66, U55): a scheduling hint means nothing and ignoring it is always correct.
67        | Stmt::ScheduleHint { .. } => Coverage::Lowered,
68        Stmt::Call { .. } | Stmt::CallTuple { .. } | Stmt::ExternCall { .. } => {
69            Coverage::Row("ROADMAP row 8g: device function calls are not lowered yet")
70        }
71        Stmt::Mma { .. } | Stmt::MatrixLoad { .. } | Stmt::MatrixStore { .. } => Coverage::Row(
72            "ROADMAP row 8j: matrix multiply-accumulate waits on a device with the extension (SPIR-V, GLSL) and on Unpopped's tile statements (Metal)",
73        ),
74        Stmt::TileLoad { .. }
75        | Stmt::TileMma { .. }
76        | Stmt::TileFill { .. }
77        | Stmt::TileStore { .. } => Coverage::Row(
78            "ROADMAP row 8j: the tile statements (unpopped 0.62) are declined by name until a device with the cooperative-matrix extension (SPIR-V, GLSL) or simdgroup matrices (Metal) can run them; no saturating variant and no transpose option (US12405770B2 hold)",
79        ),
80        Stmt::CopyAsync { .. }
81        | Stmt::AsyncCommit
82        | Stmt::AsyncWait { .. }
83        | Stmt::Collective { .. }
84        | Stmt::CollectiveTuple { .. }
85        | Stmt::MbarInit { .. }
86        | Stmt::MbarArrive { .. }
87        | Stmt::MbarCompleteTx { .. }
88        | Stmt::MbarWait { .. }
89        | Stmt::CopyBulk { .. }
90        | Stmt::Tcgen05Commit { .. }
91        | Stmt::WgmmaWait { .. }
92        | Stmt::CopyUnpack { .. }
93        | Stmt::LaunchGrid { .. } => Coverage::Patent,
94        Stmt::Wgmma { .. } | Stmt::WgmmaCommit => Coverage::Nvidia(
95            "a warpgroup-level asynchronous matrix multiply-accumulate (PTX `wgmma`, Hopper); none of SPIR-V, GLSL, HLSL, WGSL or MSL has a construct with its asynchronous warpgroup semantics",
96        ),
97        Stmt::Tcgen05Mma { .. }
98        | Stmt::Tcgen05Ld { .. }
99        | Stmt::Tcgen05Alloc { .. }
100        | Stmt::Tcgen05Dealloc { .. }
101        | Stmt::Tcgen05RelinquishPermit => Coverage::Nvidia(
102            "a fifth-generation tensor-core operation on tensor memory (PTX `tcgen05`, Blackwell); no target language of this repository has tensor memory",
103        ),
104        Stmt::ProxyFence { .. } => Coverage::Nvidia(
105            "an async-proxy fence (PTX `fence.proxy.async`, as unpopped documents `ProxyFence`): it orders generic-proxy writes against the asynchronous proxy that `CopyBulk` and `wgmma` use; no target language of this repository has memory proxies",
106        ),
107        Stmt::GridDepWait | Stmt::GridDepLaunchDependents => Coverage::Nvidia(
108            "CUDA programmatic dependent launch (a kernel waiting on, or releasing, the next kernel of a stream); a Vulkan dispatch has no in-kernel dependency on another dispatch",
109        ),
110        Stmt::MulticastLoadReduce { .. } => Coverage::Nvidia(
111            "an NVLink multicast load-reduce (PTX `multimem`) over several devices' memory; no target language of this repository addresses another device's memory",
112        ),
113    }
114}
115
116/// The sentence an emitter adds to its "not lowered" refusal of `stmt`: the row it waits for, the by-name ruling or
117/// the NVIDIA-specific reason, or `None` for a statement the emitters lower (a refusal of one is about its operands).
118#[must_use]
119pub fn not_lowered_note(stmt: &Stmt) -> Option<String> {
120    match coverage(stmt) {
121        Coverage::Lowered => None,
122        Coverage::Row(why) => Some(why.to_string()),
123        Coverage::Patent if matches!(stmt, Stmt::LaunchGrid { .. }) => Some(
124            "refused by name for possible patent exposure (board 539), see `declined_by_name`"
125                .to_string(),
126        ),
127        Coverage::Patent => Some(
128            "refused by name for possible patent exposure (board 434 C), see `declined_by_name`"
129                .to_string(),
130        ),
131        Coverage::Nvidia(why) => Some(format!("NVIDIA-specific: {why}")),
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use unpopped::exec::Scope;
139    use unpopped::kernel::{BarrierKind, Stmt};
140
141    #[test]
142    fn the_cheap_to_build_variants_are_classified_as_documented() {
143        assert_eq!(coverage(&Stmt::Break), Coverage::Lowered);
144        assert_eq!(
145            coverage(&Stmt::Barrier {
146                scope: Scope::Block,
147                kind: BarrierKind::Full
148            }),
149            Coverage::Lowered
150        );
151        assert_eq!(coverage(&Stmt::AsyncCommit), Coverage::Patent);
152        for s in [
153            Stmt::WgmmaCommit,
154            Stmt::GridDepWait,
155            Stmt::GridDepLaunchDependents,
156        ] {
157            assert!(
158                matches!(coverage(&s), Coverage::Nvidia(why) if !why.is_empty()),
159                "{s:?}"
160            );
161        }
162    }
163
164    #[test]
165    fn the_tile_statements_wait_on_row_8j_and_say_the_patent_hold() {
166        use unpopped::ir::ScalarExpr;
167        let fill = Stmt::TileFill {
168            d: 0,
169            value: ScalarExpr::ConstInt(1, unpopped_vocab::ElementKind::U32),
170        };
171        assert!(
172            matches!(coverage(&fill), Coverage::Row(why) if why.contains("row 8j")),
173            "{fill:?}"
174        );
175        let n = not_lowered_note(&fill).expect("a note");
176        assert!(
177            n.contains("US12405770B2") && n.contains("no transpose option"),
178            "{n}"
179        );
180    }
181
182    #[test]
183    fn a_lowered_statement_has_no_note_and_the_others_say_why() {
184        assert_eq!(not_lowered_note(&Stmt::Return), None);
185        let n = not_lowered_note(&Stmt::GridDepWait).expect("a note");
186        assert!(
187            n.contains("NVIDIA-specific") && n.contains("dependent launch"),
188            "{n}"
189        );
190        let p = not_lowered_note(&Stmt::AsyncCommit).expect("a note");
191        assert!(p.contains("board 434 C"), "{p}");
192    }
193}
194
195#[cfg(test)]
196mod collective_coverage_tests {
197    use super::*;
198    use unpopped::exec::Scope;
199    use unpopped::ir::{ReduceOp, ScalarExpr};
200    use unpopped::kernel::{CollectiveKind, ShuffleMode, VoteKind};
201
202    /// Every `CollectiveKind` shape the type has, over every operand an enum carries, so a `(kind, scope)` pair that
203    /// `collective_is_ruled` could admit or refuse is in the table.
204    fn every_kind() -> Vec<CollectiveKind> {
205        let ops = [
206            ReduceOp::Sum,
207            ReduceOp::Mean,
208            ReduceOp::Max,
209            ReduceOp::Min,
210            ReduceOp::Prod,
211            ReduceOp::And,
212            ReduceOp::Or,
213            ReduceOp::Xor,
214        ];
215        let mut kinds = Vec::new();
216        for mode in [
217            ShuffleMode::Idx,
218            ShuffleMode::Up,
219            ShuffleMode::Down,
220            ShuffleMode::Xor,
221        ] {
222            kinds.push(CollectiveKind::Shuffle {
223                mode,
224                operand: ScalarExpr::ConstInt(1, unpopped_vocab::ElementKind::U32),
225            });
226        }
227        for v in [VoteKind::All, VoteKind::Any, VoteKind::Ballot] {
228            kinds.push(CollectiveKind::Vote(v));
229        }
230        kinds.push(CollectiveKind::MatchAny);
231        for op in ops {
232            kinds.push(CollectiveKind::Reduce(op));
233            for exclusive in [false, true] {
234                kinds.push(CollectiveKind::Scan { op, exclusive });
235            }
236        }
237        kinds.push(CollectiveKind::Broadcast {
238            lane: ScalarExpr::ConstInt(3, unpopped_vocab::ElementKind::U32),
239        });
240        kinds.push(CollectiveKind::ReduceWith { combine: 0 });
241        kinds.push(CollectiveKind::ScanWith { combine: 0 });
242        kinds
243    }
244
245    const SCOPES: [Scope; 7] = [
246        Scope::Thread,
247        Scope::Subgroup,
248        Scope::Warpgroup,
249        Scope::Block,
250        Scope::Cluster,
251        Scope::Device,
252        Scope::System,
253    ];
254
255    fn collective(kind: &CollectiveKind, scope: Scope) -> Stmt {
256        Stmt::Collective {
257            kind: kind.clone(),
258            value: ScalarExpr::ConstInt(0, unpopped_vocab::ElementKind::U32),
259            result: 0,
260            scope,
261        }
262    }
263
264    /// The two cannot drift: for every `(kind, scope)` pair an emitter that lifts the ruled subgroup collectives reports
265    /// exactly what `collective_is_ruled` admits as lowered and everything else as `Patent`; an emitter that does not lift
266    /// reports `Patent` for all of them (so `coverage` and `coverage_in(false, ..)` agree).
267    #[test]
268    fn coverage_in_follows_collective_is_ruled_for_every_kind_and_scope() {
269        let kinds = every_kind();
270        let mut ruled = 0;
271        for kind in &kinds {
272            for scope in SCOPES {
273                let stmt = collective(kind, scope);
274                let want = if collective_is_ruled(kind, scope) {
275                    ruled += 1;
276                    Coverage::Lowered
277                } else {
278                    Coverage::Patent
279                };
280                assert_eq!(
281                    coverage_in(true, &stmt),
282                    want,
283                    "{kind:?} at {scope:?}, lifting"
284                );
285                assert_eq!(
286                    coverage_in(false, &stmt),
287                    Coverage::Patent,
288                    "{kind:?} at {scope:?}, not lifting"
289                );
290                assert_eq!(
291                    coverage(&stmt),
292                    Coverage::Patent,
293                    "{kind:?} at {scope:?}: the dialect-agnostic answer"
294                );
295            }
296        }
297        // the control: the table holds ruled and unruled pairs, so the comparison is not over one answer. The ruled pairs are the
298        // subgroup-scope ones: 4 shuffles + 3 votes + 1 broadcast + 7 reductions (every `ReduceOp` but `Mean`) = 15 of the 245.
299        assert_eq!(
300            ruled,
301            15,
302            "ruled (kind, scope) pairs of {}",
303            kinds.len() * SCOPES.len()
304        );
305    }
306
307    /// `CollectiveTuple` is never lifted: it stays `Patent` for every emitter (a tuple state needs a combine function).
308    #[test]
309    fn a_collective_tuple_stays_patent_for_every_emitter() {
310        let stmt = Stmt::CollectiveTuple {
311            kind: CollectiveKind::ReduceWith { combine: 0 },
312            values: vec![ScalarExpr::ConstInt(0, unpopped_vocab::ElementKind::U32)],
313            results: vec![0],
314            scope: Scope::Subgroup,
315        };
316        assert_eq!(coverage_in(true, &stmt), Coverage::Patent);
317        assert_eq!(coverage_in(false, &stmt), Coverage::Patent);
318    }
319}