wasm2spirv 0.1.0

Compile your WebAssembly programs into SPIR-V shaders
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
use super::{
    block::{translate_block, BlockBuilder, BlockReader},
    module::ModuleBuilder,
    values::{integer::Integer, pointer::Pointer, Value},
    End, Operation,
};
use crate::{
    config::{execution_model_capabilities, storage_class_capabilities, ConfigBuilder},
    decorator::VariableDecorator,
    error::{Error, Result},
    r#type::Type,
    version::Version,
};
use once_cell::unsync::OnceCell;
use rspirv::spirv::{Capability, ExecutionModel, StorageClass};
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, cell::Cell, collections::VecDeque, rc::Rc};
use vector_mapp::vec::VecMap;
use wasmparser::{Export, FuncType, FunctionBody, ValType};

/// May be a pointer or an integer, but you won't know until you try to store into it.
#[derive(Debug, Clone, PartialEq)]
pub struct Schrodinger {
    pub variable: OnceCell<Rc<Pointer>>,
    pub offset: OnceCell<Rc<Pointer>>,
}

impl Schrodinger {
    fn offset_variable(&self, module: &ModuleBuilder) -> &Rc<Pointer> {
        self.offset.get_or_init(|| {
            let init = Rc::new(Integer::new_constant_usize(0, module));
            Rc::new(Pointer::new_variable_with_init(
                StorageClass::Function,
                module.isize_type(),
                init,
                None,
            ))
        })
    }

    pub fn store_integer(
        &self,
        value: Rc<Integer>,
        block: &mut BlockBuilder,
        module: &mut ModuleBuilder,
    ) -> Result<(Operation, Option<Operation>)> {
        let variable = self.variable.get_or_init(|| {
            Rc::new(Pointer::new_variable(
                StorageClass::Function,
                module.isize_type(),
                None,
            ))
        });

        let offset = if let Some(sch_offset) = self.offset.get() {
            let zero = Rc::new(Integer::new_constant_usize(0, module));
            Some(sch_offset.clone().store(zero, None, block, module)?)
        } else {
            None
        };

        let value = match &variable.pointee {
            Type::Scalar(x) if x == &module.isize_type() => {
                variable.clone().store(value, None, block, module)
            }
            Type::Pointer(storage_class, pointee) => {
                let value = value.to_pointer(*storage_class, Type::clone(pointee), module)?;
                variable.clone().store(value, None, block, module)
            }
            _ => return Err(Error::unexpected()),
        }?;

        Ok((value, offset))
    }

    pub fn store_pointer(
        &self,
        value: Rc<Pointer>,
        block: &mut BlockBuilder,
        module: &mut ModuleBuilder,
    ) -> Result<(Operation, Option<Operation>)> {
        let (value, offset) = value.split_ptr_offset(module)?;

        let variable = self.variable.get_or_init(|| {
            Rc::new(Pointer::new_variable(
                StorageClass::Function,
                Type::pointer(value.storage_class, value.pointee.clone()),
                None,
            ))
        });

        let offset = if let Some(offset) = offset {
            Some(
                self.offset_variable(module)
                    .clone()
                    .store(offset, None, block, module)?,
            )
        } else if let Some(sch_offset) = self.offset.get() {
            let zero = Rc::new(Integer::new_constant_usize(0, module));
            Some(sch_offset.clone().store(zero, None, block, module)?)
        } else {
            None
        };

        let value = match &variable.pointee {
            Type::Scalar(x) if x == &module.isize_type() => {
                let value = value.to_integer(module)?;
                variable.clone().store(value, None, block, module)
            }
            Type::Pointer(sch_storage_class, pointee)
                if sch_storage_class == &value.storage_class =>
            {
                let value = value.cast(Type::clone(pointee));
                variable.clone().store(value, None, block, module)
            }
            _ => return Err(Error::unexpected()),
        }?;

        Ok((value, offset))
    }

