pliron 0.17.0

Programming Languages Intermediate RepresentatiON
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) The pliron contributors

//! A framework to run passes and manage analyses.
//!
//! The design is centered around the [Pass] trait and aims to be
//! flexible and composable. Passes can be combined into pipelines,
//! and analyses can be cached and invalidated between passes.
//!
//! This module provides:
//! 1. [`Pass`]: A transformation that runs on an operation.
//! 2. [`Passes`]: Runs a sequence of [Pass]es on the provided operation,
//!    managing invalidation of analyses between passes.
//! 3. [`NestedOpsPass`]: Runs a provided [Pass] on each immediately nested operation,
//!    managing invalidation of analyses between runs.
//! 4. [`GuardedPass`], [`OpPass`], and [`OpInterfacePass`]: Wrappers that
//!    constrain where a pass is allowed to run.
//! 5. [`Analysis`] and [`AnalysisManager`]: Provides analyses caching with
//!    preservation and invalidation support.
//! 6. [`PMConfig`] provides configuration that can be set via the [AnalysisManager].
//!
//! # Usage
//!
//! A pass receives three inputs:
//! * The operation it should process,
//! * A mutable reference to the context
//! * An analysis cache.
//!
//! It returns a [`PassResult`] indicating whether IR changed and which analyses
//! are preserved.
//!
//! If a pass reports [`IRStatus::Unchanged`], all analyses are treated as
//! preserved. If it reports changes, analyses not explicitly preserved are
//! invalidated.
//!
//! **NOTE**: A pass must not modify the IR outside of the operation it is applied to.
//!
//! ## Example: Define and run a simple pass
//!
//! ```rust
//! use pliron::{
//!     context::Context,
//!     operation::Operation,
//!     pass::{AnalysisManager, Pass, PassResult, Passes},
//!     result::Result,
//!     irbuild::IRStatus,
//! };
//!
//! #[derive(Default)]
//! struct NoOpPass;
//!
//! impl Pass for NoOpPass {
//!     fn name(&self) -> &str { "noop" }
//!
//!     fn run(
//!         &mut self,
//!         _op: pliron::context::Ptr<Operation>,
//!         _ctx: &mut Context,
//!         _analyses: &mut AnalysisManager,
//!     ) -> Result<PassResult> {
//!         let mut result = PassResult::default();
//!         result.ir_changed = IRStatus::Unchanged;
//!         Ok(result)
//!     }
//! }
//!
//! fn run_pipeline(
//!     root: pliron::context::Ptr<Operation>,
//!     ctx: &mut Context,
//! ) -> Result<()> {
//!     let mut passes = Passes::default();
//!     passes.add_pass(NoOpPass);
//!     let res = passes.run(root, ctx, &mut AnalysisManager::default())?;
//!     assert!(matches!(res.ir_changed, IRStatus::Unchanged));
//!     Ok(())
//! }
//! ```
//!
//! ## Example: Restrict a pass to a specific op kind.
//! [GuardedPass] is a [Pass] wrapper restricting the run to specific operations.
//! [OpPass] is a [GuardedPass] that restricts the run to a specific [Op].
//! [NestedOpsPass] is a [Pass] that runs a provided [Pass] on each immediately nested operation.
//!
//! ```rust
//! use pliron::{
//!     context::Context,
//!     irbuild::IRStatus,
//!     operation::Operation,
//!     pass::{AnalysisManager, NestedOpsPass, Passes, OpPass, Pass, PassResult},
//!     result::Result,
//! };
//! use pliron::builtin::ops::{FuncOp, ModuleOp};
//!
//! #[derive(Default)]
//! struct MyFuncPass;
//!
//! impl Pass for MyFuncPass {
//!     fn name(&self) -> &str { "my_func_pass" }
//!
//!     fn run(
//!         &mut self,
//!         _op: pliron::context::Ptr<Operation>,
//!         _ctx: &mut Context,
//!         _analyses: &mut AnalysisManager,
//!     ) -> Result<PassResult> {
//!         let mut result = PassResult::default();
//!         result.ir_changed = IRStatus::Unchanged;
//!         Ok(result)
//!     }
//! }
//!
//! // Run a pass manager only when the root op is ModuleOp.
//! let mut passes = OpPass::<ModuleOp, Passes>::default();
//! // Add a pass that runs only on nested FuncOp operations.
//! let nested_pass = NestedOpsPass::new(OpPass::<FuncOp, MyFuncPass>::default());
//! passes.add_pass(nested_pass);
//! ```
//!
//! ## Example: Analysis caching and preservation
//!
//! ```rust
//! use pliron::{
//!     context::Context,
//!     operation::Operation,
//!     pass::{Analysis, AnalysisManager, Pass, PassResult},
//!     result::Result,
//! };
//!
//! struct MyAnalysis;
//!
//! impl Analysis for MyAnalysis {
//!     fn name(&self) -> &str { "my_analysis" }
//!     fn compute(
//!         _op: pliron::context::Ptr<Operation>,
//!         _ctx: &Context,
//!         _analyses: &mut AnalysisManager,
//!     ) -> Result<Self> {
//!         Ok(Self)
//!     }
//! }
//!
//! struct UsesMyAnalysis;
//!
//! impl Pass for UsesMyAnalysis {
//!     fn name(&self) -> &str { "uses_my_analysis" }
//!
//!     fn run(
//!         &mut self,
//!         op: pliron::context::Ptr<Operation>,
//!         ctx: &mut Context,
//!         analyses: &mut AnalysisManager,
//!     ) -> Result<PassResult> {
//!         let _analysis = analyses.get_analysis::<MyAnalysis>(op, ctx)?;
//!         let mut result = PassResult::default();
//!         // If this pass mutates IR but does not invalidate MyAnalysis,
//!         // explicitly preserve it.
//!         result.set_preserved::<MyAnalysis>();
//!         Ok(result)
//!     }
//! }
//! ```

