analyssa 0.4.1

Target-agnostic SSA IR, analyses, and optimization pipeline
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
//! Pass scheduler configuration tests.

mod common;

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Mutex,
};

use analyssa::{
    Error, PipelineConfig, Result,
    events::{EventListener, EventLog, NullListener},
    host::{DirtySet, SsaStore},
    ir::{function::SsaFunction, ops::SsaOp, variable::SsaVarId},
    passes::{
        AlgebraicSimplificationPass, BlockMergingPass, ControlFlowSimplificationPass,
        CopyPropagationPass, DeadCodeEliminationPass, DeadMethodEliminationPass,
        GlobalValueNumberingPass, JumpThreadingPass, LicmPass, LoopCanonicalizationPass,
        MemoryOptimizationPass, OpaquePredicatePass, ReassociationPass, StrengthReductionPass,
        ValueRangePropagationPass,
    },
    scheduling::{ModificationScope, PassScheduler, SsaPass, SsaPassHost},
    testing::{self, MockTarget},
    world::World,
};
use common::assert_valid_full;

fn pass_name(pass: &dyn SsaPass<MockTarget, MockHost>) -> &'static str {
    pass.name()
}

fn pass_scope(pass: &dyn SsaPass<MockTarget, MockHost>) -> ModificationScope {
    pass.modification_scope()
}

fn pass_repairs_ssa(pass: &dyn SsaPass<MockTarget, MockHost>) -> bool {
    pass.repairs_ssa()
}

fn pass_is_global(pass: &dyn SsaPass<MockTarget, MockHost>) -> bool {
    pass.is_global()
}

fn some_or_abort<T>(value: Option<T>) -> T {
    value.unwrap_or_else(|| std::process::abort())
}

fn result_or_abort<T>(result: Result<T>) -> T {
    result.unwrap_or_else(|_| std::process::abort())
}

fn err_or_abort<T>(result: Result<T>) -> Error {
    match result {
        Ok(_) => std::process::abort(),
        Err(error) => error,
    }
}

#[derive(Default)]
struct MockHost {
    ssa: Mutex<BTreeMap<u32, SsaFunction<MockTarget>>>,
    dirty: Mutex<BTreeSet<u32>>,
    processed: Mutex<BTreeSet<u32>>,
    events: EventLog<MockTarget>,
    /// Counts `methods_reverse_topological` calls. That default implementation
    /// builds the whole call graph, and the scheduler used to ask for it once
    /// per method list — twice per pass batch, inside its own fixpoint.
    topo_calls: std::sync::atomic::AtomicUsize,
}

impl World<MockTarget> for MockHost {
    fn methods_reverse_topological(&self) -> Vec<Vec<u32>> {
        self.topo_calls
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        analyssa::interproc::CallGraph::from_world(self).components_callee_first()
    }

    fn all_methods(&self) -> Vec<u32> {
        self.iter_methods()
    }

    fn entry_points(&self) -> Vec<u32> {
        self.iter_methods()
    }

    fn callees(&self, _method: &u32) -> Vec<u32> {
        Vec::new()
    }

    fn is_dead(&self, _method: &u32) -> bool {
        false
    }

    fn mark_dead(&self, _method: &u32) {}
}

impl SsaStore<MockTarget> for MockHost {
    fn contains(&self, method: &u32) -> bool {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .contains_key(method)
    }

    fn take_ssa(&self, method: &u32) -> Option<SsaFunction<MockTarget>> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .remove(method)
    }

    fn insert_ssa(&self, method: u32, ssa: SsaFunction<MockTarget>) {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .insert(method, ssa);
    }

    fn clone_ssa(&self, method: &u32) -> Option<SsaFunction<MockTarget>> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .get(method)
            .cloned()
    }

    fn iter_methods(&self) -> Vec<u32> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .keys()
            .copied()
            .collect()
    }
}

impl DirtySet<MockTarget> for MockHost {
    fn mark_dirty(&self, method: &u32) {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .insert(*method);
    }

    fn is_dirty(&self, method: &u32) -> bool {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .contains(method)
    }

    fn dirty_snapshot(&self) -> Vec<u32> {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .iter()
            .copied()
            .collect()
    }

    fn clear_dirty_for(&self, method: &u32) {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .remove(method);
    }

    fn mark_processed(&self, method: &u32) {
        self.processed
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .insert(*method);
    }

    fn is_processed(&self, method: &u32) -> bool {
        self.processed
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .contains(method)
    }
}

impl SsaPassHost<MockTarget> for MockHost {
    fn events(&self) -> &dyn EventListener<MockTarget> {
        &self.events
    }
}

struct BreakingPass;