    pub fn load(&self, block: &mut BlockBuilder, module: &mut ModuleBuilder) -> Result<Value> {
        let variable = self
            .variable
            .get()
            .ok_or_else(|| Error::msg("Schrodinger variable is still uninitialized"))?;

        let mut value = variable.clone().load(None, block, module)?;
        if let Some(offset) = self.offset.get() {
            let offset = offset.clone().load(None, block, module)?.into_integer()?;
            value = value.i_add(offset, module)?;
        }

        return Ok(value);
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Storeable {
    Pointer {
        is_extern_pointer: bool,
        pointer: Rc<Pointer>,
    },
    Schrodinger(Rc<Schrodinger>),
}

#[derive(Debug, Clone)]
pub struct EntryPoint<'a> {
    pub execution_model: ExecutionModel,
    pub execution_mode: Option<ExecutionMode>,
    pub name: &'a str,
    pub interface: Vec<Rc<Pointer>>,
}

#[derive(Debug, Default)]
pub struct FunctionBuilder<'a> {
    pub(crate) function_id: Rc<Cell<Option<rspirv::spirv::Word>>>,
    pub entry_point: Option<EntryPoint<'a>>,
    pub parameters: Box<[Value]>,
    pub local_variables: Box<[Storeable]>,
    pub return_type: Option<Type>,
    /// Instructions who's order **must** be followed
    pub anchors: Vec<Operation>,
    pub variable_initializers: Box<[Operation]>,
    pub outside_vars: Box<[Rc<Pointer>]>,
}

impl<'a> FunctionBuilder<'a> {
    pub fn new(
        function_id: Rc<Cell<Option<rspirv::spirv::Word>>>,
        export: Option<Export<'a>>,
        config: &FunctionConfig,
        ty: &FuncType,
        body: FunctionBody<'a>,
        module: &mut ModuleBuilder,
    ) -> Result<Self> {
        if ty.results().len() >= 2 {
            return Err(Error::msg("Function can only have a single result value"));
        }

        let mut interface = Vec::new();
        let mut params = Vec::new();
        let mut locals = Vec::new();
        let mut outside_vars = Vec::new();
        let mut variable_initializers = Vec::new();
        let return_type = ty.results().get(0).cloned().map(Type::from);

        // Add function params as local variables
        for (wasm_ty, i) in ty.params().iter().zip(0..) {
            let param = config
                .params
                .get(&i)
                .map_or_else(Cow::default, Cow::Borrowed);

            let ty = param.ty.clone().unwrap_or_else(|| Type::from(*wasm_ty));
            let storage_class = param.kind.storage_class();

            let variable = match param.kind {
                ParameterKind::FunctionParameter => {
                    let param = Value::function_parameter(ty.clone());
                    let var = Rc::new(Pointer::new_variable(storage_class, ty, Vec::new()));
                    variable_initializers.push(var.clone().store(
                        param.clone(),
                        None,
                        &mut BlockBuilder::dummy(),
                        module,
                    )?);
                    params.push(param);
                    var
                }
                ParameterKind::Input | ParameterKind::Output => {
                    Rc::new(Pointer::new_variable(storage_class, ty, Vec::new()))
                }
                ParameterKind::DescriptorSet { set, binding, .. } => {
                    Rc::new(Pointer::new_variable(
                        storage_class,
                        ty,
                        vec![
                            VariableDecorator::DesctiptorSet(set),
                            VariableDecorator::Binding(binding),
                        ],
                    ))
                }
            };

            if storage_class != StorageClass::Function {
                outside_vars.push(variable.clone());
                if module.version >= Version::V1_4
                    || matches!(storage_class, StorageClass::Input | StorageClass::Output)
                {
                    interface.push(variable.clone())
                }
            }

            locals.push(Storeable::Pointer {
                pointer: variable,
                is_extern_pointer: param.is_extern_pointer,
            });
        }

        // Create local variables
        let mut locals_reader = body.get_locals_reader()?;
        for _ in 0..locals_reader.get_count() {
            let (count, ty) = locals_reader.read()?;
            locals.reserve(count as usize);

            if matches!(ty, ValType::I32 if !module.wasm_memory64)
                || matches!(ty, ValType::I64 if module.wasm_memory64)
            {
                for _ in 0..count {
                    let storeable = Storeable::Schrodinger(Rc::new(Schrodinger {
                        variable: OnceCell::new(),
                        offset: OnceCell::new(),
                    }));

                    locals.push(storeable);
                }
            } else {
                let ty = Type::from(ty);
                for _ in 0..count {
                    let pointer = Rc::new(Pointer::new_variable(
                        StorageClass::Function,
                        ty.clone(),
                        None,
                    ));

                    locals.push(Storeable::Pointer {
                        pointer,
                        is_extern_pointer: false,
                    });
                }
            }
        }

        let entry_point = match (export, config.execution_model) {
            (Some(export), Some(execution_model)) => Some(EntryPoint {
                execution_model,
                execution_mode: config.execution_mode.clone(),
                name: export.name,
                interface, // TODO
            }),
            (None, Some(_)) => todo!(),
            _ => None,
        };

        let mut result = Self {
            anchors: Vec::new(),
            parameters: params.into_boxed_slice(),
            local_variables: locals.into_boxed_slice(),
            outside_vars: outside_vars.into_boxed_slice(),
            variable_initializers: variable_initializers.into_boxed_slice(),
            function_id,
            entry_point,
            return_type,
        };

        let reader = BlockReader::new(body.get_operators_reader()?);
        translate_block(
            reader,
            VecDeque::new(),
            End::Return(result.return_type.clone()),
            &mut result,
            module,
        )?;

        return Ok(result);
    }
}

