prism-q 0.32.0

Fast Rust quantum circuit simulator. OpenQASM 3.0, multiple backends, AVX2 SIMD kernels, optional CUDA and MPI, QEC tooling, Python bindings.
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! Single-qubit gate fusion and matrix precomputation pass.
//!
//! Scans the instruction stream and fuses consecutive single-qubit gates on the
//! same target qubit into a single `Gate::Fused` carrying the product matrix.
//! Gates on different qubits are transparent. They do not break a pending fusion.
//!
//! When the pass creates a new instruction stream, ALL single-qubit gates are
//! emitted as `Gate::Fused` with precomputed matrices, including isolated gates
//! that have no fusion partner. This avoids redundant `matrix_2x2()` dispatch
//! during simulation. Identity matrices (from inverse cancellation) are elided.
//!
//! # Matrix multiplication order
//!
//! Gates applied in circuit order G1, G2, G3 produce fused matrix M = G3 · G2 · G1.
//! The accumulator multiplies each new gate on the LEFT: `acc = G_new * acc`.
//!
//! # Flush triggers
//!
//! Two-qubit gates, measurements, and barriers flush pending fusions for every
//! qubit they touch before the instruction is emitted.

use std::borrow::Cow;

use num_complex::Complex64;

use super::{Circuit, GuardedRegion, Instruction, SmallVec, smallvec};
use crate::gates::{
    DiagEntry, DiagonalBatchData, Gate, IDENTITY_EPS, Multi2qData, MultiFusedData, is_diagonal_2x2,
    is_diagonal_4x4, kron_2x2, mat_mul_2x2, mat_mul_4x4,
};

use super::fusion_phase::{batch_post_phase_1q, fuse_controlled_phases};
use super::fusion_rzz::{fuse_batch_rzz, fuse_rzz};

use super::plan::{Place, Tracer};

// Under miri the fusion floors drop to the reduced parallel threshold (see
// `PARALLEL_THRESHOLD_QUBITS` in `backend/mod.rs`), so the fused kernel forms
// appear at sizes the interpreter can execute. Native values are unchanged.

/// Minimum qubit count for 1q fusion, reorder, and batching passes.
///
/// Below 10 qubits, statevectors are small enough that gate execution is
/// nanoseconds. The instruction-clone cost of fusion passes (allocating output
/// Vec, cloning non-fuseable instructions) exceeds any simulation savings.
#[cfg(not(miri))]
const MIN_QUBITS_FOR_FUSION: usize = 10;
#[cfg(miri)]
const MIN_QUBITS_FOR_FUSION: usize = 8;

/// Minimum qubit count for multi-gate tiled fusion to be profitable.
#[cfg(not(miri))]
const MIN_QUBITS_FOR_MULTI_FUSION: usize = 14;
#[cfg(miri)]
const MIN_QUBITS_FOR_MULTI_FUSION: usize = 8;

/// Minimum qubit count for diagonal-family batch passes (BatchRzz, BatchPhase,
/// DiagonalBatch) to be profitable. LUT kernel overhead needs enough state size
/// to amortize.
#[cfg(not(miri))]
const MIN_QUBITS_FOR_DIAG_BATCH: usize = 16;
#[cfg(miri)]
const MIN_QUBITS_FOR_DIAG_BATCH: usize = 8;

/// Minimum qubit count for post-phase-fusion 1q batching.
///
/// After `fuse_controlled_phases`, consecutive 1q gates (H gates in QFT) are
/// batched into MultiFused for tiled execution. At 16q (1MB, L3-resident),
/// tiling overhead exceeds savings. Profitable at 18q+ where DRAM bandwidth
/// dominates.
#[cfg(not(miri))]
const MIN_QUBITS_FOR_POST_PHASE_BATCH: usize = 18;
#[cfg(miri)]
const MIN_QUBITS_FOR_POST_PHASE_BATCH: usize = 8;

/// Minimum qubit count for two-qubit gate fusion (absorb 1q into CX/CZ) to be profitable.
///
/// The generic 4×4 kernel does ~4x the FLOPs of specialized CX/CZ + SIMD 1q kernels.
/// Benchmarked QV and random sweeps show memory-pass reduction wins from 12q.
#[cfg(not(miri))]
const MIN_QUBITS_FOR_2Q_FUSION: usize = 12;
#[cfg(miri)]
const MIN_QUBITS_FOR_2Q_FUSION: usize = 8;

/// Bench-only kill switch for `reorder_disjoint_fused2q`. Reads
/// `PRISM_NO_REORDER` once and caches the result. Toggle for A/B timing
/// comparisons without rebuilding.
#[inline]
fn reorder_2q_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("PRISM_NO_REORDER").is_none())
}

/// Minimum qubit count for multi-2q tiled fusion to be profitable.
///
/// Batches consecutive Fused2q gates into a single cache-tiled pass. Only
/// created when Fused2q gates exist, so threshold matches.
const MIN_QUBITS_FOR_MULTI_2Q_FUSION: usize = MIN_QUBITS_FOR_2Q_FUSION;

/// Minimum batch size for multi-2q fusion (single gate not worth wrapping).
const MIN_MULTI_2Q_BATCH: usize = 2;

/// Append `q` to a fused-instruction target list unless already present.
#[inline]
pub(super) fn push_unique(qubits: &mut SmallVec<[usize; 4]>, q: usize) {
    if !qubits.contains(&q) {
        qubits.push(q);
    }
}

/// Returns the qubits touched by an instruction.
fn inst_qubits(inst: &Instruction) -> &[usize] {
    match inst {
        Instruction::Gate { targets, .. } | Instruction::Conditional { targets, .. } => targets,
        Instruction::Measure { qubit, .. } | Instruction::Reset { qubit } => {
            std::slice::from_ref(qubit)
        }
        Instruction::Barrier { qubits } => qubits,
        Instruction::Region(region) => region.qubits(),
    }
}

/// Clear the pending entry for qubit `q` and its partner.
fn clear_pending(q: usize, instructions: &[Instruction], pending: &mut [Option<usize>]) {
    if let Some(pi) = pending[q] {
        if let Instruction::Gate { targets, .. } = &instructions[pi] {
            for &t in targets.iter() {
                pending[t] = None;
            }
        }
    }
}