use core::{
    cell::{Ref, RefCell, RefMut},
    ops::{Deref, DerefMut},
};

use alloc::{
    boxed::Box,
    string::{String, ToString},
    vec::Vec,
};
use downcast_rs::{Downcast, impl_downcast};
use thiserror::Error;

use crate::{
    arg_error_noloc,
    context::{Context, Ptr},
    identifier::Identifier,
    irbuild::IRStatus,
    op::{Op, OpInterfaceMarker, op_impls},
    operation::{OpDbg, Operation, verify_operation},
    printable::Printable,
    result::Result,
    std_deps::{
        self,
        fs::{create_dir_all, write},
        path::PathBuf,
    },
    utils::{
        table::{HMap, HSet, IMap},
        timer::Timer,
    },
};

#[derive(Default)]
/// The result of running a [Pass].
///
/// 1. [IRStatus]: Whether the IR was changed or not.
/// 2. A list of preserved analyses.
///
/// [IRStatus::Unchanged] implies all analyses are preserved.
pub struct PassResult {
    pub ir_changed: IRStatus,
    preserved_analyses: HSet<core::any::TypeId>,
}

impl PassResult {
    pub fn set_preserved<A: Analysis + 'static>(&mut self) {
        self.preserved_analyses.insert(core::any::TypeId::of::<A>());
    }
}

/// A pass is any code that runs on the provided [Operation].
/// Typically a transformation or (nested) passes.
///
/// Transformations must not modify the IR outside of the [Operation] they are applied to.
pub trait Pass {
    /// Name of the pass.
    fn name(&self) -> &str;

    /// Run the pass and return whether the IR changed and which analyses are preserved.
    fn run(
        &mut self,
        op: Ptr<Operation>,
        ctx: &mut Context,
        analyses: &mut AnalysisManager,
    ) -> Result<PassResult>;

    /// If this [Pass] contains, manages and runs other passes,
    /// get [self] as a [PassManager].
    /// Most passes do not qualify and must not override this method.
    fn as_pass_manager(&mut self) -> Option<&mut dyn PassManager> {
        None
    }
}

#[derive(Default)]
/// Runs a sequence of [Pass]es on the provided [Operation].
/// Manages invalidation of analyses between passes.
pub struct Passes {
    passes: Vec<Box<dyn Pass>>,
}

impl Pass for Passes {
    fn name(&self) -> &str {
        "passes"
    }

    fn run(
        &mut self,
        op: Ptr<Operation>,
        ctx: &mut Context,
        analyses: &mut AnalysisManager,
    ) -> Result<PassResult> {
        let mut pass_res = PassResult::default();

        // Run each pass in the list on the current operation.
        for pass in &mut self.passes {
            let res = <Self as PassManager>::run_pass(&mut **pass, op, ctx, analyses)?;
            pass_res.ir_changed |= res.ir_changed;
            // Invalidate analyses that are not preserved.
            analyses.retain_preserved(&res);
        }

        // Since we invalidate analyses after each pass,
        // all remaining analyses are preserved.
        let preserved_analyses = analyses.list_analyses();
        pass_res.preserved_analyses = preserved_analyses;

        Ok(pass_res)
    }