#[must_use]
#[derive(Debug)]
pub struct FunctionConfigBuilder<'a> {
    pub(crate) inner: FunctionConfig,
    pub(crate) idx: u32,
    pub(crate) config: &'a mut ConfigBuilder,
}

impl<'a> FunctionConfigBuilder<'a> {
    pub fn param(self, idx: u32) -> ParameterBuilder<'a> {
        return ParameterBuilder {
            inner: Parameter::default(),
            function: self,
            idx,
        };
    }

    pub fn set_exec_mode(mut self, exec_mode: ExecutionMode) -> Result<Self> {
        if let Some(capability) = exec_mode.required_capability() {
            self.config.require_capability(capability)?;
        }
        self.inner.execution_mode = Some(exec_mode);
        Ok(self)
    }

    pub fn set_entry_point(mut self, exec_model: ExecutionModel) -> Result<Self> {
        let capability = match exec_model {
            ExecutionModel::Vertex | ExecutionModel::Fragment | ExecutionModel::GLCompute => {
                Capability::Shader
            }
            ExecutionModel::TessellationEvaluation | ExecutionModel::TessellationControl => {
                Capability::Tessellation
            }
            ExecutionModel::Geometry => Capability::Geometry,
            ExecutionModel::Kernel => Capability::Kernel,
            _ => todo!(),
        };

        self.config.require_capability(capability)?;
        self.inner.execution_model = Some(exec_model);
        Ok(self)
    }

    pub fn build(self) -> &'a mut ConfigBuilder {
        self.config.inner.functions.insert(self.idx, self.inner);
        self.config
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FunctionConfig {
    #[serde(default)]
    pub execution_model: Option<ExecutionModel>,
    #[serde(default)]
    pub execution_mode: Option<ExecutionMode>,
    #[serde(default)]
    pub params: VecMap<u32, Parameter>,
}

