metal2vulkan 0.1.0

Translate Metal AIR / LLVM IR to Vulkan SPIR-V with a native Rust emitter
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! AIR struct-member remapping for resource-rooted access chains.

use super::*;

pub(in crate::passes) fn type_after_spirv_access_operands(
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    operands: &[Operand],
) -> Option<Word> {
    let mut cur = root_ty;
    for operand in operands {
        let def = types.get(&cur)?;
        cur = match def.class.opcode {
            Op::TypeStruct => {
                let Operand::IdRef(index) = operand else {
                    return None;
                };
                let member = const_u32(types, *index)? as usize;
                let Operand::IdRef(member_ty) = def.operands.get(member)? else {
                    return None;
                };
                *member_ty
            }
            Op::TypeArray | Op::TypeRuntimeArray | Op::TypeVector | Op::TypeMatrix => {
                let Operand::IdRef(elem_ty) = def.operands.first()? else {
                    return None;
                };
                *elem_ty
            }
            _ => return None,
        };
    }
    Some(cur)
}

/// Rewrite a struct buffer that AIR indexes as an implicit array of records. The native emitter omits
/// LLVM GEP's leading zero for record-0 member paths, so each chain is classified before mutation:
/// direct member paths become `var, 0, 0, ...old_indices`; record-indexed paths become
/// `var, 0, ...old_indices`.
pub(in crate::passes) fn rewrite_record_array_buffer(
    ctx: &mut Ctx,
    entry_idx: usize,
    pid: Word,
    var: Word,
    block_ty: Word,
    elem_ty: Word,
    defs: &HashMap<Word, Instruction>,
) -> HashSet<Word> {
    let u0 = ctx.const_uint(0);
    let mut nested_air_ordinal_roots = HashSet::new();

    let mut types = defs.clone();
    for g in &ctx.new_globals {
        if let Some(id) = g.result_id {
            types.entry(id).or_insert_with(|| g.clone());
        }
    }

    let value_types = combined_value_types(ctx, entry_idx);
    let desired_pointees = pointer_leaf_use_types(ctx, entry_idx, &value_types);
    let n_blocks = ctx.module.functions[entry_idx].blocks.len();
    for bi in 0..n_blocks {
        let n_inst = ctx.module.functions[entry_idx].blocks[bi]
            .instructions
            .len();
        for ii in 0..n_inst {
            let rewritten_pointee = {
                let (old_indices, result_type, result_id) = {
                    let inst = &ctx.module.functions[entry_idx].blocks[bi].instructions[ii];
                    if !matches!(
                        inst.class.opcode,
                        Op::AccessChain | Op::InBoundsAccessChain | Op::PtrAccessChain
                    ) || inst.operands.first() != Some(&Operand::IdRef(pid))
                    {
                        (vec![], None, None)
                    } else {
                        (
                            inst.operands[1..].to_vec(),
                            inst.result_type,
                            inst.result_id,
                        )
                    }
                };
                if old_indices.is_empty() {
                    None
                } else {
                    let (operands, pointee) = if let Some((indices, pointee)) =
                        remap_direct_air_struct_access(
                            ctx,
                            &types,
                            elem_ty,
                            &old_indices,
                            result_type,
                        ) {
                        let mut operands = vec![
                            Operand::IdRef(var),
                            Operand::IdRef(u0), // Block member 0: RuntimeArray<Struct>.
                            Operand::IdRef(u0), // record 0.
                        ];
                        operands.extend(indices);
                        (operands, Some(pointee))
                    } else if let Some((indices, pointee)) = result_id
                        .and_then(|rid| desired_pointees.get(&rid).and_then(|ty| *ty))
                        .and_then(|desired_pointee| {
                            remap_direct_air_struct_access_to_pointee(
                                ctx,
                                &types,
                                elem_ty,
                                &old_indices,
                                desired_pointee,
                            )
                        })
                    {
                        let mut operands = vec![
                            Operand::IdRef(var),
                            Operand::IdRef(u0), // Block member 0: RuntimeArray<Struct>.
                            Operand::IdRef(u0), // record 0.
                        ];
                        operands.extend(indices);
                        (operands, Some(pointee))
                    } else if let Some((indices, pointee)) = resolve_record_member_fallback(
                        ctx,
                        &types,
                        elem_ty,
                        &old_indices,
                        result_type,
                        result_id,
                        &desired_pointees,
                    ) {
                        // The plain AIR padding remap rejected these indices, but a per-level walk
                        // driven by the loaded pointee recovers a valid record-0 member path. The
                        // backend emits access-chain indices (and the declared result type) against
                        // its own view of the record struct, so at each struct level the RAW index
                        // is the faithful choice when it already type-checks toward the loaded
                        // pointee; `remap_air_struct_member_index` is needed only where the emitter's
                        // index space genuinely diverges (an explicit AIR padding member the compact
                        // struct dropped) and it misfires on natural alignment gaps. The resolver
                        // tries raw first, falls back to remap, and backtracks so a chain can mix
                        // diverged and aligned levels. Prepend the record-0 index.
                        let mut operands = vec![
                            Operand::IdRef(var),
                            Operand::IdRef(u0), // Block member 0: RuntimeArray<Struct>.
                            Operand::IdRef(u0), // record 0.
                        ];
                        operands.extend(indices);
                        (operands, Some(pointee))
                    } else {
                        let mut operands = vec![
                            Operand::IdRef(var),
                            Operand::IdRef(u0), // Block member 0: RuntimeArray<Struct>.
                        ];
                        operands.extend(old_indices);
                        let pointee =
                            type_after_spirv_access_operands(&types, block_ty, &operands[1..]);
                        (operands, pointee)
                    };
                    if let (Some(result_id), Some(result_ptr_ty), Some(pointee)) =
                        (result_id, result_type, pointee)
                    {
                        if let Some(result_pointee) = ptr_pointee(&types, result_ptr_ty) {
                            if !types_structurally_match(ctx, &types, pointee, result_pointee)
                                && types_match_with_elided_air_padding(
                                    ctx,
                                    &types,
                                    pointee,
                                    result_pointee,
                                )
                            {
                                nested_air_ordinal_roots.insert(result_id);
                            }
                        }
                    }
                    ctx.module.functions[entry_idx].blocks[bi].instructions[ii].operands = operands;
                    pointee
                }
            };
            if let Some(pointee) = rewritten_pointee {
                let ptr_ty = ctx.ty_ptr(StorageClass::StorageBuffer, pointee);
                ctx.module.functions[entry_idx].blocks[bi].instructions[ii].result_type =
                    Some(ptr_ty);
            }
        }
    }

    let mut want: Vec<Word> = vec![];
    for blk in &ctx.module.functions[entry_idx].blocks {
        for inst in &blk.instructions {
            match inst.class.opcode {
                Op::Load if inst.operands.first() == Some(&Operand::IdRef(pid)) => {
                    if let Some(t) = inst.result_type {
                        if !want.contains(&t) {
                            want.push(t);
                        }
                    }
                }
                Op::Store if inst.operands.first() == Some(&Operand::IdRef(pid)) => {
                    let Some(Operand::IdRef(object)) = inst.operands.get(1) else {
                        continue;
                    };
                    if let Some(t) = value_types.get(object).copied() {
                        if !want.contains(&t) {
                            want.push(t);
                        }
                    }
                }
                _ => {}
            }
        }
    }
    let mut direct_root_chain: HashMap<Word, Word> = HashMap::new();
    let mut injected: Vec<Instruction> = vec![];
    for t in want {
        let path = if t == elem_ty {
            vec![0, 0]
        } else {
            let Some(mut leaf) = path_to_leaf(&types, elem_ty, t) else {
                continue;
            };
            let mut path = vec![0, 0];
            path.append(&mut leaf);
            path
        };
        let ptr_ty = ctx.ty_ptr(StorageClass::StorageBuffer, t);
        let id = ctx.module.fresh_id();
        let mut ops = vec![Operand::IdRef(var)];
        for _ in &path {
            ops.push(Operand::IdRef(u0));
        }
        injected.push(Instruction::new(
            Op::AccessChain,
            Some(ptr_ty),
            Some(id),
            ops,
        ));
        direct_root_chain.insert(t, id);
    }
    for blk in &mut ctx.module.functions[entry_idx].blocks {
        for inst in &mut blk.instructions {
            match inst.class.opcode {
                Op::Load if inst.operands.first() == Some(&Operand::IdRef(pid)) => {
                    if let Some(&chain) = inst
                        .result_type
                        .as_ref()
                        .and_then(|t| direct_root_chain.get(t))
                    {
                        inst.operands[0] = Operand::IdRef(chain);
                    }
                }
                Op::Store if inst.operands.first() == Some(&Operand::IdRef(pid)) => {
                    let Some(Operand::IdRef(object)) = inst.operands.get(1) else {
                        continue;
                    };
                    if let Some(&chain) = value_types
                        .get(object)
                        .and_then(|t| direct_root_chain.get(t))
                    {
                        inst.operands[0] = Operand::IdRef(chain);
                    }
                }
                _ => {}
            }
        }
    }
    if let Some(first) = ctx.module.functions[entry_idx].blocks.first_mut() {
        for (k, chain) in injected.into_iter().enumerate() {
            first.instructions.insert(k, chain);
        }
    }

    // Unexpected pass-through use: preserve a valid pointer by replacing the param with record 0.
    let still_used = ctx.module.functions[entry_idx].blocks.iter().any(|b| {
        b.instructions.iter().any(|i| {
            i.operands
                .iter()
                .any(|o| matches!(o, Operand::IdRef(r) if *r == pid))
        })
    });
    if still_used {
        let ptr_ty = ctx.ty_ptr(StorageClass::StorageBuffer, elem_ty);
        let id = ctx.module.fresh_id();
        let ops = vec![Operand::IdRef(var), Operand::IdRef(u0), Operand::IdRef(u0)];
        if let Some(first) = ctx.module.functions[entry_idx].blocks.first_mut() {
            first.instructions.insert(
                0,
                Instruction::new(Op::AccessChain, Some(ptr_ty), Some(id), ops),
            );
        }
        replace_id_in_function(&mut ctx.module.functions[entry_idx], pid, id);
    }

    let _ = block_ty;
    nested_air_ordinal_roots
}