    fn as_pass_manager(&mut self) -> Option<&mut dyn PassManager> {
        Some(self)
    }
}

impl Passes {
    /// Add a [Pass] to the list of passes to run.
    pub fn add_pass(&mut self, pass: impl Pass + 'static) {
        self.passes.push(Box::new(pass));
    }
}

impl PassManager for Passes {}

/// Runs a provided [Pass] on each immediately nested [Operation].
/// Manages invalidation of analyses between runs.
pub struct NestedOpsPass {
    pass: Box<dyn Pass>,
}

impl Pass for NestedOpsPass {
    fn name(&self) -> &str {
        "nested_ops_pass"
    }

    fn run(
        &mut self,
        op: Ptr<Operation>,
        ctx: &mut Context,
        analyses: &mut AnalysisManager,
    ) -> Result<PassResult> {
        use crate::linked_list::ContainsLinkedList;

        let mut pass_res = PassResult::default();

        let regions = op.deref(ctx).regions().collect::<Vec<_>>();
        for region in regions {
            let blocks = region.deref(ctx).iter(ctx).collect::<Vec<_>>();
            for block in blocks {
                let ops = block.deref(ctx).iter(ctx).collect::<Vec<_>>();
                for nested_op in ops {
                    let res =
                        <Self as PassManager>::run_pass(&mut *self.pass, nested_op, ctx, analyses)?;
                    pass_res.ir_changed |= res.ir_changed;
                    // Invalidate analyses that are not preserved.
                    analyses.retain_preserved(&res);
                }
            }
        }

        // Since we invalidate analyses after each pass,
        // all remaining analyses are preserved.
        let preserved_analyses = analyses.list_analyses();
        pass_res.preserved_analyses = preserved_analyses;

        Ok(pass_res)
    }

    fn as_pass_manager(&mut self) -> Option<&mut dyn PassManager> {
        Some(self)
    }
}

impl NestedOpsPass {
    pub fn new(pass: impl Pass + 'static) -> Self {
        Self {
            pass: Box::new(pass),
        }
    }
}

impl PassManager for NestedOpsPass {}

/// A `Guard` determines whether a [Pass] is applicable to a given [Operation].
pub trait Guard {
    /// Applicability of a [Pass] for a given [Operation].
    fn is_allowed(&self, op: Ptr<Operation>, ctx: &Context) -> bool;
}

/// Allow [Operation]s of a specific `Op`.
pub struct OpGuard<T: Op> {
    _marker: core::marker::PhantomData<T>,
}

impl<T: Op> Default for OpGuard<T> {
    fn default() -> Self {
        Self {
            _marker: core::marker::PhantomData,
        }
    }
}

impl<T: Op> Guard for OpGuard<T> {
    fn is_allowed(&self, op: Ptr<Operation>, ctx: &Context) -> bool {
        Operation::is_op::<T>(op, ctx)
    }
}

/// Allow [Operation]s that implement a specific `OpInterface`.
pub struct OpInterfaceGuard<T: ?Sized + OpInterfaceMarker + 'static> {
    _marker: core::marker::PhantomData<T>,
}

impl<T: ?Sized + OpInterfaceMarker + 'static> Default for OpInterfaceGuard<T> {
    fn default() -> Self {
        Self {
            _marker: core::marker::PhantomData,
        }
    }
}

impl<T: ?Sized + OpInterfaceMarker + 'static> Guard for OpInterfaceGuard<T> {
    fn is_allowed(&self, op: Ptr<Operation>, ctx: &Context) -> bool {
        let op = Operation::get_op_dyn(op, ctx);
        op_impls::<T>(&*op)
    }
}

/// Adds a [Guard] to a [Pass], making it run only on [Operation]s that the [Guard] allows.
#[derive(Default)]
pub struct GuardedPass<G: Guard, P: Pass> {
    guard: G,
    pass: P,
}

impl<G: Guard, P: Pass> GuardedPass<G, P> {
    pub fn new(guard: G, pass: P) -> Self {
        Self { guard, pass }
    }
}

