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
use crate::error::ToContextError;
use crate::handle::Handle;
use crate::Compiler;
use crate::{error, spirv};
use spirv_cross_sys as sys;
use spirv_cross_sys::ConstantId;
use std::slice;

/// Arguments to an `OpExecutionMode`.
#[derive(Debug)]
pub enum ExecutionModeArguments {
    /// No arguments.
    ///
    /// This is also used to set execution modes for modes that don't have arguments.
    None,
    /// A single literal argument.
    Literal(u32),
    /// Arguments to `LocalSize` execution mode.
    LocalSize {
        /// Workgroup size x.
        x: u32,
        /// Workgroup size y.
        y: u32,
        /// Workgroup size z.
        z: u32,
    },
    /// Arguments to `LocalSizeId` execution mode.
    LocalSizeId {
        /// Workgroup size x ID.
        x: Handle<ConstantId>,
        /// Workgroup size y ID.
        y: Handle<ConstantId>,
        /// Workgroup size z ID.
        z: Handle<ConstantId>,
    },
}

impl ExecutionModeArguments {
    fn expand(self) -> [u32; 3] {
        match self {
            ExecutionModeArguments::None => [0, 0, 0],
            ExecutionModeArguments::Literal(a) => [a, 0, 0],
            ExecutionModeArguments::LocalSize { x, y, z } => [x, y, z],
            ExecutionModeArguments::LocalSizeId { x, y, z } => [x.id(), y.id(), z.id()],
        }
    }
}

impl<'a, T> Compiler<'a, T> {
    /// Set or unset execution modes and arguments.
    ///
    /// If arguments is `None`, unsets the execution mode. To set an execution mode that does not
    /// take arguments, pass `Some(ExecutionModeArguments::None)`.
    pub fn set_execution_mode(
        &mut self,
        mode: spirv::ExecutionMode,
        arguments: Option<ExecutionModeArguments>,
    ) {
        unsafe {
            let Some(arguments) = arguments else {
                return sys::spvc_compiler_unset_execution_mode(self.ptr.as_ptr(), mode);
            };

            let [x, y, z] = arguments.expand();

            sys::spvc_compiler_set_execution_mode_with_arguments(self.ptr.as_ptr(), mode, x, y, z);
        }
    }

    /// Query `OpExecutionMode`.
    pub fn execution_modes(&self) -> error::Result<&'a [spirv::ExecutionMode]> {
        unsafe {
            let mut size = 0;
            let mut modes = std::ptr::null();

            sys::spvc_compiler_get_execution_modes(self.ptr.as_ptr(), &mut modes, &mut size)
                .ok(self)?;

            Ok(slice::from_raw_parts(modes, size))
        }
    }

    /// Get arguments used by the execution mode.
    ///
    /// If the execution mode is unused, returns `None`.
    ///
    /// LocalSizeId query returns an ID. If LocalSizeId execution mode is not used, it returns None.
    /// LocalSize always returns a literal. If execution mode is LocalSizeId, the literal (spec constant or not) is still returned.
    pub fn execution_mode_arguments(
        &self,
        mode: spirv::ExecutionMode,
    ) -> error::Result<Option<ExecutionModeArguments>> {
        Ok(match mode {
            spirv::ExecutionMode::LocalSize => unsafe {
                let x = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    0,
                );
                let y = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    1,
                );
                let z = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    2,
                );

                if x * y * z == 0 {
                    None
                } else {
                    Some(ExecutionModeArguments::LocalSize { x, y, z })
                }
            },
            spirv::ExecutionMode::LocalSizeId => unsafe {
                let x = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    0,
                );
                let y = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    1,
                );
                let z = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    2,
                );

                if x * y * z == 0 {
                    // If one is zero, then all are zero.
                    None
                } else {
                    Some(ExecutionModeArguments::LocalSizeId {
                        x: self.create_handle(ConstantId::from(x)),
                        y: self.create_handle(ConstantId::from(y)),
                        z: self.create_handle(ConstantId::from(z)),
                    })
                }
            },
            spirv::ExecutionMode::Invocations
            | spirv::ExecutionMode::OutputVertices
            | spirv::ExecutionMode::OutputPrimitivesEXT => unsafe {
                if !self.execution_modes()?.contains(&mode) {
                    return Ok(None);
                };

                let x = sys::spvc_compiler_get_execution_mode_argument_by_index(
                    self.ptr.as_ptr(),
                    mode,
                    0,
                );
                Some(ExecutionModeArguments::Literal(x))
            },
            _ => {
                if !self.execution_modes()?.contains(&mode) {
                    return Ok(None);
                };

                Some(ExecutionModeArguments::None)
            }
        })
    }
}

#[cfg(test)]
mod test {
    use crate::error::SpirvCrossError;
    use crate::Compiler;
    use crate::{spirv, targets, Module, SpirvCrossContext};

    static BASIC_SPV: &[u8] = include_bytes!("../../basic.spv");

    #[test]
    pub fn execution_modes() -> Result<(), SpirvCrossError> {
        let spv = SpirvCrossContext::new()?;
        let words = Module::from_words(bytemuck::cast_slice(BASIC_SPV));

        let compiler: Compiler<targets::None> = spv.create_compiler(words)?;
        let resources = compiler.shader_resources()?.all_resources()?;

        // println!("{:#?}", resources);

        let ty = compiler.execution_modes()?;
        assert_eq!([spirv::ExecutionMode::OriginUpperLeft], ty);

        let args = compiler.work_group_size_specialization_constants();
        eprintln!("{:?}", args);

        // match ty.inner {
        //     TypeInner::Struct(ty) => {
        //         compiler.get_type(ty.members[0].id)?;
        //     }
        //     TypeInner::Vector { .. } => {}
        //     _ => {}
        // }
        Ok(())
    }
}