/// Remap descendant GEPs after a direct record-member chain has crossed from the padded AIR type to
/// the compact metadata layout. The seed is the proof that descendant struct operands are still AIR
/// ordinals; ordinary compact chains never enter this walk and therefore cannot be remapped twice.
pub(in crate::passes) fn remap_nested_air_struct_accesses(
    ctx: &mut Ctx,
    entry_idx: usize,
    seeds: &HashSet<Word>,
    defs: &HashMap<Word, Instruction>,
) {
    let types = combined_type_defs(ctx, defs);
    let mut value_types = combined_value_types(ctx, entry_idx);
    let mut roots = seeds.clone();
    let mut processed = HashSet::new();
    let mut changed = true;

    while changed {
        changed = false;
        let n_blocks = ctx.module.functions[entry_idx].blocks.len();
        for bi in 0..n_blocks {
            let n_inst = ctx.module.functions[entry_idx].blocks[bi]
                .instructions
                .len();
            for ii in 0..n_inst {
                let (op, result_id, result_type, base, operands) = {
                    let inst = &ctx.module.functions[entry_idx].blocks[bi].instructions[ii];
                    let base = inst.operands.first().and_then(|operand| match operand {
                        Operand::IdRef(base) => Some(*base),
                        _ => None,
                    });
                    (
                        inst.class.opcode,
                        inst.result_id,
                        inst.result_type,
                        base,
                        inst.operands.clone(),
                    )
                };
                let Some(result_id) = result_id.filter(|result| !processed.contains(result)) else {
                    continue;
                };
                let Some(base) = base.filter(|base| roots.contains(base)) else {
                    continue;
                };
                if !matches!(
                    op,
                    Op::AccessChain | Op::InBoundsAccessChain | Op::PtrAccessChain
                ) {
                    continue;
                }
                let Some(base_ptr_ty) = value_types.get(&base).copied() else {
                    continue;
                };
                let Some(base_pointee) = pointer_pointee_including_new(ctx, &types, base_ptr_ty)
                else {
                    continue;
                };
                let Some((remapped, pointee)) =
                    remap_air_struct_access_operands(ctx, &types, base_pointee, op, &operands)
                else {
                    continue;
                };
                let Some(old_ptr_ty) = result_type else {
                    continue;
                };
                let Some(old_pointee) = pointer_pointee_including_new(ctx, &types, old_ptr_ty)
                else {
                    continue;
                };
                if old_pointee != pointee
                    && !types_structurally_match(ctx, &types, old_pointee, pointee)
                    && !types_match_with_elided_air_padding(ctx, &types, pointee, old_pointee)
                {
                    continue;
                }
                let Some(storage) = ptr_storage(&types, old_ptr_ty) else {
                    continue;
                };
                let new_ptr_ty = ctx.ty_ptr(storage, pointee);
                let inst = &mut ctx.module.functions[entry_idx].blocks[bi].instructions[ii];
                inst.operands = remapped;
                inst.result_type = Some(new_ptr_ty);
                value_types.insert(result_id, new_ptr_ty);
                processed.insert(result_id);
                if roots.insert(result_id) {
                    changed = true;
                }
            }
        }
    }
}