/// True if two instructions form a cancelling pair (same self-inverse 2q gate, same targets).
///
/// For CX, target order must match exactly (CX(0,1) ≠ CX(1,0)).
/// For CZ and SWAP, either order matches (symmetric gates).
fn is_cancelling_pair(a: &Instruction, b: &Instruction) -> bool {
    match (a, b) {
        (
            Instruction::Gate {
                gate: ga,
                targets: ta,
            },
            Instruction::Gate {
                gate: gb,
                targets: tb,
            },
        ) => {
            if !ga.is_self_inverse_2q() || std::mem::discriminant(ga) != std::mem::discriminant(gb)
            {
                return false;
            }
            if ta.as_slice() == tb.as_slice() {
                return true;
            }
            // CZ and SWAP are symmetric, reversed order also cancels
            matches!(ga, Gate::Cz | Gate::Swap)
                && ta.len() == 2
                && tb.len() == 2
                && ta[0] == tb[1]
                && ta[1] == tb[0]
        }
        _ => false,
    }
}

/// Cancel pairs of self-inverse two-qubit gates (CX·CX, CZ·CZ, SWAP·SWAP).
///
/// Tracks pending self-inverse 2q gates per-qubit. When a matching gate appears
/// with no intervening instruction on the same qubits, both are removed.
/// Returns `Cow::Borrowed` when no cancellation opportunities exist.
pub(crate) fn cancel_self_inverse_pairs<'a>(
    circuit: &'a Circuit,
    t: &mut Tracer,
) -> Cow<'a, Circuit> {
    let has_candidates = circuit.instructions.iter().any(|inst| {
        matches!(
            inst,
            Instruction::Gate { gate, .. } if gate.is_self_inverse_2q()
        )
    });
    if !has_candidates {
        return Cow::Borrowed(circuit);
    }

    let n = circuit.num_qubits;
    let len = circuit.instructions.len();
    let mut cancelled = vec![false; len];
    let mut any_cancelled = false;

    let mut pending: Vec<Option<usize>> = vec![None; n];

    for i in 0..len {
        let inst = &circuit.instructions[i];
        match inst {
            Instruction::Gate { gate, targets } if gate.is_self_inverse_2q() => {
                let (q0, q1) = (targets[0], targets[1]);

                let found = pending[q0]
                    .filter(|&pi| is_cancelling_pair(&circuit.instructions[pi], inst))
                    .or_else(|| {
                        pending[q1]
                            .filter(|&pi| is_cancelling_pair(&circuit.instructions[pi], inst))
                    });

                if let Some(pi) = found {
                    cancelled[pi] = true;
                    cancelled[i] = true;
                    any_cancelled = true;
                    clear_pending(q0, &circuit.instructions, &mut pending);
                    clear_pending(q1, &circuit.instructions, &mut pending);
                } else {
                    clear_pending(q0, &circuit.instructions, &mut pending);
                    clear_pending(q1, &circuit.instructions, &mut pending);
                    pending[q0] = Some(i);
                    pending[q1] = Some(i);
                }
            }
            _ => {
                for &q in inst_qubits(inst) {
                    if q < n {
                        clear_pending(q, &circuit.instructions, &mut pending);
                    }
                }
            }
        }
    }

    if !any_cancelled {
        return Cow::Borrowed(circuit);
    }

    t.begin();
    let mut output = Vec::with_capacity(len);
    for (j, inst) in circuit.instructions.iter().enumerate() {
        if !cancelled[j] {
            output.push(inst.clone());
            t.keep(j);
        }
    }
    t.commit();

    Cow::Owned(circuit.with_instructions(output))
}

pub(super) fn is_identity(mat: &[[Complex64; 2]; 2]) -> bool {
    (mat[0][0].re - 1.0).abs() < IDENTITY_EPS
        && mat[0][0].im.abs() < IDENTITY_EPS
        && mat[0][1].norm() < IDENTITY_EPS
        && mat[1][0].norm() < IDENTITY_EPS
        && (mat[1][1].re - 1.0).abs() < IDENTITY_EPS
        && mat[1][1].im.abs() < IDENTITY_EPS
}

#[inline]
fn gate_1q_matrix(gate: &Gate) -> [[Complex64; 2]; 2] {
    match gate {
        Gate::Fused(m) => **m,
        _ => gate.matrix_2x2(),
    }
}

#[inline]
fn accumulate_1q(slot: &mut Option<[[Complex64; 2]; 2]>, mat: [[Complex64; 2]; 2]) -> bool {
    match slot {
        Some(existing) => {
            *existing = mat_mul_2x2(&mat, existing);
            false
        }
        empty => {
            *empty = Some(mat);
            true
        }
    }
}

#[inline]
fn push_fused_1q(output: &mut Vec<Instruction>, q: usize, mat: [[Complex64; 2]; 2]) {
    output.push(Instruction::Gate {
        gate: Gate::Fused(Box::new(mat)),
        targets: smallvec![q],
    });
}

struct PendingFusion {
    matrix: [[Complex64; 2]; 2],
    target: usize,
    srcs: Vec<(usize, Place)>,
}

fn flush(pending: &mut Option<PendingFusion>, output: &mut Vec<Instruction>, t: &mut Tracer) {
    if let Some(p) = pending.take() {
        if !is_identity(&p.matrix) {
            let gate = match Gate::recognize_matrix(&p.matrix) {
                // A run collapsing to a named gate drops the stored angles, so
                // a rebinding cannot rebuild it.
                Some(named) => {
                    t.bail();
                    named
                }
                None => Gate::Fused(Box::new(p.matrix)),
            };
            output.push(Instruction::Gate {
                gate,
                targets: smallvec![p.target],
            });
            t.guard_1q(&p.srcs, is_diagonal_2x2(&p.matrix));
            t.merge(&p.srcs);
        } else {
            t.bail();
        }
    }
}