impl<G: Guard, P: Pass> PassManager for GuardedPass<G, P> {}

impl<G: Guard, P: Pass> Pass for GuardedPass<G, P> {
    fn name(&self) -> &str {
        "guarded_pass"
    }

    fn run(
        &mut self,
        op: Ptr<Operation>,
        ctx: &mut Context,
        analyses: &mut AnalysisManager,
    ) -> Result<PassResult> {
        if self.guard.is_allowed(op, ctx) {
            <Self as PassManager>::run_pass(&mut self.pass, op, ctx, analyses)
        } else {
            Ok(PassResult::default())
        }
    }

    fn as_pass_manager(&mut self) -> Option<&mut dyn PassManager> {
        Some(self)
    }
}

impl<G: Guard, P: Pass> Deref for GuardedPass<G, P> {
    type Target = P;

    fn deref(&self) -> &Self::Target {
        &self.pass
    }
}

impl<G: Guard, P: Pass> DerefMut for GuardedPass<G, P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.pass
    }
}

/// A [GuardedPass] that allows [Operation]s of a specific [Op].
pub type OpPass<T, P> = GuardedPass<OpGuard<T>, P>;

/// A [GuardedPass] that allows [Operation]s that implement a specific `OpInterface`.
pub type OpInterfacePass<T, P> = GuardedPass<OpInterfaceGuard<T>, P>;

/// A [Pass] that contains, manages and runs other [Pass]es.
/// The only requirement (that cannot be enforced by the type system)
/// is that a [PassManager] [Pass] must run its contained [Passes] via
/// [PassManager::run_pass].
pub trait PassManager {
    /// Run a [Pass], calling pre/post hooks for non-manager passes.
    fn run_pass(
        pass: &mut dyn Pass,
        op: Ptr<Operation>,
        ctx: &mut Context,
        analyses: &mut AnalysisManager,
    ) -> Result<PassResult>
    where
        Self: Sized,
    {
        let is_pass_manager = pass.as_pass_manager().is_some();
        let config = analyses.pm_data().config();
        let pass_run_count = analyses.pm_data().state().pass_run_count;

        let skip_pass = !is_pass_manager && config.skip_passes.contains(pass.name());
        let pre_print_pass = !is_pass_manager
            && (config.print_before_all || config.print_before.contains(pass.name()));
        let post_print_pass = !is_pass_manager
            && (config.print_after_all || config.print_after.contains(pass.name()));
        let pre_verify_pass = !is_pass_manager
            && (config.verify_before_all || config.verify_before.contains(pass.name()));
        let post_verify_pass = !is_pass_manager
            && (config.verify_after_all || config.verify_after.contains(pass.name()));
        let should_time = !is_pass_manager
            && (config.time_all_passes || config.time_passes.contains(pass.name()));

        let ir_printing_dir = config.ir_printing_dir.clone();

        // Skip passes that are configured to be skipped, but only for non-manager passes.
        if skip_pass {
            log::debug!("Skipping pass {} on {}", pass.name(), OpDbg { op, ctx });
            return Ok(PassResult::default());
        }

        if !is_pass_manager {
            log::debug!("Running pass {} on {}", pass.name(), OpDbg { op, ctx });
        }

        if pre_print_pass {
            log::info!("IR before pass {}:\n{}", pass.name(), op.disp(ctx));
            if let Some(dir) = &ir_printing_dir {
                let filename = alloc::format!("{}-before-{}.plir", pass_run_count, pass.name());
                print_op_to_file(ctx, dir, filename, op)?;
            }
        }
        if pre_verify_pass {
            verify_operation(op, ctx).inspect_err(|e| {
                log::error!(
                    "Verification failed before pass {} on {}:\n{}",
                    pass.name(),
                    OpDbg { op, ctx },
                    e.disp(ctx)
                );
            })?;
        }
        let timer = Timer::start();
        // Run the pass and get the result.
        let result = pass.run(op, ctx, analyses);
        if should_time {
            let elapsed = timer.elapsed();
            log::info!(
                "Pass {} on {} completed in {:?}",
                pass.name(),
                OpDbg { op, ctx },
                elapsed
            );
        }
        if post_print_pass {
            log::info!("IR after pass {}:\n{}", pass.name(), op.disp(ctx));
            if let Some(dir) = &ir_printing_dir {
                let filename = alloc::format!("{}-after-{}.plir", pass_run_count, pass.name());
                print_op_to_file(ctx, dir, filename, op)?;
            }
        }
        if post_verify_pass {
            verify_operation(op, ctx).inspect_err(|e| {
                log::error!(
                    "Verification failed after pass {} on {}:\n{}",
                    pass.name(),
                    OpDbg { op, ctx },
                    e.disp(ctx)
                );
            })?;
        }

        if !is_pass_manager {
            analyses.pm_data_mut().state_mut().pass_run_count += 1;
        }

        result
    }
}