impl SsaPass<MockTarget, MockHost> for BreakingPass {
    fn name(&self) -> &'static str {
        "breaking"
    }

    fn run_on_method(
        &self,
        ssa: &mut SsaFunction<MockTarget>,
        _method: &u32,
        _host: &MockHost,
    ) -> Result<bool> {
        ssa.replace_instruction_op(
            0,
            1,
            SsaOp::Return {
                value: Some(SsaVarId::from_index(99)),
            },
        );
        Ok(true)
    }

    fn modification_scope(&self) -> ModificationScope {
        ModificationScope::InstructionsOnly
    }
}

struct FailingPass;

impl SsaPass<MockTarget, MockHost> for FailingPass {
    fn name(&self) -> &'static str {
        "failing"
    }

    fn run_on_method(
        &self,
        _ssa: &mut SsaFunction<MockTarget>,
        _method: &u32,
        _host: &MockHost,
    ) -> Result<bool> {
        Err(Error::new("pass failed"))
    }
}

#[test]
fn default_pipeline_config_registers_all_builtin_passes() {
    let config = PipelineConfig::default();
    let scheduler = PassScheduler::<MockTarget, MockHost>::new(config);

    assert_eq!(scheduler.normalize_count(), 3);
    assert_eq!(scheduler.pass_count(), 12);

    let without_global = PipelineConfig {
        include_dead_method_elimination: false,
        ..PipelineConfig::default()
    };
    let scheduler = PassScheduler::<MockTarget, MockHost>::new(without_global);

    assert_eq!(scheduler.normalize_count(), 3);
    assert_eq!(scheduler.pass_count(), 11);
}

#[test]
fn verify_hard_reports_invalid_pass_output_and_rolls_back() {
    let host = MockHost::default();
    let method = 1u32;
    let original = testing::const_i32_return(7);
    host.insert_ssa(method, original.clone());

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        verify_hard: true,
        max_iterations: 1,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, MockHost>::new(config);
    scheduler.add_at_layer(Box::new(BreakingPass), 0);

    let error = err_or_abort(scheduler.run_pipeline(&host));

    assert!(error.to_string().contains("breaking"));
    assert!(error.to_string().contains("invalid SSA"));
    let stored = some_or_abort(host.clone_ssa(&method));
    assert_eq!(format!("{stored}"), format!("{original}"));
}

#[test]
fn scheduler_propagates_pass_errors() {
    let host = MockHost::default();
    let method = 1u32;
    host.insert_ssa(method, testing::const_i32_return(7));

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        max_iterations: 1,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, MockHost>::new(config);
    scheduler.add_at_layer(Box::new(FailingPass), 0);

    let error = err_or_abort(scheduler.run_pipeline(&host));

    assert!(error.to_string().contains("failing"));
    assert!(error.to_string().contains("pass failed"));
}

#[test]
fn default_scheduler_verify_hard_handles_mixed_builder_fixtures() {
    let host = MockHost::default();
    host.insert_ssa(1, testing::scalar_rewrite_fixture());
    host.insert_ssa(2, testing::diamond_phi_fixture());
    host.insert_ssa(3, testing::memory_effect_fixture());
    host.insert_ssa(4, testing::native_effect_fixture());
    host.insert_ssa(5, testing::vector_simd_fixture());

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        verify_hard: true,
        max_iterations: 2,
        max_phase_iterations: 3,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, MockHost>::new(config);

    let changes = result_or_abort(scheduler.run_pipeline(&host));
    assert!(changes > 0, "mixed fixtures should expose scheduler work");

    for method in host.iter_methods() {
        let ssa = some_or_abort(host.clone_ssa(&method));
        assert_valid_full(&ssa, &format!("method {method} after scheduler"));
    }
}