/// Fuse consecutive single-qubit gates on the same target into one `Gate::Fused`.
///
/// Returns a `Cow::Borrowed` reference to the original circuit when no two
/// consecutive 1q gates share a qubit (zero overhead), or a `Cow::Owned` new
/// circuit with fused instructions. The fused circuit produces identical
/// simulation results.
pub(crate) fn fuse_single_qubit_gates<'a>(
    circuit: &'a Circuit,
    t: &mut Tracer,
) -> Cow<'a, Circuit> {
    let n = circuit.num_qubits;
    let mut pending: Vec<Option<PendingFusion>> = (0..n).map(|_| None).collect();
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut changed = false;
    t.begin();

    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate { gate, targets } if gate.num_qubits() == 1 => {
                let q = targets[0];
                let mat = gate.matrix_2x2();
                match &mut pending[q] {
                    Some(p) => {
                        p.matrix = mat_mul_2x2(&mat, &p.matrix);
                        t.note(&mut p.srcs, i, Place::Plain);
                        changed = true;
                    }
                    slot => {
                        *slot = Some(PendingFusion {
                            matrix: mat,
                            target: q,
                            srcs: t.seed(i, Place::Plain),
                        });
                    }
                }
            }
            _ => {
                for &q in inst_qubits(inst) {
                    flush(&mut pending[q], &mut output, t);
                }
                output.push(inst.clone());
                t.keep(i);
            }
        }
    }

    for slot in &mut pending {
        flush(slot, &mut output, t);
    }

    if changed {
        t.commit();
        Cow::Owned(circuit.with_instructions(output))
    } else {
        t.discard();
        Cow::Borrowed(circuit)
    }
}

/// Reorder single-qubit gates as early as possible in the instruction stream.
///
/// Moves each 1q gate backward past non-conflicting instructions (those that
/// don't touch the same qubit). Diagonal 1q gates can also pass through CX
/// (when on the control qubit) and CZ (on either qubit) via commutation.
///
/// This groups 1q gates together, maximizing batching opportunities for the
/// subsequent `fuse_multi_1q_gates()` pass.
///
/// Returns the input unchanged when no gate moves.
pub(crate) fn reorder_1q_gates<'a>(circuit: Cow<'a, Circuit>, t: &mut Tracer) -> Cow<'a, Circuit> {
    let n = circuit.num_qubits;
    // block_all[q] / block_diag[q]: index into non_1q of the last blocker
    let mut block_all: Vec<usize> = vec![usize::MAX; n];
    let mut block_diag: Vec<usize> = vec![usize::MAX; n];
    let mut last_1q_slot: Vec<usize> = vec![0; n];
    let mut non_1q: Vec<&Instruction> = Vec::new();
    let mut non_1q_idx: Vec<usize> = Vec::new();
    let mut slots: Vec<Vec<Instruction>> = vec![Vec::new()];
    let mut slot_idx: Vec<Vec<usize>> = vec![Vec::new()];
    let mut changed = false;

    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate { gate, targets } if gate.num_qubits() == 1 => {
                let q = targets[0];
                let blocker = if gate.is_diagonal_1q() {
                    block_diag[q]
                } else {
                    block_all[q]
                };
                let dep_slot = if blocker == usize::MAX {
                    0
                } else {
                    blocker + 1
                };
                let slot = dep_slot.max(last_1q_slot[q]);
                if slot < non_1q.len() {
                    changed = true;
                }
                slots[slot].push(inst.clone());
                if t.on {
                    slot_idx[slot].push(i);
                }
                last_1q_slot[q] = slot;
            }
            _ => {
                let idx = non_1q.len();
                non_1q.push(inst);
                slots.push(Vec::new());
                if t.on {
                    non_1q_idx.push(i);
                    slot_idx.push(Vec::new());
                }
                match inst {
                    Instruction::Gate { gate, targets } => match gate {
                        Gate::Cx => {
                            block_all[targets[0]] = idx;
                            // block_diag[targets[0]] unchanged, diagonal commutes on control
                            block_all[targets[1]] = idx;
                            block_diag[targets[1]] = idx;
                        }
                        Gate::Cz | Gate::Rzz(_) => {
                            block_all[targets[0]] = idx;
                            block_all[targets[1]] = idx;
                            // block_diag unchanged for both, diagonal commutes on both
                        }
                        Gate::BatchRzz(_) | Gate::DiagonalBatch(_) => {
                            for &q in targets.iter() {
                                block_all[q] = idx;
                            }
                            // block_diag unchanged, all-diagonal gate
                        }
                        _ => {
                            for &q in targets.iter() {
                                block_all[q] = idx;
                                block_diag[q] = idx;
                            }
                        }
                    },
                    _ => {
                        for &q in inst_qubits(inst) {
                            block_all[q] = idx;
                            block_diag[q] = idx;
                        }
                    }
                }
            }
        }
    }

    if !changed {
        return circuit;
    }

    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    t.begin();
    for (i, non_1q_inst) in non_1q.iter().enumerate() {
        output.append(&mut slots[i]);
        if t.on {
            for &src in &slot_idx[i] {
                t.keep(src);
            }
        }
        output.push((*non_1q_inst).clone());
        if t.on {
            t.keep(non_1q_idx[i]);
        }
    }
    output.append(&mut slots[non_1q.len()]);
    if t.on {
        for &src in &slot_idx[non_1q.len()] {
            t.keep(src);
        }
    }
    t.commit();

    Cow::Owned(circuit.with_instructions(output))
}

/// Fuse single-qubit gates on distinct qubits into `Gate::MultiFused`.
///
/// Accumulates 1q gates per-qubit across the instruction stream. When a non-1q
/// instruction is encountered, only the pending gates on the **affected qubits**
/// are flushed. Gates on unrelated qubits continue accumulating. This produces
/// fewer but larger MultiFused batches than flushing the entire run at every 2q gate.
///
/// Correctness: a 1q gate on qubit q commutes with any multi-qubit gate not
/// involving q (independent subspaces), so deferring its application is safe.
pub(crate) fn fuse_multi_1q_gates<'a>(
    circuit: Cow<'a, Circuit>,
    t: &mut Tracer,
) -> Cow<'a, Circuit> {
    if !has_multi_1q_run(&circuit) {
        return circuit;
    }

    let n = circuit.num_qubits;
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut pending: Vec<Option<[[Complex64; 2]; 2]>> = vec![None; n];
    let mut srcs: Vec<Vec<(usize, Place)>> = vec![Vec::new(); n];
    let mut pending_count = 0usize;
    t.begin();

    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate { gate, targets } if gate.num_qubits() == 1 => {
                let q = targets[0];
                let mat = gate_1q_matrix(gate);
                if accumulate_1q(&mut pending[q], mat) {
                    pending_count += 1;
                }
                t.note(&mut srcs[q], i, Place::Plain);
            }
            _ => {
                for &q in inst_qubits(inst) {
                    flush_1q_pending(
                        q,
                        &mut pending,
                        &mut pending_count,
                        &mut output,
                        &mut srcs,
                        t,
                    );
                }
                output.push(inst.clone());
                t.keep(i);
            }
        }
    }
    flush_all_pending(&mut pending, &mut pending_count, &mut output, &mut srcs, t);
    t.commit();

    Cow::Owned(circuit.with_instructions(output))
}