/// [PassManager] configuration.
#[derive(Default)]
pub struct PMConfig {
    /// If true, print the IR before running each pass.
    pub print_before_all: bool,
    /// If true, print the IR after running each pass.
    pub print_after_all: bool,
    /// Directory to place printed IR files before and after passes.
    /// The directory is created (including parents) if it doesn't exist.
    pub ir_printing_dir: Option<PathBuf>,
    /// Set of pass names for which to print the IR before execution.
    pub print_before: HSet<String>,
    /// Set of pass names for which to print the IR after execution.
    pub print_after: HSet<String>,
    /// If true, verify the IR before running each pass.
    pub verify_before_all: bool,
    /// If true, verify the IR after running each pass.
    pub verify_after_all: bool,
    /// Set of pass names for which to verify the IR before execution.
    pub verify_before: HSet<String>,
    /// Set of pass names for which to verify the IR after execution.
    pub verify_after: HSet<String>,
    /// If true, time the execution of each pass.
    pub time_all_passes: bool,
    /// Set of pass names for which to time the execution.
    pub time_passes: HSet<String>,
    /// Set of pass names to skip execution.
    pub skip_passes: HSet<String>,
    /// Custom configuration for extensibility.
    pub custom_config: HMap<Identifier, Box<dyn core::any::Any>>,
}

/// Internal state maintained across [PassManager]s.
/// For use by [PassManager] implementations and not by passes themselves.
#[derive(Default)]
pub struct PMState {
    /// Statistics reported by passes, keyed by pass name.
    /// These statistics are printed (as requested in [PMConfig])
    /// at the end of a pass.
    pub stats: IMap<&'static str, Box<dyn Printable>>,
    /// Custom state for extensibility.
    pub custom_state: HMap<Identifier, Box<dyn core::any::Any>>,
    /// A count of the number of non-manager passes run so far
    pub pass_run_count: usize,
}

/// Common data across [PassManager]s stored in [AnalysisManager].
#[derive(Default)]
pub struct PMData {
    /// Configuration for any [PassManager].
    config: PMConfig,
    /// Internal state across any [PassManager].
    state: PMState,
}

impl PMData {
    /// Get a reference to the [PMConfig].
    pub fn config(&self) -> &PMConfig {
        &self.config
    }

    /// Set [PMConfig]
    pub fn set_config(&mut self, config: PMConfig) {
        self.config = config;
    }

    /// Get a reference to the internal state.
    pub fn state(&self) -> &PMState {
        &self.state
    }

    /// Get a mutable reference to the internal state.
    pub fn state_mut(&mut self) -> &mut PMState {
        &mut self.state
    }
}

/// An analysis is any code that computes information
/// about an [Operation] without modifying the IR.
pub trait Analysis: Downcast {
    /// Name of this analysis.
    fn name(&self) -> &str;
    /// Compute this analysis for a given [Operation].
    fn compute(op: Ptr<Operation>, ctx: &Context, analyses: &mut AnalysisManager) -> Result<Self>
    where
        Self: Sized;
}
impl_downcast!(Analysis);

/// An [Analysis] together with the [Operation] it is computed for.
/// Used as a key in the [AnalysisManager] cache.
type AnalysisManagerKey = (core::any::TypeId, Ptr<Operation>);

#[derive(Default)]
/// A manager for analyses, responsible for caching and invalidating them.
pub struct AnalysisManager {
    /// Common data across [PassManager]s.
    pub pm_data: PMData,
    /// Cached analyses keyed by (TypeId of the analysis, Operation).
    analyses: IMap<AnalysisManagerKey, Box<RefCell<dyn Analysis>>>,
}