#[test]
fn built_in_pass_wrappers_report_expected_metadata() {
    let instructions_only = ModificationScope::InstructionsOnly;
    let uses_only = ModificationScope::UsesOnly;
    let cfg = ModificationScope::CfgModifying;

    let algebraic = AlgebraicSimplificationPass::new();
    assert_eq!(pass_name(&algebraic), "algebraic-simplification");
    assert_eq!(pass_scope(&algebraic), instructions_only);
    assert!(pass_repairs_ssa(&algebraic));
    assert!(!pass_is_global(&algebraic));

    let blockmerge = BlockMergingPass::new(3);
    assert_eq!(pass_name(&blockmerge), "block-merging");
    assert_eq!(pass_scope(&blockmerge), cfg);
    assert!(pass_repairs_ssa(&blockmerge));
    assert_eq!(blockmerge.max_iterations, 3);

    let controlflow = ControlFlowSimplificationPass::new(4);
    assert_eq!(pass_name(&controlflow), "control-flow-simplification");
    assert_eq!(pass_scope(&controlflow), cfg);
    assert!(pass_repairs_ssa(&controlflow));
    assert_eq!(controlflow.max_iterations, 4);

    let copying = CopyPropagationPass::new(5);
    assert_eq!(pass_name(&copying), "copy-propagation");
    assert_eq!(pass_scope(&copying), instructions_only);
    assert!(pass_repairs_ssa(&copying));
    assert_eq!(copying.max_iterations, 5);

    let memory_opt = MemoryOptimizationPass;
    assert_eq!(pass_name(&memory_opt), "memory-optimization");
    assert_eq!(pass_scope(&memory_opt), instructions_only);
    assert!(pass_repairs_ssa(&memory_opt));
    assert!(!pass_is_global(&memory_opt));

    let dce = DeadCodeEliminationPass::new(6);
    assert_eq!(pass_name(&dce), "dead-code-elimination");
    assert_eq!(pass_scope(&dce), instructions_only);
    assert_eq!(dce.max_iterations, 6);

    let global_dce = DeadMethodEliminationPass;
    assert_eq!(pass_name(&global_dce), "dead-method-elimination");
    assert!(pass_is_global(&global_dce));

    let gvn = GlobalValueNumberingPass::new();
    assert_eq!(pass_name(&gvn), "global-value-numbering");
    assert_eq!(pass_scope(&gvn), uses_only);

    let licm = LicmPass::new();
    assert_eq!(pass_name(&licm), "licm");
    assert_eq!(pass_scope(&licm), cfg);
    assert!(pass_repairs_ssa(&licm));

    let loopcanon = LoopCanonicalizationPass::new();
    assert_eq!(pass_name(&loopcanon), "loop-canonicalization");
    assert_eq!(pass_scope(&loopcanon), cfg);
    assert!(pass_repairs_ssa(&loopcanon));

    let predicates = OpaquePredicatePass::<MockTarget>::new();
    assert_eq!(pass_name(&predicates), "opaque-predicate");
    assert_eq!(pass_scope(&predicates), cfg);
    assert!(pass_repairs_ssa(&predicates));

    let ranges = ValueRangePropagationPass::new(7);
    assert_eq!(pass_name(&ranges), "value-range-propagation");
    assert_eq!(pass_scope(&ranges), cfg);
    assert!(pass_repairs_ssa(&ranges));
    assert_eq!(ranges.max_iterations, 7);

    let reassociation = ReassociationPass::new();
    assert_eq!(pass_name(&reassociation), "reassociation");
    assert_eq!(pass_scope(&reassociation), instructions_only);
    assert!(pass_repairs_ssa(&reassociation));

    let strength = StrengthReductionPass;
    assert_eq!(pass_name(&strength), "strength-reduction");
    assert_eq!(pass_scope(&strength), instructions_only);
    assert!(pass_repairs_ssa(&strength));

    let threading = JumpThreadingPass::new();
    assert_eq!(pass_name(&threading), "jump-threading");
    assert_eq!(pass_scope(&threading), cfg);
    assert!(pass_repairs_ssa(&threading));
}

/// The scheduler needs two method orders per pass batch — every method, and the
/// dirty subset. It used to derive each with its own call to
/// `methods_reverse_topological`, whose default implementation builds the entire
/// call graph. That doubled the call-graph cost of every batch, and batches run
/// inside the scheduler's own fixpoint, so it was paid per iteration too.
#[test]
fn a_pass_batch_builds_the_call_graph_once() {
    use std::sync::atomic::Ordering;

    let host = MockHost::default();
    for method in 1u32..=4 {
        host.insert_ssa(method, testing::const_i32_return(method as i32));
    }

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        max_iterations: 1,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, MockHost>::new(config);
    scheduler.add_at_layer(Box::new(CountingPass), 0);

    host.topo_calls.store(0, Ordering::Relaxed);
    result_or_abort(scheduler.run_pipeline(&host));

    // This configuration runs two batches. Each must build the call graph once,
    // for two total — it was four, one per method list per batch.
    let calls = host.topo_calls.load(Ordering::Relaxed);
    assert_eq!(
        calls, 2,
        "each pass batch must build the call graph once, not once per method list"
    );
}

/// A pass that touches nothing, so the pipeline runs exactly one batch.
struct CountingPass;

impl SsaPass<MockTarget, MockHost> for CountingPass {
    fn name(&self) -> &'static str {
        "counting"
    }

    fn run_on_method(
        &self,
        _ssa: &mut SsaFunction<MockTarget>,
        _method: &u32,
        _host: &MockHost,
    ) -> Result<bool> {
        Ok(false)
    }
}

/// A host that discards events entirely.
///
/// This is the shape that `SsaPassHost::events()` returning a concrete
/// `&EventLog<T>` made impossible: `EventLog` is an append-only `boxcar::Vec`
/// with no bound and no drain, so a host that never consumes events still had to
/// retain every one of them for the process lifetime.
#[derive(Default)]
struct SilentHost {
    ssa: Mutex<BTreeMap<u32, SsaFunction<MockTarget>>>,
    dirty: Mutex<BTreeSet<u32>>,
    sink: NullListener,
}