impl FunctionConfig {
    pub fn required_capabilities(&self) -> Vec<Capability> {
        let mut res = Vec::new();

        if let Some(execution_model) = self.execution_model {
            res.extend(execution_model_capabilities(execution_model));
        }

        if let Some(execution_mode) = &self.execution_mode {
            res.extend(execution_mode.required_capability());
        }

        res.extend(self.params.values().flat_map(|x| x.required_capabilities()));

        res
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionMode {
    Invocations(u32),
    PixelCenterInteger,
    OriginUpperLeft,
    OriginLowerLeft,
    LocalSize(u32, u32, u32),
    LocalSizeHint(u32, u32, u32),
}

impl ExecutionMode {
    pub fn required_capability(&self) -> Option<Capability> {
        return Some(match self {
            Self::Invocations(_) => Capability::Geometry,
            Self::PixelCenterInteger | Self::OriginUpperLeft | Self::OriginLowerLeft => {
                Capability::Shader
            }
            Self::LocalSizeHint(_, _, _) => Capability::Kernel,
            _ => return None,
        });
    }
}

#[must_use]
pub struct ParameterBuilder<'a> {
    inner: Parameter,
    idx: u32,
    function: FunctionConfigBuilder<'a>,
}

impl<'a> ParameterBuilder<'a> {
    /// This will determine wether tha pointer itself, instead of it's pointed value, will be the one pushed to,
    /// and poped from, the stack.
    pub fn set_extern_pointer(mut self, extern_pointer: bool) -> Self {
        self.inner.is_extern_pointer = extern_pointer;
        self
    }

    pub fn set_type(mut self, ty: impl Into<Type>) -> Result<Self> {
        let ty = ty.into();

        for capability in ty.required_capabilities() {
            self.function.config.require_capability(capability)?;
        }

        self.inner.ty = Some(ty);
        Ok(self)
    }

    pub fn set_kind(mut self, kind: ParameterKind) -> Result<Self> {
        for capability in kind.required_capabilities() {
            self.function.config.require_capability(capability)?;
        }

        self.inner.kind = kind;
        Ok(self)
    }

    pub fn build(mut self) -> FunctionConfigBuilder<'a> {
        self.function.inner.params.insert(self.idx, self.inner);
        self.function
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
    #[serde(rename = "type", default)]
    pub ty: Option<Type>,
    pub kind: ParameterKind,
    /// This will determine wether tha pointer itself, instead of it's pointed value, will be the one pushed to,
    /// and poped from, the stack.
    #[serde(default)]
    pub is_extern_pointer: bool,
}

impl Parameter {
    pub fn new(ty: impl Into<Option<Type>>, kind: ParameterKind, is_extern_pointer: bool) -> Self {
        return Self {
            ty: ty.into(),
            kind,
            is_extern_pointer,
        };
    }

    pub fn required_capabilities(&self) -> Vec<Capability> {
        let mut res = Vec::new();

        if let Some(ty) = &self.ty {
            res.extend(ty.required_capabilities());
        }

        res.extend(self.kind.required_capabilities());

        res
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParameterKind {
    #[default]
    FunctionParameter,
    Input,
    Output,
    DescriptorSet {
        storage_class: StorageClass,
        set: u32,
        binding: u32,
    },
}

impl ParameterKind {
    pub fn required_capabilities(&self) -> Vec<Capability> {
        match self {
            ParameterKind::FunctionParameter | ParameterKind::Input => Vec::new(),
            ParameterKind::Output => vec![Capability::Shader],
            ParameterKind::DescriptorSet { storage_class, .. } => {
                let mut res = vec![Capability::Shader];
                res.extend(storage_class_capabilities(*storage_class));
                res
            }
        }
    }

    pub fn storage_class(&self) -> StorageClass {
        match self {
            ParameterKind::FunctionParameter => StorageClass::Function,
            ParameterKind::Input => StorageClass::Input,
            ParameterKind::Output => StorageClass::Output,
            ParameterKind::DescriptorSet { storage_class, .. } => *storage_class,
        }
    }
}

impl Default for Parameter {
    fn default() -> Self {
        Self {
            ty: Default::default(),
            kind: Default::default(),
            is_extern_pointer: false,
        }
    }
}