#[inline]
fn flush_indexed_1q(
    q: usize,
    pending: &mut [Option<[[Complex64; 2]; 2]>],
    output: &mut Vec<Instruction>,
    srcs: &mut [Vec<(usize, Place)>],
    t: &mut Tracer,
) {
    if let Some(mat) = pending[q].take() {
        push_fused_1q(output, q, mat);
        t.merge(&std::mem::take(&mut srcs[q]));
    }
}

fn flush_1q_pending(
    q: usize,
    pending: &mut [Option<[[Complex64; 2]; 2]>],
    pending_count: &mut usize,
    output: &mut Vec<Instruction>,
    srcs: &mut [Vec<(usize, Place)>],
    t: &mut Tracer,
) {
    if pending[q].is_some() {
        *pending_count -= 1;
        flush_indexed_1q(q, pending, output, srcs, t);
    }
}

fn flush_all_pending(
    pending: &mut [Option<[[Complex64; 2]; 2]>],
    pending_count: &mut usize,
    output: &mut Vec<Instruction>,
    srcs: &mut [Vec<(usize, Place)>],
    t: &mut Tracer,
) {
    if *pending_count >= 2 {
        let mut gates: Vec<(usize, [[Complex64; 2]; 2])> = Vec::with_capacity(*pending_count);
        let mut entries: Vec<Vec<(usize, Place)>> = Vec::new();
        for (q, slot) in pending.iter_mut().enumerate() {
            if let Some(mat) = slot.take() {
                gates.push((q, mat));
                if t.on {
                    entries.push(std::mem::take(&mut srcs[q]));
                }
            }
        }
        let all_diagonal = gates.iter().all(|(_, m)| is_diagonal_2x2(m));
        let targets: SmallVec<[usize; 4]> = gates.iter().map(|&(t, _)| t).collect();
        output.push(Instruction::Gate {
            gate: Gate::MultiFused(Box::new(MultiFusedData {
                gates,
                all_diagonal,
            })),
            targets,
        });
        t.batch(&entries);
    } else {
        for (q, slot) in pending.iter_mut().enumerate() {
            if let Some(mat) = slot.take() {
                push_fused_1q(output, q, mat);
                t.merge(&std::mem::take(&mut srcs[q]));
            }
        }
    }
    *pending_count = 0;
}

fn has_multi_1q_run(circuit: &Circuit) -> bool {
    let mut total_1q = 0usize;
    for inst in &circuit.instructions {
        if let Instruction::Gate { gate, .. } = inst {
            if gate.num_qubits() == 1 {
                total_1q += 1;
                if total_1q >= 2 {
                    return true;
                }
            }
        }
    }
    false
}

/// Fuse adjacent single-qubit gates into two-qubit gates.
///
/// Scans for patterns where a CX or CZ gate has pending 1q gates on its qubits.
/// The 1q gates are absorbed into the 2q gate via Kronecker product,
/// producing a `Gate::Fused2q` with a 4×4 unitary.
///
/// Only CX and CZ are targeted. SWAP and Cu have specialized SIMD kernels;
/// Cu is excluded to preserve downstream cphase batching.
///
/// Algorithm: greedy forward pass, absorbing pre-gates only. Post-gates of one
/// 2q gate become pre-gates of the next, so most HEA-style patterns are captured.
///
/// Returns the input unchanged when no absorption happens.
pub(crate) fn fuse_2q_gates<'a>(circuit: Cow<'a, Circuit>, t: &mut Tracer) -> Cow<'a, Circuit> {
    let identity_2x2 = Gate::Id.matrix_2x2();
    let n = circuit.num_qubits;
    let mut pending_1q: Vec<Option<[[Complex64; 2]; 2]>> = vec![None; n];
    let mut srcs: Vec<Vec<(usize, Place)>> = vec![Vec::new(); n];
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut changed = false;
    t.begin();

    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate { gate, targets } if gate.num_qubits() == 1 => {
                let q = targets[0];
                let mat = gate_1q_matrix(gate);
                accumulate_1q(&mut pending_1q[q], mat);
                t.note(&mut srcs[q], i, Place::Plain);
            }
            Instruction::Gate {
                gate: gate @ (Gate::Cx | Gate::Cz | Gate::Fused2q(_) | Gate::PauliRot(_)),
                targets,
            } if gate.num_qubits() == 2 => {
                let q0 = targets[0];
                let q1 = targets[1];
                let pre0 = pending_1q[q0].take();
                let pre1 = pending_1q[q1].take();

                if pre0.is_none() && pre1.is_none() {
                    output.push(inst.clone());
                    t.keep(i);
                } else {
                    let m0 = pre0.unwrap_or(identity_2x2);
                    let m1 = pre1.unwrap_or(identity_2x2);
                    let kron = kron_2x2(&m0, &m1);
                    let gate4 = gate.matrix_4x4();
                    let fused = mat_mul_4x4(&gate4, &kron);
                    output.push(Instruction::Gate {
                        gate: Gate::Fused2q(Box::new(fused)),
                        targets: smallvec![q0, q1],
                    });
                    if t.on {
                        let mut steps: Vec<(usize, Place)> = Vec::new();
                        for (src, _) in std::mem::take(&mut srcs[q0]) {
                            steps.push((src, Place::Low));
                        }
                        for (src, _) in std::mem::take(&mut srcs[q1]) {
                            steps.push((src, Place::High));
                        }
                        steps.push((i, Place::Plain));
                        t.merge(&steps);
                    }
                    changed = true;
                }
            }
            _ => {
                for &q in inst_qubits(inst) {
                    flush_indexed_1q(q, &mut pending_1q, &mut output, &mut srcs, t);
                }
                output.push(inst.clone());
                t.keep(i);
            }
        }
    }

    for q in 0..n {
        flush_indexed_1q(q, &mut pending_1q, &mut output, &mut srcs, t);
    }

    if changed {
        t.commit();
        Cow::Owned(circuit.with_instructions(output))
    } else {
        t.discard();
        circuit
    }
}