pub(in crate::passes) fn remap_air_struct_access_operands(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    base_pointee: Word,
    op: Op,
    operands: &[Operand],
) -> Option<(Vec<Operand>, Word)> {
    let first_index = if op == Op::PtrAccessChain { 2 } else { 1 };
    let mut remapped = operands.to_vec();
    let mut cur = base_pointee;
    for operand_index in first_index..operands.len() {
        let def = types.get(&cur)?;
        cur = match def.class.opcode {
            Op::TypeStruct => {
                let Operand::IdRef(index) = operands[operand_index] else {
                    return None;
                };
                let member = remap_air_struct_member_index(ctx, types, cur, index)?;
                remapped[operand_index] = Operand::IdRef(ctx.const_uint(member));
                let Operand::IdRef(member_ty) = def.operands.get(member as usize)? else {
                    return None;
                };
                *member_ty
            }
            Op::TypeArray | Op::TypeRuntimeArray | Op::TypeVector | Op::TypeMatrix => {
                let Operand::IdRef(elem_ty) = def.operands.first()? else {
                    return None;
                };
                *elem_ty
            }
            _ => return None,
        };
    }
    Some((remapped, cur))
}

pub(in crate::passes) fn remap_direct_air_struct_access(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    indices: &[Operand],
    result_ptr_ty: Option<Word>,
) -> Option<(Vec<Operand>, Word)> {
    let result_pointee = ptr_pointee(types, result_ptr_ty?)?;
    remap_direct_air_struct_access_to_pointee(ctx, types, root_ty, indices, result_pointee)
}

