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
use crate::error;
use spirv_tools_sys::opt;

pub struct Options {
    pub(crate) inner: *mut opt::OptimizerOptions,
}

impl From<super::Options> for Options {
    fn from(o: super::Options) -> Self {
        unsafe {
            let inner = opt::optimizer_options_create();

            if let Some(vopts) = o.validator_options {
                let vopts = crate::val::compiled::Options::from(vopts);

                opt::optimizer_options_run_validator(inner, true);

                // The validator options are copied, so it's fine to drop vopts
                // after this call
                opt::optimizer_options_set_validator_options(inner, vopts.inner);
            }

            if let Some(max_bound) = o.max_id_bound {
                opt::optimizer_options_set_max_id_bound(inner, max_bound);
            }

            if o.preserve_bindings {
                opt::optimizer_options_preserve_bindings(inner, true);
            }

            if o.preserve_spec_constants {
                opt::optimizer_options_preserve_spec_constants(inner, true);
            }

            Self { inner }
        }
    }
}

impl Drop for Options {
    #[inline]
    fn drop(&mut self) {
        unsafe { opt::optimizer_options_destroy(self.inner) }
    }
}

pub struct CompiledOptimizer {
    inner: *mut opt::Optimizer,
}

use super::Optimizer;

impl Optimizer for CompiledOptimizer {
    fn with_env(target: crate::TargetEnv) -> Self {
        Self {
            inner: unsafe { opt::optimizer_create(target) },
        }
    }

    fn optimize<MC: error::MessageCallback>(
        &self,
        input: impl AsRef<[u32]>,
        msg_callback: &mut MC,
        options: Option<super::Options>,
    ) -> Result<crate::binary::Binary, crate::Error> {
        unsafe {
            struct Ctx<'a> {
                cb: &'a mut dyn error::MessageCallback,
            }

            let mut ctx = Ctx { cb: msg_callback };

            let cb_ctx: *mut std::ffi::c_void = (&mut ctx as *mut Ctx<'_>).cast();

            extern "C" fn callback(
                level: spirv_tools_sys::diagnostics::MessageLevel,
                source: *const std::os::raw::c_char,
                source_pos: *const spirv_tools_sys::diagnostics::Position,
                msg: *const std::os::raw::c_char,
                ctx: *mut std::ffi::c_void,
            ) {
                unsafe {
                    let ctx: &mut Ctx<'_> = &mut *(ctx.cast::<Ctx<'_>>());

                    let msg = error::Message::from_parts(level, source, source_pos, msg);

                    ctx.cb.on_message(msg);
                }
            }

            let mut binary = std::ptr::null_mut();

            let options = options.map(Options::from);

            let options = match &options {
                Some(opts) => opts.inner,
                None => std::ptr::null(),
            };

            let input = input.as_ref();

            let res = opt::optimizer_run(
                self.inner,
                input.as_ptr(),
                input.len(),
                &mut binary,
                callback,
                cb_ctx,
                options,
            );

            match res {
                spirv_tools_sys::shared::SpirvResult::Success => {
                    if binary.is_null() {
                        return Err(error::Error {
                            inner: spirv_tools_sys::shared::SpirvResult::InternalError,
                            diagnostic: Some(crate::error::Diagnostic {
                                line: 0,
                                column: 0,
                                index: 0,
                                message: "spirv optimizer indicated success but did not return a valid binary".to_owned(),
                                is_text: false,
                            }),
                        });
                    }

                    Ok(crate::binary::Binary::External(
                        crate::binary::external::ExternalBinary::new(binary),
                    ))
                }
                other => Err(error::Error {
                    inner: other,
                    diagnostic: None,
                }),
            }
        }
    }

    /// Register a single pass with the the optimizer.
    #[inline]
    fn register_pass(&mut self, pass: super::Passes) -> &mut Self {
        unsafe { opt::optimizer_register_pass(self.inner, pass) }
        self
    }

    /// Registers passes that attempt to improve performance of generated code.
    /// This sequence of passes is subject to constant review and will change
    /// from time to time.
    #[inline]
    fn register_performance_passes(&mut self) -> &mut Self {
        unsafe { opt::optimizer_register_performance_passes(self.inner) }
        self
    }

    /// Registers passes that attempt to improve the size of generated code.
    /// This sequence of passes is subject to constant review and will change
    /// from time to time.
    #[inline]
    fn register_size_passes(&mut self) -> &mut Self {
        unsafe { opt::optimizer_register_size_passes(self.inner) }
        self
    }

    // /// Registers passes that have been prescribed for converting from Vulkan to
    // /// WebGPU. This sequence of passes is subject to constant review and will
    // /// change from time to time.
    // #[inline]
    // pub fn register_vulkan_to_webgpu_passes(&mut self) -> &mut Self {
    //     unsafe { opt::optimizer_register_vulkan_to_webgpu_passes(self.inner) }
    //     self
    // }

    // /// Registers passes that have been prescribed for converting from WebGPU to
    // /// Vulkan. This sequence of passes is subject to constant review and will
    // /// change from time to time.
    // #[inline]
    // pub fn register_webgpu_to_vulkan_passes(&mut self) -> &mut Self {
    //     unsafe { opt::optimizer_register_webgpu_to_vulkan_passes(self.inner) }
    //     self
    // }

    /// Registers passes that attempt to legalize the generated code.
    ///
    /// Note: this recipe is specially designed for legalizing SPIR-V. It should be
    /// used by compilers after translating HLSL source code literally. It should
    /// *not* be used by general workloads for performance or size improvement.
    ///
    /// This sequence of passes is subject to constant review and will change
    /// from time to time.
    #[inline]
    fn register_hlsl_legalization_passes(&mut self) -> &mut Self {
        unsafe { opt::optimizer_register_hlsl_legalization_passes(self.inner) }
        self
    }
}

impl Default for CompiledOptimizer {
    fn default() -> Self {
        Self::with_env(crate::TargetEnv::default())
    }
}

impl Drop for CompiledOptimizer {
    #[inline]
    fn drop(&mut self) {
        unsafe { opt::optimizer_destroy(self.inner) }
    }
}