Skip to main content

naga/compact/
mod.rs

1pub(crate) mod expressions;
2pub(crate) mod functions;
3mod handle_set_map;
4mod statements;
5mod types;
6
7use alloc::vec::Vec;
8
9use crate::{
10    arena::{self, HandleSet},
11    compact::functions::FunctionTracer,
12    ir,
13};
14use handle_set_map::HandleMap;
15
16#[cfg(test)]
17use alloc::{format, string::ToString};
18
19/// Configuration option for [`compact`]. See [`compact`] for details.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum KeepUnused {
22    No,
23    Yes,
24}
25
26impl From<KeepUnused> for bool {
27    fn from(keep_unused: KeepUnused) -> Self {
28        match keep_unused {
29            KeepUnused::No => false,
30            KeepUnused::Yes => true,
31        }
32    }
33}
34
35/// Remove most unused objects from `module`, which must be valid.
36///
37/// Always removes the following unused objects:
38/// - anonymous types, overrides, and constants
39/// - abstract-typed constants
40/// - expressions
41///
42/// If `keep_unused` is `Yes`, the following are never considered unused,
43/// otherwise, they will also be removed if unused:
44/// - functions
45/// - global variables
46/// - named types and overrides
47///
48/// The following are never removed:
49/// - named constants with a concrete type
50/// - special types
51/// - entry points
52/// - within an entry point or a used function:
53///     - arguments
54///     - local variables
55///     - named expressions
56///
57/// After removing items according to the rules above, all handles in the
58/// remaining objects are adjusted as necessary. When `KeepUnused` is `Yes`, the
59/// resulting module should have all the named objects (except abstract-typed
60/// constants) present in the original, and those objects should be functionally
61/// identical. When `KeepUnused` is `No`, the resulting module should have the
62/// entry points present in the original, and those entry points should be
63/// functionally identical.
64///
65/// # Panics
66///
67/// If `module` would not pass validation, this may panic.
68pub fn compact(module: &mut crate::Module, keep_unused: KeepUnused) {
69    // The trickiest part of compaction is determining what is used and what is
70    // not. Once we have computed that correctly, it's easy enough to call
71    // `retain_mut` on each arena, drop unused elements, and fix up the handles
72    // in what's left.
73    //
74    // For every compactable arena in a `Module`, whether global to the `Module`
75    // or local to a function or entry point, the `ModuleTracer` type holds a
76    // bitmap indicating which elements of that arena are used. Our task is to
77    // populate those bitmaps correctly.
78    //
79    // First, we mark everything that is considered used by definition, as
80    // described in this function's documentation.
81    //
82    // Since functions and entry points are considered used by definition, we
83    // traverse their statement trees, and mark the referents of all handles
84    // appearing in those statements as used.
85    //
86    // Once we've marked which elements of an arena are referred to directly by
87    // handles elsewhere (for example, which of a function's expressions are
88    // referred to by handles in its body statements), we can mark all the other
89    // arena elements that are used indirectly in a single pass, traversing the
90    // arena from back to front. Since Naga allows arena elements to refer only
91    // to prior elements, we know that by the time we reach an element, all
92    // other elements that could possibly refer to it have already been visited.
93    // Thus, if the present element has not been marked as used, then it is
94    // definitely unused, and compaction can remove it. Otherwise, the element
95    // is used and must be retained, so we must mark everything it refers to.
96    //
97    // The final step is to mark the global expressions and types, which must be
98    // traversed simultaneously; see `ModuleTracer::type_expression_tandem`'s
99    // documentation for details.
100    //
101    // # A definition and a rule of thumb
102    //
103    // In this module, to "trace" something is to mark everything else it refers
104    // to as used, on the assumption that the thing itself is used. For example,
105    // to trace an `Expression` is to mark its subexpressions as used, as well
106    // as any types, constants, overrides, etc. that it refers to. This is what
107    // `ExpressionTracer::trace_expression` does.
108    //
109    // Given that we we want to visit each thing only once (to keep compaction
110    // linear in the size of the module), this definition of "trace" implies
111    // that things that are not "used by definition" must be marked as used
112    // *before* we trace them.
113    //
114    // Thus, whenever you are marking something as used, it's a good idea to ask
115    // yourself how you know that thing will be traced in the future. If you're
116    // not sure, then you could be marking it too late to be noticed. The thing
117    // itself will be retained by compaction, but since it will not be traced,
118    // anything it refers to could be compacted away.
119    let mut module_tracer = ModuleTracer::new(module);
120
121    // Observe what each entry point actually uses.
122    log::trace!("tracing entry points");
123    let entry_point_maps = module
124        .entry_points
125        .iter()
126        .map(|e| {
127            log::trace!("tracing entry point {:?}", e.function.name);
128
129            if let Some(sizes) = e.workgroup_size_overrides {
130                for size in sizes.iter().filter_map(|x| *x) {
131                    module_tracer.global_expressions_used.insert(size);
132                }
133            }
134
135            if let Some(task_payload) = e.task_payload {
136                module_tracer.global_variables_used.insert(task_payload);
137            }
138            if let Some(incoming_ray_payload) = e.incoming_ray_payload {
139                module_tracer
140                    .global_variables_used
141                    .insert(incoming_ray_payload);
142            }
143            if let Some(ref mesh_info) = e.mesh_info {
144                module_tracer
145                    .global_variables_used
146                    .insert(mesh_info.output_variable);
147                module_tracer
148                    .types_used
149                    .insert(mesh_info.vertex_output_type);
150                module_tracer
151                    .types_used
152                    .insert(mesh_info.primitive_output_type);
153                if let Some(max_vertices_override) = mesh_info.max_vertices_override {
154                    module_tracer
155                        .global_expressions_used
156                        .insert(max_vertices_override);
157                }
158                if let Some(max_primitives_override) = mesh_info.max_primitives_override {
159                    module_tracer
160                        .global_expressions_used
161                        .insert(max_primitives_override);
162                }
163            }
164            if e.stage == crate::ShaderStage::Task || e.stage == crate::ShaderStage::Mesh {
165                // Mesh shaders always need a u32 type, as it is e.g. the type of some
166                // expressions. We tolerate its absence here because compaction is
167                // infallible, but the module will fail validation.
168                if let Some(u32_type) = module.types.iter().find_map(|tuple| {
169                    (tuple.1.inner == crate::TypeInner::Scalar(crate::Scalar::U32))
170                        .then_some(tuple.0)
171                }) {
172                    module_tracer.types_used.insert(u32_type);
173                }
174            }
175
176            let mut used = module_tracer.as_function(&e.function);
177            used.trace();
178            FunctionMap::from(used)
179        })
180        .collect::<Vec<_>>();
181
182    // Observe which types, constant expressions, constants, and expressions
183    // each function uses, and produce maps for each function from
184    // pre-compaction to post-compaction expression handles.
185    //
186    // The function tracing logic here works in conjunction with
187    // `FunctionTracer::trace_call`, which, when tracing a `Statement::Call`
188    // to a function not already identified as used, adds the called function
189    // to both `functions_used` and `functions_pending`.
190    //
191    // Called functions are required to appear before their callers in the
192    // functions arena (recursion is disallowed). We have already traced the
193    // entry point(s) and added any functions called directly by the entry
194    // point(s) to `functions_pending`. We proceed by repeatedly tracing the
195    // last function in `functions_pending`. By an inductive argument, any
196    // functions after the last function in `functions_pending` must be unused.
197    //
198    // When `KeepUnused` is active, we simply mark all functions as pending,
199    // and then trace all of them.
200    log::trace!("tracing functions");
201    let mut function_maps = HandleMap::with_capacity(module.functions.len());
202    if keep_unused.into() {
203        module_tracer.functions_used.add_all();
204        module_tracer.functions_pending.add_all();
205    }
206    while let Some(handle) = module_tracer.functions_pending.pop() {
207        let function = &module.functions[handle];
208        log::trace!("tracing function {function:?}");
209        let mut function_tracer = module_tracer.as_function(function);
210        function_tracer.trace();
211        function_maps.insert(handle, FunctionMap::from(function_tracer));
212    }
213
214    // We treat all special types as used by definition.
215    log::trace!("tracing special types");
216    module_tracer.trace_special_types(&module.special_types);
217
218    log::trace!("tracing global variables");
219    if keep_unused.into() {
220        module_tracer.global_variables_used.add_all();
221    }
222    for global in module_tracer.global_variables_used.iter() {
223        log::trace!("tracing global {:?}", module.global_variables[global].name);
224        module_tracer
225            .types_used
226            .insert(module.global_variables[global].ty);
227        if let Some(init) = module.global_variables[global].init {
228            module_tracer.global_expressions_used.insert(init);
229        }
230    }
231
232    // We treat all named constants as used by definition, unless they have an
233    // abstract type as we do not want those reaching the validator.
234    log::trace!("tracing named constants");
235    for (handle, constant) in module.constants.iter() {
236        if constant.name.is_none() || module.types[constant.ty].inner.is_abstract(&module.types) {
237            continue;
238        }
239
240        log::trace!("tracing constant {:?}", constant.name.as_ref().unwrap());
241        module_tracer.constants_used.insert(handle);
242        module_tracer.types_used.insert(constant.ty);
243        module_tracer.global_expressions_used.insert(constant.init);
244    }
245
246    if keep_unused.into() {
247        // Treat all named overrides as used.
248        for (handle, r#override) in module.overrides.iter() {
249            if r#override.name.is_some() && module_tracer.overrides_used.insert(handle) {
250                module_tracer.types_used.insert(r#override.ty);
251                if let Some(init) = r#override.init {
252                    module_tracer.global_expressions_used.insert(init);
253                }
254            }
255        }
256
257        // Treat all named types as used.
258        for (handle, ty) in module.types.iter() {
259            if ty.name.is_some() {
260                module_tracer.types_used.insert(handle);
261            }
262        }
263    }
264
265    module_tracer.type_expression_tandem();
266
267    // Now that we know what is used and what is never touched,
268    // produce maps from the `Handle`s that appear in `module` now to
269    // the corresponding `Handle`s that will refer to the same items
270    // in the compacted module.
271    let module_map = ModuleMap::from(module_tracer);
272
273    // Drop unused types from the type arena.
274    //
275    // `FastIndexSet`s don't have an underlying Vec<T> that we can
276    // steal, compact in place, and then rebuild the `FastIndexSet`
277    // from. So we have to rebuild the type arena from scratch.
278    log::trace!("compacting types");
279    let mut new_types = arena::UniqueArena::new();
280    for (old_handle, mut ty, span) in module.types.drain_all() {
281        if let Some(expected_new_handle) = module_map.types.try_adjust(old_handle) {
282            module_map.adjust_type(&mut ty);
283            let actual_new_handle = new_types.insert(ty, span);
284            assert_eq!(actual_new_handle, expected_new_handle);
285        }
286    }
287    module.types = new_types;
288    log::trace!("adjusting special types");
289    module_map.adjust_special_types(&mut module.special_types);
290
291    // Drop unused constant expressions, reusing existing storage.
292    log::trace!("adjusting constant expressions");
293    module.global_expressions.retain_mut(|handle, expr| {
294        if module_map.global_expressions.used(handle) {
295            module_map.adjust_expression(expr, &module_map.global_expressions);
296            true
297        } else {
298            false
299        }
300    });
301
302    // Drop unused constants in place, reusing existing storage.
303    log::trace!("adjusting constants");
304    module.constants.retain_mut(|handle, constant| {
305        if module_map.constants.used(handle) {
306            module_map.types.adjust(&mut constant.ty);
307            module_map.global_expressions.adjust(&mut constant.init);
308            true
309        } else {
310            false
311        }
312    });
313
314    // Drop unused overrides in place, reusing existing storage.
315    log::trace!("adjusting overrides");
316    module.overrides.retain_mut(|handle, r#override| {
317        if module_map.overrides.used(handle) {
318            module_map.types.adjust(&mut r#override.ty);
319            if let Some(ref mut init) = r#override.init {
320                module_map.global_expressions.adjust(init);
321            }
322            true
323        } else {
324            false
325        }
326    });
327
328    // Adjust workgroup_size_overrides
329    log::trace!("adjusting workgroup_size_overrides");
330    for e in module.entry_points.iter_mut() {
331        if let Some(sizes) = e.workgroup_size_overrides.as_mut() {
332            for size in sizes.iter_mut() {
333                if let Some(expr) = size.as_mut() {
334                    module_map.global_expressions.adjust(expr);
335                }
336            }
337        }
338    }
339
340    // Drop unused global variables, reusing existing storage.
341    // Adjust used global variables' types and initializers.
342    log::trace!("adjusting global variables");
343    module.global_variables.retain_mut(|handle, global| {
344        if module_map.globals.used(handle) {
345            log::trace!("retaining global variable {:?}", global.name);
346            module_map.types.adjust(&mut global.ty);
347            if let Some(ref mut init) = global.init {
348                module_map.global_expressions.adjust(init);
349            }
350            true
351        } else {
352            log::trace!("dropping global variable {:?}", global.name);
353            false
354        }
355    });
356
357    // Adjust doc comments
358    if let Some(ref mut doc_comments) = module.doc_comments {
359        module_map.adjust_doc_comments(doc_comments.as_mut());
360    }
361
362    // Temporary storage to help us reuse allocations of existing
363    // named expression tables.
364    let mut reused_named_expressions = crate::NamedExpressions::default();
365
366    // Drop unused functions. Compact and adjust used functions.
367    module.functions.retain_mut(|handle, function| {
368        if let Some(map) = function_maps.get(handle) {
369            log::trace!("retaining and compacting function {:?}", function.name);
370            map.compact(function, &module_map, &mut reused_named_expressions);
371            true
372        } else {
373            log::trace!("dropping function {:?}", function.name);
374            false
375        }
376    });
377
378    // Compact each entry point.
379    for (entry, map) in module.entry_points.iter_mut().zip(entry_point_maps.iter()) {
380        log::trace!("compacting entry point {:?}", entry.function.name);
381        map.compact(
382            &mut entry.function,
383            &module_map,
384            &mut reused_named_expressions,
385        );
386        if let Some(ref mut task_payload) = entry.task_payload {
387            module_map.globals.adjust(task_payload);
388        }
389        if let Some(ref mut incoming_ray_payload) = entry.incoming_ray_payload {
390            module_map.globals.adjust(incoming_ray_payload);
391        }
392        if let Some(ref mut mesh_info) = entry.mesh_info {
393            module_map.globals.adjust(&mut mesh_info.output_variable);
394            module_map.types.adjust(&mut mesh_info.vertex_output_type);
395            module_map
396                .types
397                .adjust(&mut mesh_info.primitive_output_type);
398            if let Some(ref mut max_vertices_override) = mesh_info.max_vertices_override {
399                module_map.global_expressions.adjust(max_vertices_override);
400            }
401            if let Some(ref mut max_primitives_override) = mesh_info.max_primitives_override {
402                module_map
403                    .global_expressions
404                    .adjust(max_primitives_override);
405            }
406        }
407    }
408}
409
410pub(crate) struct ModuleTracer<'module> {
411    module: &'module crate::Module,
412
413    /// The subset of functions in `functions_used` that have not yet been
414    /// traced.
415    functions_pending: HandleSet<crate::Function>,
416
417    functions_used: HandleSet<crate::Function>,
418    types_used: HandleSet<crate::Type>,
419    global_variables_used: HandleSet<crate::GlobalVariable>,
420    constants_used: HandleSet<crate::Constant>,
421    overrides_used: HandleSet<crate::Override>,
422    global_expressions_used: HandleSet<crate::Expression>,
423}
424
425impl<'module> ModuleTracer<'module> {
426    pub(crate) fn new(module: &'module crate::Module) -> Self {
427        Self {
428            module,
429            functions_pending: HandleSet::for_arena(&module.functions),
430            functions_used: HandleSet::for_arena(&module.functions),
431            types_used: HandleSet::for_arena(&module.types),
432            global_variables_used: HandleSet::for_arena(&module.global_variables),
433            constants_used: HandleSet::for_arena(&module.constants),
434            overrides_used: HandleSet::for_arena(&module.overrides),
435            global_expressions_used: HandleSet::for_arena(&module.global_expressions),
436        }
437    }
438
439    fn trace_special_types(&mut self, special_types: &crate::SpecialTypes) {
440        let crate::SpecialTypes {
441            ref ray_desc,
442            ref ray_intersection,
443            ref ray_vertex_return,
444            ref predeclared_types,
445            ref external_texture_params,
446            ref external_texture_transfer_function,
447        } = *special_types;
448
449        if let Some(ray_desc) = *ray_desc {
450            self.types_used.insert(ray_desc);
451        }
452        if let Some(ray_intersection) = *ray_intersection {
453            self.types_used.insert(ray_intersection);
454        }
455        if let Some(ray_vertex_return) = *ray_vertex_return {
456            self.types_used.insert(ray_vertex_return);
457        }
458        // The `external_texture_params` type is generated purely as a
459        // convenience to the backends. While it will never actually be used in
460        // the IR, it must be marked as used so that it survives compaction.
461        if let Some(external_texture_params) = *external_texture_params {
462            self.types_used.insert(external_texture_params);
463        }
464        if let Some(external_texture_transfer_function) = *external_texture_transfer_function {
465            self.types_used.insert(external_texture_transfer_function);
466        }
467        for (_, &handle) in predeclared_types {
468            self.types_used.insert(handle);
469        }
470    }
471
472    /// Traverse types and global expressions in tandem to determine which are used.
473    ///
474    /// Assuming that all types and global expressions used by other parts of
475    /// the module have been added to [`types_used`] and
476    /// [`global_expressions_used`], expand those sets to include all types and
477    /// global expressions reachable from those.
478    ///
479    /// [`types_used`]: ModuleTracer::types_used
480    /// [`global_expressions_used`]: ModuleTracer::global_expressions_used
481    fn type_expression_tandem(&mut self) {
482        // For each type T, compute the latest global expression E that T and
483        // its predecessors refer to. Given the ordering rules on types and
484        // global expressions in valid modules, we can do this with a single
485        // forward scan of the type arena. The rules further imply that T can
486        // only be referred to by expressions after E.
487        let mut max_dep = Vec::with_capacity(self.module.types.len());
488        let mut previous = None;
489        for (_handle, ty) in self.module.types.iter() {
490            previous = core::cmp::max(
491                previous,
492                match ty.inner {
493                    crate::TypeInner::Array { size, .. }
494                    | crate::TypeInner::BindingArray { size, .. } => match size {
495                        crate::ArraySize::Constant(_) | crate::ArraySize::Dynamic => None,
496                        crate::ArraySize::Pending(handle) => self.module.overrides[handle].init,
497                    },
498                    _ => None,
499                },
500            );
501            max_dep.push(previous);
502        }
503
504        // Visit types and global expressions from youngest to oldest.
505        //
506        // The outer loop visits types. Before visiting each type, the inner
507        // loop ensures that all global expressions that could possibly refer to
508        // it have been visited. And since the inner loop stop at the latest
509        // expression that the type could possibly refer to, we know that we
510        // have previously visited any types that might refer to each expression
511        // we visit.
512        //
513        // This lets us assume that any type or expression that is *not* marked
514        // as used by the time we visit it is genuinely unused, and can be
515        // ignored.
516        let mut exprs = self.module.global_expressions.iter().rev().peekable();
517
518        for ((ty_handle, ty), dep) in self.module.types.iter().zip(max_dep).rev() {
519            while let Some((expr_handle, expr)) = exprs.next_if(|&(h, _)| Some(h) > dep) {
520                if self.global_expressions_used.contains(expr_handle) {
521                    self.as_const_expression().trace_expression(expr);
522                }
523            }
524            if self.types_used.contains(ty_handle) {
525                self.as_type().trace_type(ty);
526            }
527        }
528        // Visit any remaining expressions.
529        for (expr_handle, expr) in exprs {
530            if self.global_expressions_used.contains(expr_handle) {
531                self.as_const_expression().trace_expression(expr);
532            }
533        }
534    }
535
536    const fn as_type(&mut self) -> types::TypeTracer<'_> {
537        types::TypeTracer {
538            overrides: &self.module.overrides,
539            types_used: &mut self.types_used,
540            expressions_used: &mut self.global_expressions_used,
541            overrides_used: &mut self.overrides_used,
542        }
543    }
544
545    const fn as_const_expression(&mut self) -> expressions::ExpressionTracer<'_> {
546        expressions::ExpressionTracer {
547            constants: &self.module.constants,
548            overrides: &self.module.overrides,
549            expressions: &self.module.global_expressions,
550            types_used: &mut self.types_used,
551            global_variables_used: &mut self.global_variables_used,
552            constants_used: &mut self.constants_used,
553            expressions_used: &mut self.global_expressions_used,
554            overrides_used: &mut self.overrides_used,
555            global_expressions_used: None,
556        }
557    }
558
559    pub fn as_function<'tracer>(
560        &'tracer mut self,
561        function: &'tracer crate::Function,
562    ) -> FunctionTracer<'tracer> {
563        FunctionTracer {
564            function,
565            constants: &self.module.constants,
566            overrides: &self.module.overrides,
567            functions_pending: &mut self.functions_pending,
568            functions_used: &mut self.functions_used,
569            types_used: &mut self.types_used,
570            global_variables_used: &mut self.global_variables_used,
571            constants_used: &mut self.constants_used,
572            overrides_used: &mut self.overrides_used,
573            global_expressions_used: &mut self.global_expressions_used,
574            expressions_used: HandleSet::for_arena(&function.expressions),
575        }
576    }
577}
578
579struct ModuleMap {
580    functions: HandleMap<crate::Function>,
581    types: HandleMap<crate::Type>,
582    globals: HandleMap<crate::GlobalVariable>,
583    constants: HandleMap<crate::Constant>,
584    overrides: HandleMap<crate::Override>,
585    global_expressions: HandleMap<crate::Expression>,
586}
587
588impl From<ModuleTracer<'_>> for ModuleMap {
589    fn from(used: ModuleTracer) -> Self {
590        ModuleMap {
591            functions: HandleMap::from_set(used.functions_used),
592            types: HandleMap::from_set(used.types_used),
593            globals: HandleMap::from_set(used.global_variables_used),
594            constants: HandleMap::from_set(used.constants_used),
595            overrides: HandleMap::from_set(used.overrides_used),
596            global_expressions: HandleMap::from_set(used.global_expressions_used),
597        }
598    }
599}
600
601impl ModuleMap {
602    fn adjust_special_types(&self, special: &mut crate::SpecialTypes) {
603        let crate::SpecialTypes {
604            ref mut ray_desc,
605            ref mut ray_intersection,
606            ref mut ray_vertex_return,
607            ref mut predeclared_types,
608            ref mut external_texture_params,
609            ref mut external_texture_transfer_function,
610        } = *special;
611
612        if let Some(ref mut ray_desc) = *ray_desc {
613            self.types.adjust(ray_desc);
614        }
615        if let Some(ref mut ray_intersection) = *ray_intersection {
616            self.types.adjust(ray_intersection);
617        }
618
619        if let Some(ref mut ray_vertex_return) = *ray_vertex_return {
620            self.types.adjust(ray_vertex_return);
621        }
622
623        if let Some(ref mut external_texture_params) = *external_texture_params {
624            self.types.adjust(external_texture_params);
625        }
626
627        if let Some(ref mut external_texture_transfer_function) =
628            *external_texture_transfer_function
629        {
630            self.types.adjust(external_texture_transfer_function);
631        }
632
633        for handle in predeclared_types.values_mut() {
634            self.types.adjust(handle);
635        }
636    }
637
638    fn adjust_doc_comments(&self, doc_comments: &mut ir::DocComments) {
639        let crate::DocComments {
640            module: _,
641            types: ref mut doc_types,
642            struct_members: ref mut doc_struct_members,
643            entry_points: _,
644            functions: ref mut doc_functions,
645            constants: ref mut doc_constants,
646            global_variables: ref mut doc_globals,
647        } = *doc_comments;
648        log::trace!("adjusting doc comments for types");
649        for (mut ty, doc_comment) in core::mem::take(doc_types) {
650            if !self.types.used(ty) {
651                continue;
652            }
653            self.types.adjust(&mut ty);
654            doc_types.insert(ty, doc_comment);
655        }
656        log::trace!("adjusting doc comments for struct members");
657        for ((mut ty, index), doc_comment) in core::mem::take(doc_struct_members) {
658            if !self.types.used(ty) {
659                continue;
660            }
661            self.types.adjust(&mut ty);
662            doc_struct_members.insert((ty, index), doc_comment);
663        }
664        log::trace!("adjusting doc comments for functions");
665        for (mut handle, doc_comment) in core::mem::take(doc_functions) {
666            if !self.functions.used(handle) {
667                continue;
668            }
669            self.functions.adjust(&mut handle);
670            doc_functions.insert(handle, doc_comment);
671        }
672        log::trace!("adjusting doc comments for constants");
673        for (mut constant, doc_comment) in core::mem::take(doc_constants) {
674            if !self.constants.used(constant) {
675                continue;
676            }
677            self.constants.adjust(&mut constant);
678            doc_constants.insert(constant, doc_comment);
679        }
680        log::trace!("adjusting doc comments for globals");
681        for (mut handle, doc_comment) in core::mem::take(doc_globals) {
682            if !self.globals.used(handle) {
683                continue;
684            }
685            self.globals.adjust(&mut handle);
686            doc_globals.insert(handle, doc_comment);
687        }
688    }
689}
690
691struct FunctionMap {
692    expressions: HandleMap<crate::Expression>,
693}
694
695impl From<FunctionTracer<'_>> for FunctionMap {
696    fn from(used: FunctionTracer) -> Self {
697        FunctionMap {
698            expressions: HandleMap::from_set(used.expressions_used),
699        }
700    }
701}
702
703#[test]
704fn type_expression_interdependence() {
705    let mut module: crate::Module = Default::default();
706    let u32 = module.types.insert(
707        crate::Type {
708            name: None,
709            inner: crate::TypeInner::Scalar(crate::Scalar {
710                kind: crate::ScalarKind::Uint,
711                width: 4,
712            }),
713        },
714        crate::Span::default(),
715    );
716    let expr = module.global_expressions.append(
717        crate::Expression::Literal(crate::Literal::U32(0)),
718        crate::Span::default(),
719    );
720    let type_needs_expression = |module: &mut crate::Module, handle| {
721        let override_handle = module.overrides.append(
722            crate::Override {
723                name: None,
724                id: None,
725                ty: u32,
726                init: Some(handle),
727            },
728            crate::Span::default(),
729        );
730        module.types.insert(
731            crate::Type {
732                name: None,
733                inner: crate::TypeInner::Array {
734                    base: u32,
735                    size: crate::ArraySize::Pending(override_handle),
736                    stride: 4,
737                },
738            },
739            crate::Span::default(),
740        )
741    };
742    let expression_needs_type = |module: &mut crate::Module, handle| {
743        module
744            .global_expressions
745            .append(crate::Expression::ZeroValue(handle), crate::Span::default())
746    };
747    let expression_needs_expression = |module: &mut crate::Module, handle| {
748        module.global_expressions.append(
749            crate::Expression::Load { pointer: handle },
750            crate::Span::default(),
751        )
752    };
753    let type_needs_type = |module: &mut crate::Module, handle| {
754        module.types.insert(
755            crate::Type {
756                name: None,
757                inner: crate::TypeInner::Array {
758                    base: handle,
759                    size: crate::ArraySize::Dynamic,
760                    stride: 0,
761                },
762            },
763            crate::Span::default(),
764        )
765    };
766    let mut type_name_counter = 0;
767    let mut type_needed = |module: &mut crate::Module, handle| {
768        let name = Some(format!("type{type_name_counter}"));
769        type_name_counter += 1;
770        module.types.insert(
771            crate::Type {
772                name,
773                inner: crate::TypeInner::Array {
774                    base: handle,
775                    size: crate::ArraySize::Dynamic,
776                    stride: 0,
777                },
778            },
779            crate::Span::default(),
780        )
781    };
782    let mut override_name_counter = 0;
783    let mut expression_needed = |module: &mut crate::Module, handle| {
784        let name = Some(format!("override{override_name_counter}"));
785        override_name_counter += 1;
786        module.overrides.append(
787            crate::Override {
788                name,
789                id: None,
790                ty: u32,
791                init: Some(handle),
792            },
793            crate::Span::default(),
794        )
795    };
796    let cmp_modules = |mod0: &crate::Module, mod1: &crate::Module| {
797        (mod0.types.iter().collect::<Vec<_>>() == mod1.types.iter().collect::<Vec<_>>())
798            && (mod0.global_expressions.iter().collect::<Vec<_>>()
799                == mod1.global_expressions.iter().collect::<Vec<_>>())
800    };
801    // borrow checker breaks without the tmp variables as of Rust 1.83.0
802    let expr_end = type_needs_expression(&mut module, expr);
803    let ty_trace = type_needs_type(&mut module, expr_end);
804    let expr_init = expression_needs_type(&mut module, ty_trace);
805    expression_needed(&mut module, expr_init);
806    let ty_end = expression_needs_type(&mut module, u32);
807    let expr_trace = expression_needs_expression(&mut module, ty_end);
808    let ty_init = type_needs_expression(&mut module, expr_trace);
809    type_needed(&mut module, ty_init);
810    let untouched = module.clone();
811    compact(&mut module, KeepUnused::Yes);
812    assert!(cmp_modules(&module, &untouched));
813    let unused_expr = module.global_expressions.append(
814        crate::Expression::Literal(crate::Literal::U32(1)),
815        crate::Span::default(),
816    );
817    type_needs_expression(&mut module, unused_expr);
818    assert!(!cmp_modules(&module, &untouched));
819    compact(&mut module, KeepUnused::Yes);
820    assert!(cmp_modules(&module, &untouched));
821}
822
823#[test]
824fn array_length_override() {
825    let mut module: crate::Module = Default::default();
826    let ty_bool = module.types.insert(
827        crate::Type {
828            name: None,
829            inner: crate::TypeInner::Scalar(crate::Scalar::BOOL),
830        },
831        crate::Span::default(),
832    );
833    let ty_u32 = module.types.insert(
834        crate::Type {
835            name: None,
836            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
837        },
838        crate::Span::default(),
839    );
840    let one = module.global_expressions.append(
841        crate::Expression::Literal(crate::Literal::U32(1)),
842        crate::Span::default(),
843    );
844    let _unused_override = module.overrides.append(
845        crate::Override {
846            name: None,
847            id: Some(40),
848            ty: ty_u32,
849            init: None,
850        },
851        crate::Span::default(),
852    );
853    let o = module.overrides.append(
854        crate::Override {
855            name: None,
856            id: Some(42),
857            ty: ty_u32,
858            init: Some(one),
859        },
860        crate::Span::default(),
861    );
862    let _ty_array = module.types.insert(
863        crate::Type {
864            name: Some("array<bool, o>".to_string()),
865            inner: crate::TypeInner::Array {
866                base: ty_bool,
867                size: crate::ArraySize::Pending(o),
868                stride: 4,
869            },
870        },
871        crate::Span::default(),
872    );
873
874    let mut validator = super::valid::Validator::new(
875        super::valid::ValidationFlags::all(),
876        super::valid::Capabilities::all(),
877    );
878
879    assert!(validator.validate(&module).is_ok());
880    compact(&mut module, KeepUnused::Yes);
881    assert!(validator.validate(&module).is_ok());
882}
883
884/// Test mutual references between types and expressions via override
885/// lengths.
886#[test]
887fn array_length_override_mutual() {
888    use crate::Expression as Ex;
889    use crate::Scalar as Sc;
890    use crate::TypeInner as Ti;
891
892    let nowhere = crate::Span::default();
893    let mut module = crate::Module::default();
894    let ty_u32 = module.types.insert(
895        crate::Type {
896            name: None,
897            inner: Ti::Scalar(Sc::U32),
898        },
899        nowhere,
900    );
901
902    // This type is only referred to by the override's init
903    // expression, so if we visit that too early, this type will be
904    // removed incorrectly.
905    let ty_i32 = module.types.insert(
906        crate::Type {
907            name: None,
908            inner: Ti::Scalar(Sc::I32),
909        },
910        nowhere,
911    );
912
913    // An override that the other override's init can refer to.
914    let first_override = module.overrides.append(
915        crate::Override {
916            name: None, // so it is not considered used by definition
917            id: Some(41),
918            ty: ty_i32,
919            init: None,
920        },
921        nowhere,
922    );
923
924    // Initializer expression for the override:
925    //
926    //     (first_override + 0) as u32
927    //
928    // The `first_override` makes it an override expression; the `0`
929    // gets a use of `ty_i32` in there; and the `as` makes it match
930    // the type of `second_override` without actually making
931    // `second_override` point at `ty_i32` directly.
932    let first_override_expr = module
933        .global_expressions
934        .append(Ex::Override(first_override), nowhere);
935    let zero = module
936        .global_expressions
937        .append(Ex::ZeroValue(ty_i32), nowhere);
938    let sum = module.global_expressions.append(
939        Ex::Binary {
940            op: crate::BinaryOperator::Add,
941            left: first_override_expr,
942            right: zero,
943        },
944        nowhere,
945    );
946    let init = module.global_expressions.append(
947        Ex::As {
948            expr: sum,
949            target: crate::Scalar::U32,
950        },
951        nowhere,
952    );
953
954    // Override that serves as the array's length.
955    let second_override = module.overrides.append(
956        crate::Override {
957            name: None, // so it is not considered used by definition
958            id: Some(42),
959            ty: ty_u32,
960            init: Some(init),
961        },
962        nowhere,
963    );
964
965    // Array type that uses the overload as its length.
966    // Since this is named, it is considered used by definition.
967    let _ty_array = module.types.insert(
968        crate::Type {
969            name: Some("delicious_array".to_string()),
970            inner: Ti::Array {
971                base: ty_u32,
972                size: crate::ArraySize::Pending(second_override),
973                stride: 4,
974            },
975        },
976        nowhere,
977    );
978
979    let mut validator = super::valid::Validator::new(
980        super::valid::ValidationFlags::all(),
981        super::valid::Capabilities::all(),
982    );
983
984    assert!(validator.validate(&module).is_ok());
985    compact(&mut module, KeepUnused::Yes);
986    assert!(validator.validate(&module).is_ok());
987}
988
989#[test]
990fn array_length_expression() {
991    let mut module: crate::Module = Default::default();
992    let ty_u32 = module.types.insert(
993        crate::Type {
994            name: None,
995            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
996        },
997        crate::Span::default(),
998    );
999    let _unused_zero = module.global_expressions.append(
1000        crate::Expression::Literal(crate::Literal::U32(0)),
1001        crate::Span::default(),
1002    );
1003    let one = module.global_expressions.append(
1004        crate::Expression::Literal(crate::Literal::U32(1)),
1005        crate::Span::default(),
1006    );
1007    let override_one = module.overrides.append(
1008        crate::Override {
1009            name: None,
1010            id: None,
1011            ty: ty_u32,
1012            init: Some(one),
1013        },
1014        crate::Span::default(),
1015    );
1016    let _ty_array = module.types.insert(
1017        crate::Type {
1018            name: Some("array<u32, 1>".to_string()),
1019            inner: crate::TypeInner::Array {
1020                base: ty_u32,
1021                size: crate::ArraySize::Pending(override_one),
1022                stride: 4,
1023            },
1024        },
1025        crate::Span::default(),
1026    );
1027
1028    let mut validator = super::valid::Validator::new(
1029        super::valid::ValidationFlags::all(),
1030        super::valid::Capabilities::all(),
1031    );
1032
1033    assert!(validator.validate(&module).is_ok());
1034    compact(&mut module, KeepUnused::Yes);
1035    assert!(validator.validate(&module).is_ok());
1036}
1037
1038#[test]
1039fn global_expression_override() {
1040    let mut module: crate::Module = Default::default();
1041    let ty_u32 = module.types.insert(
1042        crate::Type {
1043            name: None,
1044            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
1045        },
1046        crate::Span::default(),
1047    );
1048
1049    // This will only be retained if we trace the initializers
1050    // of overrides referred to by `Expression::Override`
1051    // in global expressions.
1052    let expr1 = module.global_expressions.append(
1053        crate::Expression::Literal(crate::Literal::U32(1)),
1054        crate::Span::default(),
1055    );
1056
1057    // This will only be traced via a global `Expression::Override`.
1058    let o = module.overrides.append(
1059        crate::Override {
1060            name: None,
1061            id: Some(42),
1062            ty: ty_u32,
1063            init: Some(expr1),
1064        },
1065        crate::Span::default(),
1066    );
1067
1068    // This is retained by _p.
1069    let expr2 = module
1070        .global_expressions
1071        .append(crate::Expression::Override(o), crate::Span::default());
1072
1073    // Since this is named, it will be retained.
1074    let _p = module.overrides.append(
1075        crate::Override {
1076            name: Some("p".to_string()),
1077            id: None,
1078            ty: ty_u32,
1079            init: Some(expr2),
1080        },
1081        crate::Span::default(),
1082    );
1083
1084    let mut validator = super::valid::Validator::new(
1085        super::valid::ValidationFlags::all(),
1086        super::valid::Capabilities::all(),
1087    );
1088
1089    assert!(validator.validate(&module).is_ok());
1090    compact(&mut module, KeepUnused::Yes);
1091    assert!(validator.validate(&module).is_ok());
1092}
1093
1094#[test]
1095fn local_expression_override() {
1096    let mut module: crate::Module = Default::default();
1097    let ty_u32 = module.types.insert(
1098        crate::Type {
1099            name: None,
1100            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
1101        },
1102        crate::Span::default(),
1103    );
1104
1105    // This will only be retained if we trace the initializers
1106    // of overrides referred to by `Expression::Override` in a function.
1107    let expr1 = module.global_expressions.append(
1108        crate::Expression::Literal(crate::Literal::U32(1)),
1109        crate::Span::default(),
1110    );
1111
1112    // This will be removed by compaction.
1113    let _unused_override = module.overrides.append(
1114        crate::Override {
1115            name: None,
1116            id: Some(41),
1117            ty: ty_u32,
1118            init: None,
1119        },
1120        crate::Span::default(),
1121    );
1122
1123    // This will only be traced via an `Expression::Override` in a function.
1124    let o = module.overrides.append(
1125        crate::Override {
1126            name: None,
1127            id: Some(42),
1128            ty: ty_u32,
1129            init: Some(expr1),
1130        },
1131        crate::Span::default(),
1132    );
1133
1134    let mut fun = crate::Function {
1135        result: Some(crate::FunctionResult {
1136            ty: ty_u32,
1137            binding: None,
1138        }),
1139        ..crate::Function::default()
1140    };
1141
1142    // This is used by the `Return` statement.
1143    let o_expr = fun
1144        .expressions
1145        .append(crate::Expression::Override(o), crate::Span::default());
1146    fun.body.push(
1147        crate::Statement::Return {
1148            value: Some(o_expr),
1149        },
1150        crate::Span::default(),
1151    );
1152
1153    module.functions.append(fun, crate::Span::default());
1154
1155    let mut validator = super::valid::Validator::new(
1156        super::valid::ValidationFlags::all(),
1157        super::valid::Capabilities::all(),
1158    );
1159
1160    assert!(validator.validate(&module).is_ok());
1161    compact(&mut module, KeepUnused::Yes);
1162    assert!(validator.validate(&module).is_ok());
1163}
1164
1165#[test]
1166fn unnamed_constant_type() {
1167    let mut module = crate::Module::default();
1168    let nowhere = crate::Span::default();
1169
1170    // This type is used only by the unnamed constant.
1171    let ty_u32 = module.types.insert(
1172        crate::Type {
1173            name: None,
1174            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
1175        },
1176        nowhere,
1177    );
1178
1179    // This type is used by the named constant.
1180    let ty_vec_u32 = module.types.insert(
1181        crate::Type {
1182            name: None,
1183            inner: crate::TypeInner::Vector {
1184                size: crate::VectorSize::Bi,
1185                scalar: crate::Scalar::U32,
1186            },
1187        },
1188        nowhere,
1189    );
1190
1191    let unnamed_init = module
1192        .global_expressions
1193        .append(crate::Expression::Literal(crate::Literal::U32(0)), nowhere);
1194
1195    let unnamed_constant = module.constants.append(
1196        crate::Constant {
1197            name: None,
1198            ty: ty_u32,
1199            init: unnamed_init,
1200        },
1201        nowhere,
1202    );
1203
1204    // The named constant is initialized using a Splat expression, to
1205    // give the named constant a type distinct from the unnamed
1206    // constant's.
1207    let unnamed_constant_expr = module
1208        .global_expressions
1209        .append(crate::Expression::Constant(unnamed_constant), nowhere);
1210    let named_init = module.global_expressions.append(
1211        crate::Expression::Splat {
1212            size: crate::VectorSize::Bi,
1213            value: unnamed_constant_expr,
1214        },
1215        nowhere,
1216    );
1217
1218    let _named_constant = module.constants.append(
1219        crate::Constant {
1220            name: Some("totally_named".to_string()),
1221            ty: ty_vec_u32,
1222            init: named_init,
1223        },
1224        nowhere,
1225    );
1226
1227    let mut validator = super::valid::Validator::new(
1228        super::valid::ValidationFlags::all(),
1229        super::valid::Capabilities::all(),
1230    );
1231
1232    assert!(validator.validate(&module).is_ok());
1233    compact(&mut module, KeepUnused::Yes);
1234    assert!(validator.validate(&module).is_ok());
1235}
1236
1237#[test]
1238fn unnamed_override_type() {
1239    let mut module = crate::Module::default();
1240    let nowhere = crate::Span::default();
1241
1242    // This type is used only by the unnamed override.
1243    let ty_u32 = module.types.insert(
1244        crate::Type {
1245            name: None,
1246            inner: crate::TypeInner::Scalar(crate::Scalar::U32),
1247        },
1248        nowhere,
1249    );
1250
1251    // This type is used by the named override.
1252    let ty_i32 = module.types.insert(
1253        crate::Type {
1254            name: None,
1255            inner: crate::TypeInner::Scalar(crate::Scalar::I32),
1256        },
1257        nowhere,
1258    );
1259
1260    let unnamed_init = module
1261        .global_expressions
1262        .append(crate::Expression::Literal(crate::Literal::U32(0)), nowhere);
1263
1264    let unnamed_override = module.overrides.append(
1265        crate::Override {
1266            name: None,
1267            id: Some(42),
1268            ty: ty_u32,
1269            init: Some(unnamed_init),
1270        },
1271        nowhere,
1272    );
1273
1274    // The named override is initialized using a Splat expression, to
1275    // give the named override a type distinct from the unnamed
1276    // override's.
1277    let unnamed_override_expr = module
1278        .global_expressions
1279        .append(crate::Expression::Override(unnamed_override), nowhere);
1280    let named_init = module.global_expressions.append(
1281        crate::Expression::As {
1282            expr: unnamed_override_expr,
1283            target: crate::Scalar::I32,
1284        },
1285        nowhere,
1286    );
1287
1288    let _named_override = module.overrides.append(
1289        crate::Override {
1290            name: Some("totally_named".to_string()),
1291            id: None,
1292            ty: ty_i32,
1293            init: Some(named_init),
1294        },
1295        nowhere,
1296    );
1297
1298    let mut validator = super::valid::Validator::new(
1299        super::valid::ValidationFlags::all(),
1300        super::valid::Capabilities::all(),
1301    );
1302
1303    assert!(validator.validate(&module).is_ok());
1304    compact(&mut module, KeepUnused::Yes);
1305    assert!(validator.validate(&module).is_ok());
1306}