impl AnalysisManager {
    /// Compute (if not already cached) and cache an analysis `A` for [Operation] `op`.
    pub fn compute_analysis<A: Analysis + 'static>(
        &mut self,
        op: Ptr<Operation>,
        ctx: &Context,
    ) -> Result<()> {
        let key = (core::any::TypeId::of::<A>(), op);
        if !self.analyses.contains_key(&key) {
            let analysis = A::compute(op, ctx, self)?;
            self.analyses.insert(key, Box::new(RefCell::new(analysis)));
        }
        Ok(())
    }

    /// Get [RefMut] for analysis `A`, computing it if not cached.
    pub fn get_analysis_mut<'a, A: Analysis + 'static>(
        &'a mut self,
        op: Ptr<Operation>,
        ctx: &Context,
    ) -> Result<RefMut<'a, A>> {
        self.compute_analysis::<A>(op, ctx)?;
        let key = (core::any::TypeId::of::<A>(), op);
        let analysis = self.analyses.get(&key).unwrap();
        Ok(RefMut::map(analysis.borrow_mut(), |a| {
            a.downcast_mut::<A>().unwrap()
        }))
    }

    /// Get [Ref] for analysis `A`, computing it if not cached.
    pub fn get_analysis<'a, A: Analysis + 'static>(
        &'a mut self,
        op: Ptr<Operation>,
        ctx: &Context,
    ) -> Result<Ref<'a, A>> {
        self.compute_analysis::<A>(op, ctx)?;
        let key = (core::any::TypeId::of::<A>(), op);
        let analysis = self.analyses.get(&key).unwrap();
        Ok(Ref::map(analysis.borrow(), |a| {
            a.downcast_ref::<A>().unwrap()
        }))
    }

    /// Get, if cached, [Ref] for analysis `A`.
    pub fn try_get_analysis<'a, A: Analysis + 'static>(
        &'a self,
        op: Ptr<Operation>,
    ) -> Option<Ref<'a, A>> {
        let key = (core::any::TypeId::of::<A>(), op);
        self.analyses
            .get(&key)
            .map(|analysis| Ref::map(analysis.borrow(), |a| a.downcast_ref::<A>().unwrap()))
    }

    /// Get, if cached, [RefMut] for analysis `A`.
    pub fn try_get_analysis_mut<'a, A: Analysis + 'static>(
        &'a self,
        op: Ptr<Operation>,
    ) -> Option<RefMut<'a, A>> {
        let key = (core::any::TypeId::of::<A>(), op);
        self.analyses
            .get(&key)
            .map(|analysis| RefMut::map(analysis.borrow_mut(), |a| a.downcast_mut::<A>().unwrap()))
    }

    /// Retain only analyses that are preserved by a [PassResult].
    pub fn retain_preserved(&mut self, pass_res: &PassResult) {
        if pass_res.ir_changed == IRStatus::Unchanged {
            return;
        }
        self.analyses
            .retain(|(type_id, _), _| pass_res.preserved_analyses.contains(type_id));
    }

    /// Get a list of all analyses currently cached.
    fn list_analyses(&self) -> HSet<core::any::TypeId> {
        self.analyses.keys().map(|(type_id, _)| *type_id).collect()
    }

    /// Set [PMConfig]
    pub fn set_config(&mut self, config: PMConfig) {
        self.pm_data.set_config(config);
    }

    /// Get a reference to pass manager related data
    pub fn pm_data(&self) -> &PMData {
        &self.pm_data
    }

    /// Get a mutable reference to pass manager related data
    pub fn pm_data_mut(&mut self) -> &mut PMData {
        &mut self.pm_data
    }
}

#[derive(Debug, Error)]
pub enum PrintOpToFileErr {
    #[error("Failed to write to file {}: {}", .0.display(), .1)]
    FileWriteError(std_deps::path::PathBuf, std_deps::io::Error),
    #[error("Failed to create directory {}: {}", .0.display(), .1)]
    DirCreateError(std_deps::path::PathBuf, std_deps::io::Error),
}

/// Print `op` to file `dir/file_name`.
/// Creates `dir` (including parents) if it doesn't exist.
fn print_op_to_file(
    ctx: &Context,
    dir: &PathBuf,
    file_name: String,
    op: Ptr<Operation>,
) -> Result<()> {
    create_dir_all(dir)
        .map_err(|err| arg_error_noloc!(PrintOpToFileErr::DirCreateError(dir.clone(), err)))?;
    let path = dir.join(file_name);
    write(&path, op.disp(ctx).to_string().as_bytes())
        .map_err(|err| arg_error_noloc!(PrintOpToFileErr::FileWriteError(path, err)))
}