/// Cache-tier classification for 2q gates based on max target qubit.
///
/// A 2q gate on (q0, q1) fits in a tile of 2^N elements iff max(q0, q1) < N.
/// L2 tiles = 16384 = 2^14 → max qubit ≤ 13.
/// L3 tiles = 131072 = 2^17 → max qubit ≤ 16.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Tier2q {
    L2,
    L3,
    Individual,
}

fn classify_2q_tier(q0: usize, q1: usize) -> Tier2q {
    let max_q = q0.max(q1);
    if max_q <= 13 {
        Tier2q::L2
    } else if max_q <= 16 {
        Tier2q::L3
    } else {
        Tier2q::Individual
    }
}

#[inline]
fn swap_order_4x4(mat: &[[Complex64; 4]; 4]) -> [[Complex64; 4]; 4] {
    let swap = Gate::Swap.matrix_4x4();
    mat_mul_4x4(&swap, &mat_mul_4x4(mat, &swap))
}

#[inline]
fn same_unordered_pair(a0: usize, a1: usize, b0: usize, b1: usize) -> bool {
    (a0 == b0 && a1 == b1) || (a0 == b1 && a1 == b0)
}

#[inline]
fn orient_2q_matrix(
    mat: &[[Complex64; 4]; 4],
    targets: &[usize],
    q0: usize,
    q1: usize,
) -> [[Complex64; 4]; 4] {
    if targets[0] == q0 && targets[1] == q1 {
        *mat
    } else {
        swap_order_4x4(mat)
    }
}

#[inline]
fn embed_1q_matrix(mat: &[[Complex64; 2]; 2], target: usize, q0: usize) -> [[Complex64; 4]; 4] {
    let id = Gate::Id.matrix_2x2();
    if target == q0 {
        kron_2x2(mat, &id)
    } else {
        kron_2x2(&id, mat)
    }
}

struct PairRun {
    q0: usize,
    q1: usize,
    acc: [[Complex64; 4]; 4],
    fused_2q_count: usize,
    has_nondiagonal_2q: bool,
    originals: Vec<Instruction>,
    srcs: Vec<(usize, Place)>,
    src_idx: Vec<usize>,
}

impl PairRun {
    fn new(
        q0: usize,
        q1: usize,
        mat: [[Complex64; 4]; 4],
        original: Instruction,
        index: usize,
        t: &mut Tracer,
    ) -> Self {
        t.guard_diag_4x4(&[(index, Place::Plain)], is_diagonal_4x4(&mat));
        Self {
            q0,
            q1,
            acc: mat,
            fused_2q_count: 1,
            has_nondiagonal_2q: !is_diagonal_4x4(&mat),
            originals: vec![original],
            srcs: t.seed(index, Place::Plain),
            src_idx: t.seed_idx(index),
        }
    }

    #[inline]
    fn can_accept_pair(&self, q0: usize, q1: usize) -> bool {
        same_unordered_pair(self.q0, self.q1, q0, q1)
    }

    #[inline]
    fn can_accept_1q(&self, q: usize) -> bool {
        q == self.q0 || q == self.q1
    }

    fn push_2q(
        &mut self,
        mat: [[Complex64; 4]; 4],
        targets: &[usize],
        original: Instruction,
        index: usize,
        t: &mut Tracer,
    ) {
        let oriented = orient_2q_matrix(&mat, targets, self.q0, self.q1);
        let place = if targets[0] == self.q0 && targets[1] == self.q1 {
            Place::Plain
        } else {
            Place::Swapped
        };
        t.guard_diag_4x4(&[(index, place)], is_diagonal_4x4(&oriented));
        self.acc = mat_mul_4x4(&oriented, &self.acc);
        self.fused_2q_count += 1;
        self.has_nondiagonal_2q |= !is_diagonal_4x4(&oriented);
        self.originals.push(original);
        t.note(&mut self.srcs, index, place);
        t.note_idx(&mut self.src_idx, index);
    }

    fn push_1q(
        &mut self,
        mat: [[Complex64; 2]; 2],
        target: usize,
        original: Instruction,
        index: usize,
        t: &mut Tracer,
    ) {
        let embedded = embed_1q_matrix(&mat, target, self.q0);
        let place = if target == self.q0 {
            Place::Low
        } else {
            Place::High
        };
        self.acc = mat_mul_4x4(&embedded, &self.acc);
        self.originals.push(original);
        t.note(&mut self.srcs, index, place);
        t.note_idx(&mut self.src_idx, index);
    }

    fn should_fuse(&self) -> bool {
        self.fused_2q_count >= 2 && self.has_nondiagonal_2q
    }
}

fn flush_pair_run(
    run: &mut Option<PairRun>,
    output: &mut Vec<Instruction>,
    changed: &mut bool,
    t: &mut Tracer,
) {
    let Some(run) = run.take() else {
        return;
    };
    if run.should_fuse() {
        output.push(Instruction::Gate {
            gate: Gate::Fused2q(Box::new(run.acc)),
            targets: smallvec![run.q0, run.q1],
        });
        t.merge(&run.srcs);
        *changed = true;
    } else {
        output.extend(run.originals);
        for src in run.src_idx {
            t.keep(src);
        }
    }
}