impl World<MockTarget> for SilentHost {
    fn all_methods(&self) -> Vec<u32> {
        self.iter_methods()
    }

    fn entry_points(&self) -> Vec<u32> {
        self.iter_methods()
    }

    fn callees(&self, _method: &u32) -> Vec<u32> {
        Vec::new()
    }

    fn is_dead(&self, _method: &u32) -> bool {
        false
    }

    fn mark_dead(&self, _method: &u32) {}
}

impl SsaStore<MockTarget> for SilentHost {
    fn take_ssa(&self, method: &u32) -> Option<SsaFunction<MockTarget>> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .remove(method)
    }

    fn clone_ssa(&self, method: &u32) -> Option<SsaFunction<MockTarget>> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .get(method)
            .cloned()
    }

    fn insert_ssa(&self, method: u32, ssa: SsaFunction<MockTarget>) {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .insert(method, ssa);
    }

    fn contains(&self, method: &u32) -> bool {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .contains_key(method)
    }

    fn iter_methods(&self) -> Vec<u32> {
        self.ssa
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .keys()
            .copied()
            .collect()
    }
}

impl DirtySet<MockTarget> for SilentHost {
    fn mark_dirty(&self, method: &u32) {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .insert(*method);
    }

    fn is_dirty(&self, method: &u32) -> bool {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .contains(method)
    }

    fn mark_processed(&self, _method: &u32) {}

    fn is_processed(&self, _method: &u32) -> bool {
        false
    }

    fn dirty_snapshot(&self) -> Vec<u32> {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .iter()
            .copied()
            .collect()
    }

    fn clear_dirty_for(&self, method: &u32) {
        self.dirty
            .lock()
            .unwrap_or_else(|_| std::process::abort())
            .remove(method);
    }
}

impl SsaPassHost<MockTarget> for SilentHost {
    fn events(&self) -> &dyn EventListener<MockTarget> {
        &self.sink
    }
}

#[test]
fn a_host_can_discard_events_entirely() {
    let host = SilentHost::default();
    host.insert_ssa(1, testing::const_i32_return(7));

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        max_iterations: 1,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, SilentHost>::new(config);
    scheduler.add_at_layer(Box::new(CountingPass2), 0);

    result_or_abort(scheduler.run_pipeline(&host));

    // A discarding sink reports no history, and the scheduler's debug summary
    // degrades to "no detail" rather than failing to compile or panicking.
    assert_eq!(host.events().recorded_count(), 0);
    assert!(host.events().count_by_kind_since(0).is_empty());
    assert!(!host.events().is_enabled());
}

struct CountingPass2;

impl SsaPass<MockTarget, SilentHost> for CountingPass2 {
    fn name(&self) -> &'static str {
        "silent"
    }

    fn run_on_method(
        &self,
        _ssa: &mut SsaFunction<MockTarget>,
        _method: &u32,
        _host: &SilentHost,
    ) -> Result<bool> {
        Ok(false)
    }
}

/// A pass that panics.
struct PanickingPass;

impl SsaPass<MockTarget, MockHost> for PanickingPass {
    fn name(&self) -> &'static str {
        "panicking"
    }

    // The crate denies `clippy::panic`, but this test exists to prove the
    // scheduler survives a real unwind, which needs a real panic.
    #[allow(clippy::panic)]
    fn run_on_method(
        &self,
        _ssa: &mut SsaFunction<MockTarget>,
        _method: &u32,
        _host: &MockHost,
    ) -> Result<bool> {
        panic!("deliberate pass panic");
    }
}

/// The scheduler *takes* a method's SSA from the store before running a pass, so
/// an unwind through the pass skips every reinsertion and the method loses its
/// body permanently — a panicking pass would silently delete code rather than
/// fail. The panic must be reported and the function restored.
#[test]
fn a_panicking_pass_does_not_destroy_the_method() {
    let host = MockHost::default();
    let method = 1u32;
    let original = testing::const_i32_return(7);
    host.insert_ssa(method, original.clone());

    let config = PipelineConfig {
        include_dead_method_elimination: false,
        max_iterations: 1,
        ..PipelineConfig::default()
    };
    let mut scheduler = PassScheduler::<MockTarget, MockHost>::new(config);
    scheduler.add_at_layer(Box::new(PanickingPass), 0);

    let error = err_or_abort(scheduler.run_pipeline(&host));

    assert!(
        error.to_string().contains("panicked"),
        "the panic must be reported as an error; got {error}"
    );
    assert!(
        error.to_string().contains("panicking"),
        "and must name the pass; got {error}"
    );

    let stored = some_or_abort(host.clone_ssa(&method));
    assert_eq!(
        format!("{stored}"),
        format!("{original}"),
        "the method's SSA must survive the panic"
    );
}