charon_lib/transform/
mod.rs

1pub mod check_generics;
2pub mod compute_short_names;
3pub mod ctx;
4pub mod duplicate_defaulted_methods;
5pub mod duplicate_return;
6pub mod expand_associated_types;
7pub mod filter_invisible_trait_impls;
8pub mod filter_unreachable_blocks;
9pub mod graphs;
10pub mod hide_marker_traits;
11pub mod index_intermediate_assigns;
12pub mod index_to_function_calls;
13pub mod inline_local_panic_functions;
14pub mod inline_promoted_consts;
15pub mod insert_assign_return_unit;
16pub mod insert_storage_lives;
17pub mod lift_associated_item_clauses;
18pub mod merge_goto_chains;
19pub mod monomorphize;
20pub mod ops_to_function_calls;
21pub mod prettify_cfg;
22pub mod reconstruct_asserts;
23pub mod reconstruct_boxes;
24pub mod recover_body_comments;
25pub mod remove_drop_never;
26pub mod remove_dynamic_checks;
27pub mod remove_nops;
28pub mod remove_read_discriminant;
29pub mod remove_unit_locals;
30pub mod remove_unused_locals;
31pub mod remove_unused_methods;
32pub mod remove_unused_self_clause;
33pub mod reorder_decls;
34pub mod simplify_constants;
35pub mod skip_trait_refs_when_known;
36pub mod ullbc_to_llbc;
37pub mod unbind_item_vars;
38pub mod update_block_indices;
39pub mod utils;
40
41pub use ctx::TransformCtx;
42use ctx::{LlbcPass, TransformPass, UllbcPass};
43use Pass::*;
44
45/// Item and type cleanup passes.
46pub static INITIAL_CLEANUP_PASSES: &[Pass] = &[
47    // Compute short names
48    NonBody(&compute_short_names::Transform),
49    // Remove the trait/impl methods that were not translated (because not used).
50    NonBody(&remove_unused_methods::Transform),
51    // Move clauses on associated types to be parent clauses
52    NonBody(&lift_associated_item_clauses::Transform),
53    // Check that all supplied generic types match the corresponding generic parameters.
54    // Needs `lift_associated_item_clauses`.
55    NonBody(&check_generics::Check("after translation")),
56    // # Micro-pass: hide some overly-common traits we don't need: Sized, Sync, Allocator, etc..
57    NonBody(&hide_marker_traits::Transform),
58    // # Micro-pass: filter the trait impls that were marked invisible since we couldn't filter
59    // them out earlier.
60    NonBody(&filter_invisible_trait_impls::Transform),
61    // # Micro-pass: remove the explicit `Self: Trait` clause of methods/assoc const declaration
62    // items if they're not used. This simplifies the graph of dependencies between definitions.
63    NonBody(&remove_unused_self_clause::Transform),
64    // Add missing methods to trait impls by duplicating the default method.
65    NonBody(&duplicate_defaulted_methods::Transform),
66    // # Micro-pass: whenever we call a trait method on a known type, refer to the method `FunDecl`
67    // directly instead of going via a `TraitRef`. This is done before `reorder_decls` to remove
68    // some sources of mutual recursion.
69    UnstructuredBody(&skip_trait_refs_when_known::Transform),
70    // Change trait associated types to be type parameters instead. See the module for details.
71    NonBody(&expand_associated_types::Transform),
72];
73
74/// Body cleanup passes on the ullbc.
75pub static ULLBC_PASSES: &[Pass] = &[
76    // Inline promoted consts into their parent bodies.
77    UnstructuredBody(&inline_promoted_consts::Transform),
78    // # Micro-pass: merge single-origin gotos into their parent. This drastically reduces the
79    // graph size of the CFG.
80    UnstructuredBody(&merge_goto_chains::Transform),
81    // # Micro-pass: Remove overflow/div-by-zero/bounds checks since they are already part of the
82    // arithmetic/array operation in the semantics of (U)LLBC.
83    // **WARNING**: this pass uses the fact that the dynamic checks introduced by Rustc use a
84    // special "assert" construct. Because of this, it must happen *before* the
85    // [reconstruct_asserts] pass. See the comments in [crate::remove_dynamic_checks].
86    // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
87    // it must happen before passes that insert statements like [simplify_constants].
88    UnstructuredBody(&remove_dynamic_checks::Transform),
89    // # Micro-pass: reconstruct the special `Box::new` operations inserted e.g. in the `vec![]`
90    // macro.
91    // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
92    // it must happen before passes that insert statements like [simplify_constants].
93    // **WARNING**: this pass works across calls, hence must happen after `merge_goto_chains`,
94    UnstructuredBody(&reconstruct_boxes::Transform),
95    // # Micro-pass: desugar the constants to other values/operands as much
96    // as possible.
97    UnstructuredBody(&simplify_constants::Transform),
98    // # Micro-pass: make sure the block ids used in the ULLBC are consecutive
99    UnstructuredBody(&update_block_indices::Transform),
100    // # Micro-pass: reconstruct the asserts
101    UnstructuredBody(&reconstruct_asserts::Transform),
102    // # Micro-pass: duplicate the return blocks
103    UnstructuredBody(&duplicate_return::Transform),
104    // # Micro-pass: filter the "dangling" blocks. Those might have been introduced by,
105    // for instance, [`reconstruct_asserts`].
106    UnstructuredBody(&filter_unreachable_blocks::Transform),
107    // # Micro-pass: `panic!()` expands to a new function definition each time. This pass cleans
108    // those up.
109    UnstructuredBody(&inline_local_panic_functions::Transform),
110    // # Micro-pass: introduce intermediate assignments in preparation of the
111    // [`index_to_function_calls`] pass.
112    UnstructuredBody(&index_intermediate_assigns::Transform),
113    // # Micro-pass: add the missing assignments to the return value.
114    // When the function return type is unit, the generated MIR doesn't
115    // set the return value to `()`. This can be a concern: in the case
116    // of Aeneas, it means the return variable contains ⊥ upon returning.
117    // For this reason, when the function has return type unit, we insert
118    // an extra assignment just before returning.
119    UnstructuredBody(&insert_assign_return_unit::Transform),
120    // # Micro-pass: remove locals of type `()` which show up a lot.
121    UnstructuredBody(&remove_unit_locals::Transform),
122    // # Micro-pass: remove the drops of locals whose type is `Never` (`!`). This
123    // is in preparation of the next transformation.
124    UnstructuredBody(&remove_drop_never::Transform),
125];
126
127/// Body cleanup passes after control flow reconstruction.
128pub static LLBC_PASSES: &[Pass] = &[
129    // # Go from ULLBC to LLBC (Low-Level Borrow Calculus) by reconstructing the control flow.
130    NonBody(&ullbc_to_llbc::Transform),
131    // # Micro-pass: replace some unops/binops and the array aggregates with
132    // function calls (introduces: ArrayToSlice, etc.)
133    StructuredBody(&ops_to_function_calls::Transform),
134    // # Micro-pass: replace the arrays/slices index operations with function
135    // calls.
136    // (introduces: ArrayIndexShared, ArrayIndexMut, etc.)
137    StructuredBody(&index_to_function_calls::Transform),
138    // # Micro-pass: Remove the discriminant reads (merge them with the switches)
139    StructuredBody(&remove_read_discriminant::Transform),
140    // Cleanup the cfg.
141    StructuredBody(&prettify_cfg::Transform),
142];
143
144/// Cleanup passes useful for both llbc and ullbc.
145pub static SHARED_FINALIZING_PASSES: &[Pass] = &[
146    // # Micro-pass: remove the locals which are never used.
147    NonBody(&remove_unused_locals::Transform),
148    // Insert storage lives for locals that are always allocated at the beginning of the function.
149    NonBody(&insert_storage_lives::Transform),
150    // # Micro-pass: remove the useless `StatementKind::Nop`s.
151    NonBody(&remove_nops::Transform),
152    // Monomorphize the functions and types.
153    NonBody(&monomorphize::Transform),
154    // # Micro-pass: take all the comments found in the original body and assign them to
155    // statements. This must be last after all the statement-affecting passes to avoid losing
156    // comments.
157    NonBody(&recover_body_comments::Transform),
158    // # Reorder the graph of dependencies and compute the strictly connex components to:
159    // - compute the order in which to extract the definitions
160    // - find the recursive definitions
161    // - group the mutually recursive definitions
162    NonBody(&reorder_decls::Transform),
163];
164
165/// Final passes to run at the end, after pretty-printing the llbc if applicable. These are only
166/// split from the above list to get test outputs even when generics fail to match.
167pub static FINAL_CLEANUP_PASSES: &[Pass] = &[
168    // Check that all supplied generic types match the corresponding generic parameters.
169    NonBody(&check_generics::Check("after transformations")),
170    // Use `DeBruijnVar::Free` for the variables bound in item signatures.
171    NonBody(&unbind_item_vars::Check),
172];
173
174#[derive(Clone, Copy)]
175pub enum Pass {
176    NonBody(&'static dyn TransformPass),
177    UnstructuredBody(&'static dyn UllbcPass),
178    StructuredBody(&'static dyn LlbcPass),
179}
180
181impl Pass {
182    pub fn run(self, ctx: &mut TransformCtx) {
183        match self {
184            NonBody(pass) => pass.transform_ctx(ctx),
185            UnstructuredBody(pass) => pass.transform_ctx(ctx),
186            StructuredBody(pass) => pass.transform_ctx(ctx),
187        }
188    }
189
190    pub fn name(&self) -> &str {
191        match self {
192            NonBody(pass) => pass.name(),
193            UnstructuredBody(pass) => pass.name(),
194            StructuredBody(pass) => pass.name(),
195        }
196    }
197}
198
199pub struct PrintCtxPass {
200    pub message: String,
201    /// Whether we're printing to stdout or only logging.
202    pub to_stdout: bool,
203}
204
205impl PrintCtxPass {
206    pub fn new(to_stdout: bool, message: String) -> &'static Self {
207        let ret = Self { message, to_stdout };
208        Box::leak(Box::new(ret))
209    }
210}
211
212impl TransformPass for PrintCtxPass {
213    fn transform_ctx(&self, ctx: &mut TransformCtx) {
214        let message = &self.message;
215        if self.to_stdout {
216            println!("{message}:\n\n{ctx}\n");
217        } else {
218            trace!("{message}:\n\n{ctx}\n");
219        }
220    }
221}