/// Fuse contiguous same-pair `Fused2q` runs into one larger `Fused2q`.
///
/// This pass is deliberately narrow: it only consumes existing `Fused2q` gates
/// and single-qubit gates on the same two qubits, and only emits a fused block
/// when at least two 2q units are present. All-diagonal runs are left alone so
/// diagonal batch passes keep their cheaper kernels.
fn fuse_same_pair_2q_blocks<'a>(input: Cow<'a, Circuit>, t: &mut Tracer) -> Cow<'a, Circuit> {
    let circuit = input.as_ref();
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut run: Option<PairRun> = None;
    let mut changed = false;
    t.begin();

    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate {
                gate: Gate::Fused2q(mat),
                targets,
            } => {
                if let Some(active) = &mut run {
                    if active.can_accept_pair(targets[0], targets[1]) {
                        active.push_2q(**mat, targets, inst.clone(), i, t);
                    } else {
                        flush_pair_run(&mut run, &mut output, &mut changed, t);
                        run = Some(PairRun::new(
                            targets[0],
                            targets[1],
                            **mat,
                            inst.clone(),
                            i,
                            t,
                        ));
                    }
                } else {
                    run = Some(PairRun::new(
                        targets[0],
                        targets[1],
                        **mat,
                        inst.clone(),
                        i,
                        t,
                    ));
                }
            }
            Instruction::Gate { gate, targets } if gate.num_qubits() == 1 => {
                if let Some(active) = &mut run {
                    if active.can_accept_1q(targets[0]) {
                        let mat = gate_1q_matrix(gate);
                        active.push_1q(mat, targets[0], inst.clone(), i, t);
                    } else {
                        flush_pair_run(&mut run, &mut output, &mut changed, t);
                        output.push(inst.clone());
                        t.keep(i);
                    }
                } else {
                    output.push(inst.clone());
                    t.keep(i);
                }
            }
            _ => {
                flush_pair_run(&mut run, &mut output, &mut changed, t);
                output.push(inst.clone());
                t.keep(i);
            }
        }
    }

    flush_pair_run(&mut run, &mut output, &mut changed, t);

    if changed {
        t.commit();
        Cow::Owned(circuit.with_instructions(output))
    } else {
        t.discard();
        input
    }
}

/// Reorder consecutive `Fused2q` gates with pairwise-disjoint qubit supports
/// so that gates of the same `Tier2q` are grouped together. Disjoint-support
/// 2q gates commute, so reordering is identity-preserving.
///
/// Random pair circuits such as Quantum Volume emit `Fused2q` streams whose
/// tiers are interleaved. The downstream `fuse_multi_2q_gates` only batches
/// consecutive same-tier gates, so without this pass tier transitions break
/// the run after every one or two gates.
///
/// Returns `Cow::Borrowed` when no reorder happens.
pub(crate) fn reorder_disjoint_fused2q<'a>(
    input: Cow<'a, Circuit>,
    t: &mut Tracer,
) -> Cow<'a, Circuit> {
    let circuit = input.as_ref();
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut window: Vec<(Tier2q, Instruction, usize)> = Vec::new();
    let mut window_qubits = vec![false; circuit.num_qubits];
    let mut changed = false;
    t.begin();

    for (i, inst) in circuit.instructions.iter().enumerate() {
        if let Instruction::Gate {
            gate: Gate::Fused2q(_),
            targets,
        } = inst
        {
            let q0 = targets[0];
            let q1 = targets[1];
            if window_qubits[q0] || window_qubits[q1] {
                flush_disjoint_window(
                    &mut window,
                    &mut window_qubits,
                    &mut output,
                    &mut changed,
                    t,
                );
            }
            window_qubits[q0] = true;
            window_qubits[q1] = true;
            window.push((classify_2q_tier(q0, q1), inst.clone(), i));
        } else {
            flush_disjoint_window(
                &mut window,
                &mut window_qubits,
                &mut output,
                &mut changed,
                t,
            );
            output.push(inst.clone());
            t.keep(i);
        }
    }
    flush_disjoint_window(
        &mut window,
        &mut window_qubits,
        &mut output,
        &mut changed,
        t,
    );

    if changed {
        t.commit();
        Cow::Owned(circuit.with_instructions(output))
    } else {
        t.discard();
        input
    }
}

fn flush_disjoint_window(
    window: &mut Vec<(Tier2q, Instruction, usize)>,
    window_qubits: &mut [bool],
    output: &mut Vec<Instruction>,
    changed: &mut bool,
    t: &mut Tracer,
) {
    if window.len() >= 2 {
        let mut tier_counts = [0u32; 3];
        for (tier, _, _) in window.iter() {
            tier_counts[*tier as usize] += 1;
        }
        let any_tier_batchable = tier_counts.iter().any(|&c| c >= MIN_MULTI_2Q_BATCH as u32);
        if any_tier_batchable {
            let already_sorted = window.windows(2).all(|w| (w[0].0 as u8) <= (w[1].0 as u8));
            if !already_sorted {
                window.sort_by_key(|(tier, _, _)| *tier as u8);
                *changed = true;
            }
        }
    }
    for (_, inst, src) in window.drain(..) {
        output.push(inst);
        t.keep(src);
    }
    for q in window_qubits.iter_mut() {
        *q = false;
    }
}

