Skip to main content

cubecl_spirv/
lookups.rs

1use std::collections::VecDeque;
2
3use cubecl_core::{
4    ir::{self, Builtin, Id, Type, VariableKind},
5    prelude::KernelDefinition,
6};
7use cubecl_opt::{ConstArray, NodeIndex, SharedMemory};
8use hashbrown::{HashMap, HashSet};
9use rspirv::{
10    dr,
11    spirv::{
12        self, BuiltIn, CooperativeMatrixLayout, CooperativeMatrixUse, Scope, StorageClass, Word,
13    },
14};
15
16use crate::{
17    MAX_VECTORIZATION, SpirvCompiler, SpirvTarget,
18    item::{Elem, Item},
19    variable::{ConstVal, Variable},
20};
21
22#[derive(Clone, Debug, Default)]
23pub struct LookupTables {
24    pub buffers: Vec<Word>,
25    pub scalar_bindings: HashMap<ir::StorageType, u32>,
26    pub info: Word,
27    pub cube_dims: Vec<Word>,
28    pub cube_size: Word,
29
30    pub const_arrays: Vec<Array>,
31    pub shared_arrays: HashMap<Id, SharedArray>,
32    pub shared: HashMap<Id, SharedVar>,
33    pub local_arrays: HashMap<Id, Array>,
34    pub matrices: HashMap<Id, Matrix>,
35    pub globals: HashMap<Builtin, Word>,
36    pub loaded_builtins: HashMap<BuiltIn, Word>,
37
38    pub used_builtins: HashMap<BuiltIn, (Word, Item)>,
39
40    pub scalars: HashMap<(Id, ir::StorageType), Word>,
41    pub array_types: HashSet<Word>,
42    pub constants: HashMap<(ConstVal, Item), Word>,
43    pub bindings: HashMap<Id, Word>,
44    pub variables: HashMap<Id, Word>,
45    pub versioned: HashMap<(Id, u16), Word>,
46    pub labels: HashMap<NodeIndex, Word>,
47    pub end_labels: HashMap<NodeIndex, Word>,
48
49    pub atomic_scopes: HashMap<Word, Scope>,
50
51    pub slices: HashMap<Id, Slice>,
52
53    // For break, continue
54    pub loops: VecDeque<Loop>,
55
56    // Explicitly decorated types, to avoid double decorating
57    pub decorated_types: HashSet<Word>,
58    pub debug_types: HashSet<Word>,
59}
60
61#[derive(Clone, Debug)]
62pub struct Slice {
63    pub ptr: Variable,
64    pub offset: Word,
65    pub end: Word,
66    pub const_len: Option<u32>,
67    pub item: Item,
68}
69
70impl From<&Slice> for Variable {
71    fn from(value: &Slice) -> Self {
72        Variable::Slice {
73            ptr: Box::new(value.ptr.clone()),
74            offset: value.offset,
75            end: value.end,
76            const_len: value.const_len,
77            item: value.item.clone(),
78        }
79    }
80}
81
82#[derive(Clone, Debug)]
83pub struct Array {
84    pub id: Word,
85    pub item: Item,
86    pub len: u32,
87    pub var: ir::Variable,
88    pub alignment: Option<u32>,
89}
90
91#[derive(Clone, Debug)]
92pub struct SharedArray {
93    pub id: Word,
94    pub item: Item,
95    pub len: u32,
96    pub align: u32,
97    pub offset: u32,
98}
99
100#[derive(Clone, Debug)]
101pub struct SharedVar {
102    pub id: Word,
103    pub item: Item,
104    pub offset: u32,
105    pub align: u32,
106}
107
108impl SharedArray {
109    pub fn end(&self) -> u32 {
110        self.offset + self.len * self.item.size()
111    }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq)]
115#[allow(missing_docs)]
116pub struct Matrix {
117    pub id: Word,
118    pub ident: CooperativeMatrixUse,
119    pub m: u32,
120    pub n: u32,
121    pub k: u32,
122    pub elem: Elem,
123    pub layout: Option<CooperativeMatrixLayout>,
124}
125
126#[derive(Clone, Debug)]
127pub struct Loop {
128    pub header: Word,
129    pub continue_target: Word,
130    pub post: Word,
131}
132
133impl<T: SpirvTarget> SpirvCompiler<T> {
134    pub fn init_state(&mut self, kernel: KernelDefinition) {
135        let mut target = self.target.clone();
136
137        self.state.buffers = kernel
138            .buffers
139            .into_iter()
140            .map(|mut binding| {
141                // This is safe when combined with the unroll transform that adjusts all indices.
142                // Must not be used alone
143                if binding.ty.vector_size() > MAX_VECTORIZATION {
144                    binding.ty = binding.ty.with_vector_size(MAX_VECTORIZATION);
145                }
146                let var = ir::Variable::new(VariableKind::GlobalInputArray(binding.id), binding.ty);
147                let name = self.name_of_var(var);
148                target.generate_binding(self, binding, name.into())
149            })
150            .collect();
151
152        if self.info.has_info() {
153            self.state.info = target.generate_info_binding(self, self.state.buffers.len() as u32);
154        }
155
156        self.state.scalar_bindings = kernel
157            .scalars
158            .into_iter()
159            .enumerate()
160            .map(|(i, arg)| (arg.ty, i as u32))
161            .collect();
162
163        let cube_dims = [kernel.cube_dim.x, kernel.cube_dim.y, kernel.cube_dim.z];
164        self.state.cube_dims = cube_dims.iter().map(|dim| self.const_u32(*dim)).collect();
165        self.state.cube_size = self.const_u32(cube_dims.iter().product());
166
167        let shared_liveness = self.shared_liveness.clone();
168        for alloc in shared_liveness.allocations.values() {
169            let smem_id = self.id();
170
171            match alloc.smem {
172                SharedMemory::Array {
173                    id,
174                    length,
175                    ty,
176                    align,
177                } => {
178                    let item = self.compile_type(ty);
179                    self.state.shared_arrays.insert(
180                        id,
181                        SharedArray {
182                            id: smem_id,
183                            item,
184                            len: length as u32,
185                            align: align as u32,
186                            offset: alloc.offset as u32,
187                        },
188                    );
189                }
190                SharedMemory::Value { id, ty, align } => {
191                    let item = self.compile_type(ty);
192                    self.state.shared.insert(
193                        id,
194                        SharedVar {
195                            id: smem_id,
196                            item,
197                            offset: alloc.offset as u32,
198                            align: align as u32,
199                        },
200                    );
201                }
202            }
203        }
204    }
205
206    fn dedup_const(&mut self, inst: &dr::Instruction) -> Option<Word> {
207        self.module_ref()
208            .types_global_values
209            .iter()
210            .find(|it| {
211                it.class == inst.class
212                    && it.result_type == inst.result_type
213                    && it.operands == inst.operands
214            })
215            .and_then(|it| it.result_id)
216    }
217
218    pub fn dedup_constant_bit32(&mut self, ty: Word, val: u32) -> Word {
219        let inst = dr::Instruction::new(
220            spirv::Op::Constant,
221            Some(ty),
222            None,
223            vec![dr::Operand::LiteralBit32(val)],
224        );
225        if let Some(id) = self.dedup_const(&inst) {
226            id
227        } else {
228            self.constant_bit32(ty, val)
229        }
230    }
231
232    pub fn dedup_constant_bit64(&mut self, ty: Word, val: u64) -> Word {
233        let inst = dr::Instruction::new(
234            spirv::Op::Constant,
235            Some(ty),
236            None,
237            vec![dr::Operand::LiteralBit64(val)],
238        );
239        if let Some(id) = self.dedup_const(&inst) {
240            id
241        } else {
242            self.constant_bit64(ty, val)
243        }
244    }
245
246    pub fn const_u32(&mut self, value: u32) -> Word {
247        let ty = Item::Scalar(Elem::Int(32, false));
248        let ty_id = ty.id(self);
249        self.dedup_constant_bit32(ty_id, value)
250    }
251
252    pub fn insert_builtin(
253        &mut self,
254        builtin: BuiltIn,
255        insert: impl FnOnce(&mut Self) -> Word,
256    ) -> Word {
257        if let Some(id) = self.state.loaded_builtins.get(&builtin) {
258            *id
259        } else {
260            let id = self.insert_in_setup(insert);
261            self.state.loaded_builtins.insert(builtin, id);
262            id
263        }
264    }
265
266    pub fn insert_global(
267        &mut self,
268        builtin: Builtin,
269        insert: impl FnOnce(&mut Self) -> Word,
270    ) -> Word {
271        if let Some(id) = self.state.globals.get(&builtin) {
272            *id
273        } else {
274            let id = self.insert_in_setup(insert);
275            self.state.globals.insert(builtin, id);
276            id
277        }
278    }
279
280    pub fn insert_in_setup(&mut self, insert: impl FnOnce(&mut Self) -> Word) -> Word {
281        let current_block = self.selected_block();
282        let setup = self.setup_block;
283        self.select_block(Some(setup)).unwrap();
284        let id = insert(self);
285        self.select_block(current_block).unwrap();
286        id
287    }
288
289    pub fn get_local(&mut self, id: Id, item: &Item, var: ir::Variable) -> Word {
290        if let Some(existing) = self.state.variables.get(&id) {
291            *existing
292        } else {
293            let ty = Item::Pointer(StorageClass::Function, Box::new(item.clone())).id(self);
294            let word = self.declare_function_variable(ty);
295            self.state.variables.insert(id, word);
296            self.debug_var_name(word, var);
297            word
298        }
299    }
300
301    pub fn get_binding(&mut self, id: Id, var: &ir::Variable) -> Word {
302        if let Some(existing) = self.state.bindings.get(&id) {
303            *existing
304        } else {
305            let word = self.id();
306            self.state.bindings.insert(id, word);
307            self.debug_var_name(word, *var);
308            word
309        }
310    }
311
312    pub fn merge_binding(&mut self, id: Id, word: Word) {
313        self.state.bindings.insert(id, word);
314    }
315
316    pub fn get_versioned(&mut self, id: (Id, u16), var: &ir::Variable) -> Word {
317        if let Some(existing) = self.state.versioned.get(&id) {
318            *existing
319        } else {
320            let word = self.id();
321            self.state.versioned.insert(id, word);
322            let mut debug_var = *var;
323            debug_var.kind = VariableKind::LocalMut { id: id.0 };
324            let name = self.name_of_var(debug_var);
325            self.debug_name(word, format!("{name}.v{}", id.1));
326            word
327        }
328    }
329
330    pub fn label(&mut self, block: NodeIndex) -> Word {
331        if let Some(existing) = self.state.labels.get(&block) {
332            *existing
333        } else {
334            let word = self.id();
335            self.debug_name(word, format!("bb{}", block.index()));
336            self.state.labels.insert(block, word);
337            word
338        }
339    }
340
341    pub fn end_label(&mut self, block: NodeIndex) -> Word {
342        if let Some(existing) = self.state.end_labels.get(&block) {
343            *existing
344        } else {
345            let word = self.label(block);
346            self.state.end_labels.insert(block, word);
347            word
348        }
349    }
350
351    pub fn global_scalar(&mut self, id: Id, ty: ir::StorageType) -> Variable {
352        if let Some(existing) = self.state.scalars.get(&(id, ty)).copied() {
353            let item = self.compile_type(ir::Type::new(ty));
354            Variable::GlobalScalar(existing, item.elem())
355        } else {
356            let ir_var = ir::Variable::new(VariableKind::GlobalScalar(id), Type::new(ty));
357            let current_block = self.selected_block();
358            let setup = self.setup_block;
359            self.select_block(Some(setup)).unwrap();
360            let field_id = self.const_u32(self.state.scalar_bindings[&ty]);
361            let offset = self.const_u32(id);
362            let item = self.compile_type(ir::Type::new(ty));
363            let elem = item.elem();
364            let ty_id = item.id(self);
365            let storage_class = T::info_storage_class(self);
366            let ptr_ty = Item::Pointer(storage_class, Box::new(item)).id(self);
367            let info = self.state.info;
368            let access = self
369                .access_chain(ptr_ty, None, info, [field_id, offset])
370                .unwrap();
371            let read_id = self.load(ty_id, None, access, None, []).unwrap();
372            let var = Variable::GlobalScalar(read_id, elem);
373            self.debug_var_name(read_id, ir_var);
374            self.select_block(current_block).unwrap();
375            self.state.scalars.insert((id, ty), read_id);
376            var
377        }
378    }
379
380    pub fn register_const_array(&mut self, arr: ConstArray) {
381        let var = ir::Variable::new(
382            VariableKind::ConstantArray {
383                id: arr.id,
384                length: arr.length,
385                unroll_factor: 1,
386            },
387            arr.item,
388        );
389        let item = self.compile_type(arr.item);
390        let array_ty = Item::Array(Box::new(item.clone()), arr.length as u32);
391        let pointer_ty = Item::Pointer(StorageClass::Function, Box::new(array_ty.clone())).id(self);
392        let array_ty = array_ty.id(self);
393        let values = arr
394            .values
395            .into_iter()
396            .map(|it| self.compile_variable(it))
397            .collect::<Vec<_>>()
398            .into_iter()
399            .map(|it| self.read_as(&it, &item))
400            .collect::<Vec<_>>();
401        let constant = self.constant_composite(array_ty, values);
402        let id = self.variable(pointer_ty, None, StorageClass::Function, Some(constant));
403        self.debug_var_name(id, var);
404        self.state.const_arrays.insert(
405            arr.id as usize,
406            Array {
407                id,
408                item,
409                len: arr.length as u32,
410                var,
411                alignment: None,
412            },
413        );
414    }
415}