/// Fallback for `rewrite_record_array_buffer` when the plain AIR padding remap
/// (`remap_direct_air_struct_access[_to_pointee]`) rejects a record-0 member path. Picks the target
/// pointee — the access chain's own declared result pointee first, then the leaf-use pointee — and
/// asks `resolve_record_member_path` to recover indices that reach it. Returns the recovered indices
/// paired with the target they reach. Never fires for genuine record-index chains: those have a
/// runtime leading index that no struct-level resolution can consume.
pub(in crate::passes) fn resolve_record_member_fallback(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    indices: &[Operand],
    result_ptr_ty: Option<Word>,
    result_id: Option<Word>,
    desired_pointees: &HashMap<Word, Option<Word>>,
) -> Option<(Vec<Operand>, Word)> {
    let mut targets = Vec::new();
    if let Some(rp) = result_ptr_ty.and_then(|t| ptr_pointee(types, t)) {
        targets.push(rp);
    }
    if let Some(dp) = result_id.and_then(|rid| desired_pointees.get(&rid).and_then(|ty| *ty)) {
        if !targets.contains(&dp) {
            targets.push(dp);
        }
    }
    for target in targets {
        if let Some(resolved) = resolve_record_member_path(ctx, types, root_ty, indices, target) {
            return Some((resolved, target));
        }
    }
    None
}