/// Batch consecutive `Fused2q` gates into `Multi2q` for cache-tiled execution.
///
/// Scans for runs of consecutive `Fused2q` instructions within the same cache
/// tier (L2 or L3). Each run of ≥2 gates is replaced by a single `Multi2q`
/// gate that the statevector backend applies in a tiled pass. Individual-tier
/// gates (max qubit > 16) are left as-is.
///
/// Returns the input unchanged when no batch forms.
pub(crate) fn fuse_multi_2q_gates<'a>(
    circuit: Cow<'a, Circuit>,
    tracer: &mut Tracer,
) -> Cow<'a, Circuit> {
    let mut output: Vec<Instruction> = Vec::with_capacity(circuit.instructions.len());
    let mut pending: Vec<(usize, usize, [[Complex64; 4]; 4])> = Vec::new();
    let mut pending_src: Vec<usize> = Vec::new();
    let mut current_tier: Option<Tier2q> = None;
    let mut changed = false;

    let flush = |pending: &mut Vec<(usize, usize, [[Complex64; 4]; 4])>,
                 pending_src: &mut Vec<usize>,
                 tier: &mut Option<Tier2q>,
                 output: &mut Vec<Instruction>,
                 changed: &mut bool,
                 tracer: &mut Tracer| {
        if pending.is_empty() {
            return;
        }
        let t = tier.take().unwrap();
        if t == Tier2q::Individual || pending.len() < MIN_MULTI_2Q_BATCH {
            for (k, (q0, q1, mat)) in pending.drain(..).enumerate() {
                output.push(Instruction::Gate {
                    gate: Gate::Fused2q(Box::new(mat)),
                    targets: smallvec![q0, q1],
                });
                if tracer.on {
                    tracer.keep(pending_src[k]);
                }
            }
            pending_src.clear();
        } else {
            let mut all_qubits: SmallVec<[usize; 4]> = SmallVec::new();
            for &(q0, q1, _) in pending.iter() {
                push_unique(&mut all_qubits, q0);
                push_unique(&mut all_qubits, q1);
            }
            all_qubits.sort_unstable();
            output.push(Instruction::Gate {
                gate: Gate::Multi2q(Box::new(Multi2qData {
                    gates: std::mem::take(pending),
                })),
                targets: all_qubits,
            });
            if tracer.on {
                let entries: Vec<Vec<(usize, Place)>> = pending_src
                    .drain(..)
                    .map(|src| vec![(src, Place::Plain)])
                    .collect();
                tracer.batch(&entries);
            }
            *changed = true;
        }
    };

    tracer.begin();
    for (i, inst) in circuit.instructions.iter().enumerate() {
        match inst {
            Instruction::Gate {
                gate: Gate::Fused2q(mat),
                targets,
            } => {
                let q0 = targets[0];
                let q1 = targets[1];
                let tier = classify_2q_tier(q0, q1);

                if let Some(ct) = current_tier {
                    if ct != tier {
                        flush(
                            &mut pending,
                            &mut pending_src,
                            &mut current_tier,
                            &mut output,
                            &mut changed,
                            tracer,
                        );
                    }
                }
                if current_tier.is_none() {
                    current_tier = Some(tier);
                }
                pending.push((q0, q1, **mat));
                tracer.note_idx(&mut pending_src, i);
            }
            _ => {
                flush(
                    &mut pending,
                    &mut pending_src,
                    &mut current_tier,
                    &mut output,
                    &mut changed,
                    tracer,
                );
                output.push(inst.clone());
                tracer.keep(i);
            }
        }
    }
    flush(
        &mut pending,
        &mut pending_src,
        &mut current_tier,
        &mut output,
        &mut changed,
        tracer,
    );

    if changed {
        tracer.commit();
        Cow::Owned(circuit.with_instructions(output))
    } else {
        tracer.discard();
        circuit
    }
}

/// Batch contiguous runs of diagonal gates into `DiagonalBatch` instructions.
///
/// Diagonal gates (Z, S, T, Rz, P, CZ, Rzz, CPhase) commute with each other,
/// so adjacent diagonal gates can be collapsed into a single pass with precomputed
/// phase LUTs. Non-diagonal gates on non-involved qubits are deferred past the run.
fn fuse_diagonal_batch<'a>(input: Cow<'a, Circuit>, t: &mut Tracer) -> Cow<'a, Circuit> {
    let circuit = input.as_ref();
    let insts = &circuit.instructions;
    let n = insts.len();
    if n < 2 {
        return input;
    }

    let diag_count = insts
        .iter()
        .filter(|i| matches!(i, Instruction::Gate { gate, .. } if gate.is_diag_batchable()))
        .count();
    if diag_count < 2 {
        return input;
    }
    t.bail();

    let mut output: Vec<Instruction> = Vec::with_capacity(n);
    let mut run_entries: Vec<DiagEntry> = Vec::new();
    let mut run_originals: Vec<Instruction> = Vec::new();
    let mut run_qubits = vec![false; circuit.num_qubits];
    let mut deferred: Vec<Instruction> = Vec::new();
    let mut deferred_qubits = vec![false; circuit.num_qubits];

    let flush_diag_run = |output: &mut Vec<Instruction>,
                          entries: &mut Vec<DiagEntry>,
                          originals: &mut Vec<Instruction>,
                          deferred: &mut Vec<Instruction>,
                          run_qubits: &mut [bool],
                          deferred_qubits: &mut [bool]| {
        if entries.len() >= 2 {
            let mut tgts: SmallVec<[usize; 4]> = SmallVec::new();
            for (i, &used) in run_qubits.iter().enumerate() {
                if used {
                    tgts.push(i);
                }
            }
            output.push(Instruction::Gate {
                gate: Gate::DiagonalBatch(Box::new(DiagonalBatchData {
                    entries: std::mem::take(entries),
                })),
                targets: tgts,
            });
        } else {
            output.append(originals);
        }
        entries.clear();
        originals.clear();
        output.append(deferred);
        run_qubits.fill(false);
        deferred_qubits.fill(false);
    };

    for inst in insts {
        if let Instruction::Gate { gate, targets } = inst {
            if gate.is_diag_batchable() {
                // Deferred gates are re-emitted after the whole batch. Admitting
                // a diagonal gate on a deferred gate's qubit would sink that
                // gate behind one it does not commute with, so close the run
                // first and let this gate open a new one.
                if targets.iter().any(|t| deferred_qubits[*t]) {
                    flush_diag_run(
                        &mut output,
                        &mut run_entries,
                        &mut run_originals,
                        &mut deferred,
                        &mut run_qubits,
                        &mut deferred_qubits,
                    );
                }
                let new_entries = gate.diag_entries(targets);
                for t in targets.iter() {
                    run_qubits[*t] = true;
                }
                run_entries.extend(new_entries);
                run_originals.push(inst.clone());
                continue;
            }

            if !run_entries.is_empty() && gate.num_qubits() == 1 && !run_qubits[targets[0]] {
                deferred_qubits[targets[0]] = true;
                deferred.push(inst.clone());
                continue;
            }
        }

        flush_diag_run(
            &mut output,
            &mut run_entries,
            &mut run_originals,
            &mut deferred,
            &mut run_qubits,
            &mut deferred_qubits,
        );
        output.push(inst.clone());
    }

    flush_diag_run(
        &mut output,
        &mut run_entries,
        &mut run_originals,
        &mut deferred,
        &mut run_qubits,
        &mut deferred_qubits,
    );

    let mut c = Circuit::new(circuit.num_qubits, circuit.num_classical_bits);
    c.instructions = output;
    Cow::Owned(c)
}

/// Threads a `&Circuit -> Cow<Circuit>` pass over a `Cow<Circuit>` while
/// preserving zero-copy when both input and output are borrowed.
#[inline]
fn apply_pass<'a, F>(input: Cow<'a, Circuit>, t: &mut Tracer, pass: F) -> Cow<'a, Circuit>
where
    F: for<'b> Fn(&'b Circuit, &mut Tracer) -> Cow<'b, Circuit>,
{
    match input {
        Cow::Borrowed(c) => pass(c, t),
        Cow::Owned(c) => Cow::Owned(pass(&c, t).into_owned()),
    }
}

