Skip to main content

charon_lib/transform/
mod.rs

1pub mod ctx;
2pub mod typecheck_and_unify;
3pub mod utils;
4
5/// Passes that finish translation, i.e. required for the output to be a valid output.
6pub mod finish_translation {
7    pub mod filter_invisible_trait_impls;
8    pub mod insert_assign_return_unit;
9    pub mod insert_ptr_metadata;
10    pub mod insert_storage_statements;
11}
12
13/// Passes that compute extra info to be stored in the crate.
14pub mod add_missing_info {
15    pub mod add_implied_outlives;
16    pub mod add_missing_alias_clauses;
17    pub mod compute_layout_guarantees;
18    pub mod compute_short_names;
19    pub mod link_specs;
20    pub mod recover_body_comments;
21    pub mod reorder_decls;
22    pub mod sccs;
23}
24
25/// Passes that effect some kind of normalization on the crate.
26pub mod normalize {
27    pub mod desugar_drops;
28    pub mod expand_associated_types;
29    pub mod filter_unreachable_blocks;
30    pub mod normalize_trait_refs;
31    pub mod partial_monomorphization;
32    pub mod skip_trait_refs_when_known;
33    pub mod transform_dyn_trait_calls;
34}
35
36/// Passes that undo some lowering done by rustc to recover an operation closer to what the user
37/// wrote.
38pub mod resugar {
39    pub mod move_asserts_to_statements;
40    pub mod reconstruct_asserts;
41    pub mod reconstruct_box_derefs;
42    pub mod reconstruct_fallible_operations;
43    pub mod reconstruct_intrinsics;
44    pub mod reconstruct_matches;
45    pub mod reconstruct_vec_boxes;
46}
47
48/// Passes that make the output simpler/easier to consume.
49pub mod simplify_output {
50    pub mod anon_const_to_call;
51    pub mod builtins_to_function_calls;
52    pub mod duplicate_defaulted_methods;
53    pub mod filter_trivial_drops;
54    pub mod hide_allocator_param;
55    pub mod index_intermediate_assigns;
56    pub mod inline_selected_functions;
57    pub mod lift_associated_item_clauses;
58    pub mod remove_adt_clauses;
59    pub mod remove_nops;
60    pub mod remove_unit_locals;
61    pub mod remove_unused_clauses;
62    pub mod remove_unused_locals;
63    pub mod simplify_constants;
64    pub mod unbind_item_vars;
65    pub mod update_block_indices;
66}
67
68/// Passes that manipulate the control flow and reconstruct its structure.
69pub mod control_flow {
70    pub mod duplicate_return;
71    pub mod merge_goto_chains;
72    pub mod prettify_cfg;
73    pub mod ullbc_to_llbc;
74}
75
76pub use ctx::TransformCtx;
77use ctx::{LlbcPass, TransformPass, UllbcPass};
78
79use crate::options::CliOpts;
80
81/// Shorten a pass name for display: `charon_lib::transform::foo::bar::Transform` -> `foo::bar`.
82fn short_pass_name(name: &str) -> String {
83    let name = name.strip_prefix("charon_lib::transform::").unwrap_or(name);
84    let name = name.strip_suffix("::Transform").unwrap_or(name);
85    name.to_owned()
86}
87
88/// Run transformation passes on the crate before outputting it.
89pub fn run_transformation_passes(options: &CliOpts, ctx: &mut TransformCtx) {
90    // Passes that apply to the whole crate at once, typically those that change item signatures.
91    let global = |x| Pass::NonBody(CowBox::Borrowed(x));
92    // Passes that apply to bodies but work on either kind.
93    let mixed_body = |x| Pass::NonBody(CowBox::Borrowed(x));
94
95    ctx.run_pass(Pass::NonBody(PrintCtxPass::new(
96        options.print_original_ullbc,
97        "# ULLBC after translation from MIR".to_string(),
98    )));
99
100    // Item and type cleanup passes.
101    ctx.run_passes([
102        // Link specification items and the items they specify in both directions.
103        global(&add_missing_info::link_specs::Transform),
104        // `--duplicate-defaulted-methods`: copy default method bodies into impls that use them.
105        global(&simplify_output::duplicate_defaulted_methods::Transform),
106        // Compute short names. We do it early to make pretty-printed output more legible in traces.
107        global(&add_missing_info::compute_short_names::Transform),
108        // Check that translation emitted consistent types, and unify body lifetimes (best-effort).
109        global(&typecheck_and_unify::Check::PostTranslation),
110        // Filter the trait impls that were marked invisible since we couldn't filter them out
111        // earlier.
112        global(&finish_translation::filter_invisible_trait_impls::Transform),
113        // Move clauses on associated types to be implied clauses of the trait.
114        global(&simplify_output::lift_associated_item_clauses::Transform),
115        // Type aliases may use associated types without declaring the corresponding trait
116        // such missing trait clauses.
117        global(&add_missing_info::add_missing_alias_clauses::Transform),
118        // Make explicit the outlives predicates implied by item signatures.
119        global(&add_missing_info::add_implied_outlives::Transform),
120    ]);
121
122    // Body cleanup passes on the ullbc.
123    let pass = Pass::FusedUnstructuredBody(Box::new([
124        // Compute the metadata & insert for Rvalue
125        CowBox::Borrowed(&finish_translation::insert_ptr_metadata::Transform),
126        // Add the missing assignments to the return value.
127        // When the function return type is unit, the generated MIR doesn't set the return value to
128        // `()`. This can be a concern: in the case of Aeneas, it means the return variable
129        // contains ⊥ upon returning. For this reason, when the function has return type unit, we
130        // insert an extra assignment just before returning.
131        CowBox::Borrowed(&finish_translation::insert_assign_return_unit::Transform),
132        // Insert storage markers for locals that don't have them (that's allowed in MIR).
133        CowBox::Borrowed(&finish_translation::insert_storage_statements::Transform),
134        // Transform Drops into Calls to drop_glue.
135        CowBox::Borrowed(&normalize::desugar_drops::Transform),
136        // Whenever we reference a trait method on a known type, refer to the method `FunDecl`
137        // directly instead of going via a `TraitRef`. This is done before associated-type lifting
138        // because it messes up generic args order.
139        CowBox::Borrowed(&normalize::skip_trait_refs_when_known::Transform),
140        // Transform dyn trait method calls to vtable function pointer calls.
141        // This should be early to handle the calls before other transformations.
142        CowBox::Borrowed(&normalize::transform_dyn_trait_calls::Transform),
143        // Replace promoted and inline consts with calls to their initializers.
144        simplify_output::anon_const_to_call::Transform::new(ctx),
145        // Inline promoted and inline consts, as well as dummy auto-generated panic functions.
146        simplify_output::inline_selected_functions::Transform::new(ctx),
147        // Remove drop statements that are noops.
148        CowBox::Borrowed(&simplify_output::filter_trivial_drops::Transform),
149        // Inline all asserts that correspond to dynamic checks into statements.
150        // The following pass will then merge the generated gotos as part of this substitution,
151        // and [reconstruct_fallible_operations] can then use the inlined asserts to
152        // reconstruct the fallible operations.
153        CowBox::Borrowed(&resugar::move_asserts_to_statements::Transform),
154        // Merge single-origin gotos into their parent. This drastically reduces the graph size
155        // of the CFG.
156        // This must be done early as some resugaring passes depend on it.
157        CowBox::Borrowed(&control_flow::merge_goto_chains::Transform),
158        // Remove overflow/div-by-zero/bounds checks since they are already part of the
159        // arithmetic/array operation in the semantics of (U)LLBC.
160        // **WARNING**: this pass uses the fact that the dynamic checks introduced by Rustc use a
161        // special "assert" construct. Because of this, it must happen *before* the
162        // [reconstruct_asserts] pass. See the comments in [crate::remove_dynamic_checks].
163        // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of this,
164        // it must happen before passes that insert statements like [simplify_constants].
165        CowBox::Borrowed(&resugar::reconstruct_fallible_operations::Transform),
166        // Reconstruct `vec![x]` lowering to avoid unsafe operations.
167        // **WARNING**: this pass relies on a precise structure of the MIR statements. Because of
168        // this, it must happen before passes that insert statements like [simplify_constants].
169        // This must also happen after `inline_selected_functions`, and `merge_goto_chains`.
170        resugar::reconstruct_vec_boxes::Transform::new(ctx),
171        // Resugar the box derefs that got desugared in elaborated MIR.
172        CowBox::Borrowed(&resugar::reconstruct_box_derefs::Transform),
173        // Recognize calls to the `offset_of` intrinsic and replace them with the
174        // corresponding constant expression.
175        CowBox::Borrowed(&resugar::reconstruct_intrinsics::Transform),
176        // Reconstruct the asserts
177        CowBox::Borrowed(&resugar::reconstruct_asserts::Transform),
178        // Desugar the constants to other values/operands as much as possible.
179        CowBox::Borrowed(&simplify_output::simplify_constants::Transform),
180        // Introduce intermediate assignments in preparation of the [`builtins_to_function_calls`]
181        // pass.
182        CowBox::Borrowed(&simplify_output::index_intermediate_assigns::Transform),
183        // Remove locals of type `()` which show up a lot.
184        CowBox::Borrowed(&simplify_output::remove_unit_locals::Transform),
185        // Duplicate the return blocks
186        CowBox::Borrowed(&control_flow::duplicate_return::Transform),
187        // Reconstruct matches on enum variants.
188        resugar::reconstruct_matches::Transform::new(ctx),
189        // Remove the locals which are never used.
190        CowBox::Borrowed(&simplify_output::remove_unused_locals::Transform),
191        // Another round.
192        CowBox::Borrowed(&control_flow::merge_goto_chains::Transform),
193        // Filter the "dangling" blocks. Those might have been introduced by, for instance,
194        // [`merge_goto_chains`].
195        CowBox::Borrowed(&normalize::filter_unreachable_blocks::Transform),
196        // Make sure the block ids used in the ULLBC are consecutive
197        CowBox::Borrowed(&simplify_output::update_block_indices::Transform),
198    ]));
199    ctx.run_pass(pass);
200
201    if !options.ullbc {
202        // If we're reconstructing control-flow, print the ullbc here.
203        ctx.run_pass(Pass::NonBody(PrintCtxPass::new(
204            options.print_ullbc,
205            "# Final ULLBC before control-flow reconstruction".to_string(),
206        )));
207    }
208
209    if !options.ullbc {
210        // Go from ULLBC to LLBC (Low-Level Borrow Calculus) by reconstructing the control flow.
211        ctx.run_pass(mixed_body(&control_flow::ullbc_to_llbc::Transform));
212        // Body cleanup passes after control flow reconstruction.
213        let pass = Pass::FusedStructuredBody(Box::new([
214            // Cleanup the cfg.
215            CowBox::Borrowed(&control_flow::prettify_cfg::Transform),
216            // Replace some operations and array/slice indexing with standard library function
217            // calls.
218            simplify_output::builtins_to_function_calls::Transform::new(ctx),
219        ]));
220        ctx.run_pass(pass);
221    }
222    // Cleanup passes useful for both llbc and ullbc.
223    ctx.run_passes([
224        // Body passes may introduce fresh locals; make their storage markers explicit.
225        mixed_body(&finish_translation::insert_storage_statements::Transform),
226        // Normalize trait refs.
227        global(&normalize::normalize_trait_refs::Transform),
228        // Change trait associated types to be type parameters instead. See the module for details.
229        // This also normalizes any use of an associated type that we can resolve.
230        global(&normalize::expand_associated_types::Transform),
231        // Remove the explicit `Self: Trait` clause of methods/assoc const declaration items if
232        // they're not used. This simplifies the graph of dependencies between definitions.
233        global(&simplify_output::remove_unused_clauses::Transform),
234        // `--remove-adt-clauses`: Remove all trait clauses from type declarations.
235        global(&simplify_output::remove_adt_clauses::Transform),
236        // Remove the locals which are never used.
237        mixed_body(&simplify_output::remove_unused_locals::Transform),
238        // Remove the useless `StatementKind::Nop`s.
239        mixed_body(&simplify_output::remove_nops::Transform),
240        // Take all the comments found in the original body and assign them to statements. This must be
241        // last after all the statement-affecting passes to avoid losing comments.
242        mixed_body(&add_missing_info::recover_body_comments::Transform),
243        // Hide the `A` type parameter on standard library containers (`Box`, `Vec`, etc).
244        global(&simplify_output::hide_allocator_param::Transform),
245        // Partially monomorphize items so that no item is ever instanciated with a mutable reference
246        // or a type containing one.
247        global(&normalize::partial_monomorphization::Transform),
248        // Provide expressions describing the language-guaranteed properties of each type layout.
249        global(&add_missing_info::compute_layout_guarantees::Transform),
250        // Reorder the graph of dependencies and compute the strictly connex components to:
251        // - compute the order in which to extract the definitions
252        // - find the recursive definitions
253        // - group the mutually recursive definitions
254        // This is done last to account for the final item graph, not the initial one.
255        global(&add_missing_info::reorder_decls::Transform),
256        // Check that types are still consistent after the transformation passes.
257        global(&typecheck_and_unify::Check::PostTransformation),
258        // Use `DeBruijnVar::Free` for the variables bound in item signatures.
259        mixed_body(&simplify_output::unbind_item_vars::Check),
260    ]);
261
262    if options.ullbc {
263        // If we're not reconstructing control-flow, print the ullbc after finalizing passes.
264        ctx.run_pass(Pass::NonBody(PrintCtxPass::new(
265            options.print_ullbc,
266            "# Final ULLBC before serialization".to_string(),
267        )));
268    } else {
269        ctx.run_pass(Pass::NonBody(PrintCtxPass::new(
270            options.print_llbc,
271            "# Final LLBC before serialization".to_string(),
272        )));
273    }
274}
275
276pub enum CowBox<T: ?Sized + 'static> {
277    Borrowed(&'static T),
278    Owned(Box<T>),
279}
280
281impl<T: ?Sized + 'static> std::ops::Deref for CowBox<T> {
282    type Target = T;
283    fn deref(&self) -> &Self::Target {
284        match self {
285            CowBox::Borrowed(x) => x,
286            CowBox::Owned(x) => x.as_ref(),
287        }
288    }
289}
290
291pub enum Pass {
292    NonBody(CowBox<dyn TransformPass>),
293    FusedUnstructuredBody(Box<[CowBox<dyn UllbcPass>]>),
294    FusedStructuredBody(Box<[CowBox<dyn LlbcPass>]>),
295}
296
297impl TransformCtx {
298    pub fn run_pass(&mut self, mut pass: Pass) {
299        match &mut pass {
300            Pass::NonBody(pass) => {
301                if pass.should_run(&self.options) {
302                    trace!("# Starting pass {}", pass.name());
303                    let _guard =
304                        crate::timing::scope_lazy("transform", || short_pass_name(pass.name()));
305                    pass.transform_ctx(self)
306                }
307            }
308            Pass::FusedUnstructuredBody(passes) => {
309                // Some passes carry function bodies, which must also be transformed. This applies
310                // all the passes before pass `p` to the bodies potentially carried by pass `p`.
311                for i in 0..passes.len() {
312                    if let (first_passes, [pass, ..]) = passes.split_at_mut(i)
313                        && let CowBox::Owned(pass) = pass
314                    {
315                        pass.apply_preceding_passes(self, first_passes);
316                    }
317                }
318                self.for_each_item_mut(|ctx, mut item| {
319                    for pass in passes.iter() {
320                        if pass.should_run(&ctx.options) {
321                            trace!("# Starting pass {}", pass.name());
322                            let _guard = crate::timing::scope_lazy("transform", || {
323                                short_pass_name(pass.name())
324                            });
325                            pass.transform_item(ctx, item.reborrow());
326                        }
327                    }
328                });
329                for pass in passes.iter() {
330                    if pass.should_run(&self.options) {
331                        pass.finalize(self);
332                    }
333                }
334            }
335            Pass::FusedStructuredBody(passes) => {
336                self.for_each_fun_decl(|ctx, decl| {
337                    for pass in passes.iter() {
338                        if pass.should_run(&ctx.options) {
339                            trace!("# Starting pass {}", pass.name());
340                            let _guard = crate::timing::scope_lazy("transform", || {
341                                short_pass_name(pass.name())
342                            });
343                            pass.transform_function(ctx, decl);
344                        }
345                    }
346                });
347            }
348        };
349    }
350    pub fn run_passes(&mut self, passes: impl IntoIterator<Item = Pass>) {
351        for pass in passes {
352            self.run_pass(pass);
353        }
354    }
355}
356
357pub struct PrintCtxPass {
358    pub message: String,
359    /// Whether we're printing to stdout or only logging.
360    pub to_stdout: bool,
361}
362
363impl PrintCtxPass {
364    pub fn new(to_stdout: bool, message: String) -> CowBox<dyn TransformPass> {
365        let ret = Self { message, to_stdout };
366        CowBox::Owned(Box::new(ret))
367    }
368}
369
370impl TransformPass for PrintCtxPass {
371    fn transform_ctx(&self, ctx: &mut TransformCtx) {
372        let message = &self.message;
373        if self.to_stdout {
374            println!("{message}:\n\n{ctx}\n");
375        } else {
376            trace!("{message}:\n\n{ctx}\n");
377        }
378    }
379}