/// Resolve a record-0 member path to access-chain indices that walk `cur_ty` to `target`. At each
/// struct level it tries the RAW (emitter-declared) member index first and the AIR padding remap
/// (`remap_air_struct_member_index`) only as a fallback, backtracking so one chain can mix levels
/// where the emitter's index space diverges from the compact struct (an explicit AIR padding member
/// the compact struct dropped — remap needed) with levels that are naturally aligned (raw correct,
/// where the byte-offset remap otherwise misfires on alignment padding). The emitter emits both the
/// indices and the declared result type against its own view of the struct, so a raw index that
/// already type-checks toward the loaded pointee is the faithful choice. Struct member indices are
/// rebuilt as fresh constants; array/vector/matrix indices (which may be dynamic) pass through
/// unchanged.
pub(in crate::passes) fn resolve_record_member_path(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    cur_ty: Word,
    indices: &[Operand],
    target: Word,
) -> Option<Vec<Operand>> {
    let Some((idx, rest)) = indices.split_first() else {
        return (cur_ty == target || types_structurally_match(ctx, types, cur_ty, target))
            .then(Vec::new);
    };
    let def = types.get(&cur_ty)?;
    match def.class.opcode {
        Op::TypeStruct => {
            let Operand::IdRef(idx_id) = idx else {
                return None;
            };
            let member_count = def.operands.len() as u32;
            // Remap first: it is the established semantics and is correct wherever the emitter's
            // index space genuinely diverges (an explicit AIR padding member the compact struct
            // dropped). Fall back to the raw index only where remap yields a path that does not
            // type-check toward the loaded pointee — i.e. exactly the natural-alignment-gap misfire
            // this resolver exists to repair. This never overrides a remap that reaches the target.
            let remapped = remap_air_struct_member_index(ctx, types, cur_ty, *idx_id);
            let raw = const_u32(types, *idx_id).filter(|r| *r < member_count);
            let mut candidates: Vec<u32> = Vec::new();
            if let Some(remapped) = remapped {
                candidates.push(remapped);
            }
            if let Some(raw) = raw {
                if !candidates.contains(&raw) {
                    candidates.push(raw);
                }
            }
            for cand in candidates {
                let Some(Operand::IdRef(member_ty)) = def.operands.get(cand as usize) else {
                    continue;
                };
                if let Some(mut tail) =
                    resolve_record_member_path(ctx, types, *member_ty, rest, target)
                {
                    let mut resolved = vec![Operand::IdRef(ctx.const_uint(cand))];
                    resolved.append(&mut tail);
                    return Some(resolved);
                }
            }
            None
        }
        Op::TypeArray | Op::TypeRuntimeArray | Op::TypeVector | Op::TypeMatrix => {
            let Some(Operand::IdRef(elem_ty)) = def.operands.first() else {
                return None;
            };
            let elem_ty = *elem_ty;
            let mut tail = resolve_record_member_path(ctx, types, elem_ty, rest, target)?;
            let mut resolved = vec![idx.clone()];
            resolved.append(&mut tail);
            Some(resolved)
        }
        _ => None,
    }
}

// Collapsed metadata buffers can carry a source struct index that crosses several omitted padding
// members. Preserve the established offset remap first, then recover only a unique compact root.
pub(in crate::passes) fn remap_collapsed_direct_air_struct_access(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    indices: &[Operand],
    result_ptr_ty: Option<Word>,
) -> Option<(Vec<Operand>, Word)> {
    let result_pointee = ptr_pointee(types, result_ptr_ty?)?;
    if let Some(remapped) =
        remap_direct_air_struct_access_to_pointee(ctx, types, root_ty, indices, result_pointee)
    {
        return Some(remapped);
    }
    // A padded AIR index can skip more than one explicit padding field, while
    // `remap_air_struct_member_index` only models one padding slot per layout gap. If the unchanged
    // suffix reaches the declared pointee through exactly one compact root member, that member is
    // structurally determined. Keep this behind the offset-aware remapper: pointee uniqueness alone
    // cannot distinguish a compact path from a valid padded path. Require uniqueness so repeated
    // same-shaped fields remain ambiguous rather than being silently redirected.
    unique_compact_root_member_access(ctx, types, root_ty, indices, result_pointee)
}

pub(in crate::passes) fn unique_compact_root_member_access(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    indices: &[Operand],
    result_pointee: Word,
) -> Option<(Vec<Operand>, Word)> {
    let root = types.get(&root_ty)?;
    if root.class.opcode != Op::TypeStruct || indices.is_empty() {
        return None;
    }
    let suffix = &indices[1..];
    let mut candidate = None;
    for (member, operand) in root.operands.iter().enumerate() {
        let Operand::IdRef(member_ty) = operand else {
            return None;
        };
        let reached = if suffix.is_empty() {
            Some(*member_ty)
        } else {
            type_after_spirv_access_operands(types, *member_ty, suffix)
        };
        let Some(reached) = reached else {
            continue;
        };
        if reached != result_pointee
            && !types_structurally_match(ctx, types, reached, result_pointee)
        {
            continue;
        }
        if candidate.is_some() {
            return None;
        }
        candidate = Some((member as u32, reached));
    }
    let (member, reached) = candidate?;
    let mut remapped = Vec::with_capacity(indices.len());
    remapped.push(Operand::IdRef(ctx.const_uint(member)));
    remapped.extend_from_slice(suffix);
    Some((remapped, reached))
}