#[inline]
fn gated<'a, F>(
    input: Cow<'a, Circuit>,
    num_qubits: usize,
    threshold: usize,
    pass: F,
) -> Cow<'a, Circuit>
where
    F: FnOnce(Cow<'a, Circuit>) -> Cow<'a, Circuit>,
{
    if num_qubits >= threshold {
        pass(input)
    } else {
        input
    }
}

/// Fuse each guarded region's body in isolation.
///
/// Every other pass treats a region as one opaque instruction spanning its
/// qubit union, so a body would otherwise run entirely unfused. A body is an
/// ordinary instruction list over the same register, so the pipeline applies to
/// it unchanged. Nothing moves across the boundary here, and nesting is handled
/// by the recursive call rather than by descending twice.
///
/// The tracer is left alone deliberately: this pass rewrites region payloads in
/// place, and a region carries no provenance of its own, so the input mapping
/// still describes the output exactly.
fn fuse_region_bodies<'a>(circuit: &'a Circuit, n: usize) -> Cow<'a, Circuit> {
    let insts = &circuit.instructions;
    let mut out: Option<Vec<Instruction>> = None;

    for (i, inst) in insts.iter().enumerate() {
        let fused_region = match inst {
            Instruction::Region(region) => {
                let body = circuit.with_instructions(region.body().to_vec());
                match fuse_at_width(&body, n, &mut Tracer::off()) {
                    Cow::Owned(fused) => Some(Instruction::Region(Box::new(GuardedRegion::new(
                        region.condition().clone(),
                        fused.instructions,
                    )))),
                    Cow::Borrowed(_) => None,
                }
            }
            _ => None,
        };

        match fused_region {
            Some(region) => out.get_or_insert_with(|| insts[..i].to_vec()).push(region),
            None => {
                if let Some(buf) = out.as_mut() {
                    buf.push(inst.clone());
                }
            }
        }
    }

    match out {
        Some(buf) => Cow::Owned(circuit.with_instructions(buf)),
        None => Cow::Borrowed(circuit),
    }
}

/// Returns `Cow::Borrowed` when no fusion is profitable (zero overhead).
/// Set `supports_fused` to `false` for backends that cannot handle fused gates
/// (e.g., stabilizer).
///
/// Gates the passes at the circuit's own width. A backend whose buffer is wider
/// than a `num_qubits` statevector takes
/// [`fuse_circuit_for_width`] instead.
pub fn fuse_circuit<'a>(circuit: &'a Circuit, supports_fused: bool) -> Cow<'a, Circuit> {
    fuse_circuit_for_width(circuit, supports_fused, circuit.num_qubits)
}

/// Fuse for a backend that sweeps a `state_qubits`-wide buffer.
///
/// Every floor here is calibrated against the cost of one statevector pass, so
/// the gate is buffer width rather than circuit width. They coincide for a
/// statevector and part company for the density matrix, which holds an
/// `n`-qubit mixture as a `2n`-qubit statevector and so reaches each floor at
/// half the circuit width.
pub fn fuse_circuit_for_width<'a>(
    circuit: &'a Circuit,
    supports_fused: bool,
    state_qubits: usize,
) -> Cow<'a, Circuit> {
    if !supports_fused {
        return Cow::Borrowed(circuit);
    }
    fuse_at_width(circuit, state_qubits, &mut Tracer::off())
}

/// The pass pipeline at the circuit's own width, recording provenance into `t`.
pub(super) fn fuse_traced<'a>(circuit: &'a Circuit, t: &mut Tracer) -> Cow<'a, Circuit> {
    fuse_at_width(circuit, circuit.num_qubits, t)
}

fn fuse_at_width<'a>(circuit: &'a Circuit, n: usize, t: &mut Tracer) -> Cow<'a, Circuit> {
    let pass_r = fuse_region_bodies(circuit, n);
    let pass0 = apply_pass(pass_r, t, cancel_self_inverse_pairs);
    let pass0r = apply_pass(pass0, t, fuse_rzz);
    let pass0b = gated(pass0r, n, MIN_QUBITS_FOR_DIAG_BATCH, |c| {
        apply_pass(c, t, fuse_batch_rzz)
    });

    if n < MIN_QUBITS_FOR_FUSION {
        return pass0b;
    }

    let pass1 = apply_pass(pass0b, t, fuse_single_qubit_gates);
    let pass1r = reorder_1q_gates(pass1, t);
    let pass1c = apply_pass(pass1r, t, cancel_self_inverse_pairs);
    let pass1f = apply_pass(pass1c, t, fuse_single_qubit_gates);

    let pass_2q = gated(pass1f, n, MIN_QUBITS_FOR_2Q_FUSION, |c| fuse_2q_gates(c, t));
    let pass_2qb = gated(pass_2q, n, MIN_QUBITS_FOR_2Q_FUSION, |c| {
        fuse_same_pair_2q_blocks(c, t)
    });
    let pass2 = gated(pass_2qb, n, MIN_QUBITS_FOR_MULTI_FUSION, |c| {
        fuse_multi_1q_gates(c, t)
    });
    let pass_2qr = if n >= MIN_QUBITS_FOR_MULTI_2Q_FUSION && reorder_2q_enabled() {
        reorder_disjoint_fused2q(pass2, t)
    } else {
        pass2
    };
    let pass_m2q = gated(pass_2qr, n, MIN_QUBITS_FOR_MULTI_2Q_FUSION, |c| {
        fuse_multi_2q_gates(c, t)
    });
    let pass_cp = gated(pass_m2q, n, MIN_QUBITS_FOR_DIAG_BATCH, |c| {
        fuse_controlled_phases(c, t)
    });
    let pass_db = gated(pass_cp, n, MIN_QUBITS_FOR_DIAG_BATCH, |c| {
        fuse_diagonal_batch(c, t)
    });
    gated(pass_db, n, MIN_QUBITS_FOR_POST_PHASE_BATCH, |c| {
        batch_post_phase_1q(c, t)
    })
}

#[cfg(test)]
#[path = "fusion_tests.rs"]
mod tests;