pub(in crate::passes) fn remap_direct_air_struct_access_to_pointee(
    ctx: &mut Ctx,
    types: &HashMap<Word, Instruction>,
    root_ty: Word,
    indices: &[Operand],
    result_pointee: Word,
) -> Option<(Vec<Operand>, Word)> {
    let mut cur = root_ty;
    let mut remapped = Vec::with_capacity(indices.len());

    for index in indices {
        let def = types.get(&cur)?;
        cur = match def.class.opcode {
            Op::TypeStruct => {
                let Operand::IdRef(index_id) = index else {
                    return None;
                };
                let member = remap_air_struct_member_index(ctx, types, cur, *index_id)?;
                let Operand::IdRef(member_ty) = def.operands.get(member as usize)? else {
                    return None;
                };
                remapped.push(Operand::IdRef(ctx.const_uint(member)));
                *member_ty
            }
            Op::TypeArray | Op::TypeRuntimeArray | Op::TypeVector | Op::TypeMatrix => {
                let Operand::IdRef(elem_ty) = def.operands.first()? else {
                    return None;
                };
                remapped.push(index.clone());
                *elem_ty
            }
            _ => return None,
        };
    }

    (cur == result_pointee
        || types_structurally_match(ctx, types, cur, result_pointee)
        || types_match_with_elided_air_padding(ctx, types, cur, result_pointee))
    .then_some((remapped, cur))
}

/// Match a compact metadata struct to the emitter's padded AIR struct. This is deliberately
/// directional: only the compact side may elide byte-array members, it must carry AIR offsets, and
/// both layouts must have the same rounded byte extent.
pub(in crate::passes) fn types_match_with_elided_air_padding(
    ctx: &Ctx,
    types: &HashMap<Word, Instruction>,
    compact: Word,
    padded: Word,
) -> bool {
    fn inner(
        ctx: &Ctx,
        types: &HashMap<Word, Instruction>,
        compact: Word,
        padded: Word,
        seen: &mut HashSet<(Word, Word)>,
    ) -> bool {
        if types_structurally_match(ctx, types, compact, padded) {
            return true;
        }
        if !seen.insert((compact, padded)) {
            return true;
        }
        let (Some(compact_def), Some(padded_def)) = (types.get(&compact), types.get(&padded))
        else {
            return false;
        };
        if compact_def.class.opcode != Op::TypeStruct
            || padded_def.class.opcode != Op::TypeStruct
            || !ctx.air_struct_offsets.contains_key(&compact)
            || ty_size_align(compact, types) != ty_size_align(padded, types)
        {
            return false;
        }

        let mut compact_index = 0usize;
        let mut padded_index = 0usize;
        while compact_index < compact_def.operands.len() && padded_index < padded_def.operands.len()
        {
            let (Operand::IdRef(compact_member), Operand::IdRef(padded_member)) = (
                &compact_def.operands[compact_index],
                &padded_def.operands[padded_index],
            ) else {
                return false;
            };
            if inner(ctx, types, *compact_member, *padded_member, seen) {
                compact_index += 1;
                padded_index += 1;
            } else if is_backend_padding_array(types, *padded_member) {
                padded_index += 1;
            } else {
                return false;
            }
        }
        compact_index == compact_def.operands.len()
            && padded_def.operands[padded_index..].iter().all(|operand| {
                matches!(operand, Operand::IdRef(member) if is_backend_padding_array(types, *member))
            })
    }

    inner(ctx, types, compact, padded, &mut HashSet::new())
}

pub(in crate::passes) fn remap_air_struct_member_index(
    ctx: &Ctx,
    types: &HashMap<Word, Instruction>,
    struct_ty: Word,
    index_id: Word,
) -> Option<u32> {
    let index = const_u32(types, index_id)?;
    let def = types.get(&struct_ty)?;
    if def.class.opcode != Op::TypeStruct {
        return None;
    }
    let member_count = def.operands.len();
    let Some(offsets) = ctx.air_struct_offsets.get(&struct_ty) else {
        return (index < member_count as u32).then_some(index);
    };
    if offsets.len() != member_count {
        return (index < member_count as u32).then_some(index);
    }

    let mut padded_index = 0u32;
    let mut cursor = 0u32;
    for (compact_index, operand) in def.operands.iter().enumerate() {
        let Operand::IdRef(member_ty) = operand else {
            return None;
        };
        let offset = offsets[compact_index];
        if offset > cursor {
            if padded_index == index {
                return None;
            }
            padded_index += 1;
        }
        if padded_index == index {
            return Some(compact_index as u32);
        }
        let (size, _align) = ty_size_align(*member_ty, types);
        cursor = offset.saturating_add(size);
        padded_index += 1;
    }
    None
}