Skip to main content

charon_lib/transform/simplify_output/
remove_unused_locals.rs

1//! Remove the locals (which are not used for the input arguments) which are
2//! never used in the function bodies.  This is useful to remove the locals with
3//! type `Never`. We actually check that there are no such local variables
4//! remaining afterwards.
5use derive_generic_visitor::Visitor;
6use std::mem;
7use std::ops::ControlFlow::Continue;
8
9use crate::ast::*;
10use crate::ids::IndexVec;
11use crate::transform::TransformCtx;
12use crate::transform::ctx::{TransformPass, UllbcPass};
13
14#[derive(Visitor)]
15struct LocalsUsageVisitor {
16    used_locals: IndexVec<LocalId, bool>,
17}
18
19impl VisitBody for LocalsUsageVisitor {
20    fn enter_local_id(&mut self, lid: &LocalId) {
21        self.used_locals[*lid] = true;
22    }
23    fn visit_local(&mut self, local: &Local) -> ControlFlow<Self::Break> {
24        // Skip the local id.
25        self.visit(&local.borrowck_constraints)?;
26        self.visit(&local.drop_flag_for)
27    }
28    fn visit_llbc_statement(&mut self, st: &llbc_ast::Statement) -> ControlFlow<Self::Break> {
29        match &st.kind {
30            llbc_ast::StatementKind::StorageDead(_) | llbc_ast::StatementKind::StorageLive(_) => {
31                // These statements don't count as a variable use.
32                Continue(())
33            }
34            _ => self.visit_inner(st),
35        }
36    }
37    fn visit_ullbc_statement(&mut self, st: &ullbc_ast::Statement) -> ControlFlow<Self::Break> {
38        match &st.kind {
39            ullbc_ast::StatementKind::StorageDead(_) | ullbc_ast::StatementKind::StorageLive(_) => {
40                // These statements don't count as a variable use.
41                Continue(())
42            }
43            _ => self.visit_inner(st),
44        }
45    }
46}
47
48#[derive(Visitor)]
49struct LocalsRenumberVisitor {
50    ids_map: IndexVec<LocalId, Option<LocalId>>,
51}
52
53impl VisitBodyMut for LocalsRenumberVisitor {
54    fn enter_local_id(&mut self, lid: &mut LocalId) {
55        *lid = self.ids_map[*lid].unwrap();
56    }
57    fn enter_llbc_statement(&mut self, st: &mut llbc_ast::Statement) {
58        match st.kind {
59            llbc_ast::StatementKind::StorageDead(lid)
60            | llbc_ast::StatementKind::StorageLive(lid)
61                if self.ids_map[lid].is_none() =>
62            {
63                st.kind = llbc_ast::StatementKind::Nop;
64            }
65            _ => {}
66        }
67    }
68    fn enter_ullbc_statement(&mut self, st: &mut ullbc_ast::Statement) {
69        match st.kind {
70            ullbc_ast::StatementKind::StorageDead(lid)
71            | ullbc_ast::StatementKind::StorageLive(lid)
72                if self.ids_map[lid].is_none() =>
73            {
74                st.kind = ullbc_ast::StatementKind::Nop;
75            }
76            _ => {}
77        }
78    }
79}
80
81fn remove_unused_locals<Body: BodyVisitable>(body: &mut GExprBody<Body>) {
82    // Compute the set of used locals.
83    // We always register the return variable and the input arguments.
84    let mut visitor = LocalsUsageVisitor {
85        used_locals: body
86            .locals
87            .locals
88            .map_ref(|local| body.locals.is_return_or_arg(local.index)),
89    };
90    body.drive_body(&mut visitor);
91    let used_locals = visitor.used_locals;
92    trace!("used_locals: {:?}", used_locals);
93
94    // Keep only the variables that are used (storage statements don't count) and update their
95    // indices to be contiguous.
96    let mut ids_map: IndexVec<LocalId, Option<LocalId>> = body.locals.locals.map_ref(|_| None);
97    for local in mem::take(&mut body.locals.locals) {
98        if used_locals[local.index] {
99            let old_id = local.index;
100            // The pushed local has the wrong index, which will be fixed by the renumbering pass.
101            let new_id = body.locals.locals.push(local);
102            ids_map[old_id] = Some(new_id);
103        }
104    }
105    trace!("ids_maps: {:?}", ids_map);
106
107    // Update all `LocalId`s.
108    let mut visitor = LocalsRenumberVisitor { ids_map };
109    body.drive_body_mut(&mut visitor);
110}
111
112pub struct Transform;
113impl UllbcPass for Transform {
114    fn transform_body(&self, _ctx: &mut TransformCtx, body: &mut ullbc_ast::ExprBody) {
115        remove_unused_locals(body)
116    }
117}
118impl TransformPass for Transform {
119    fn transform_ctx(&self, ctx: &mut TransformCtx) {
120        ctx.for_each_fun_decl(|_ctx, fun| match &mut fun.body {
121            Body::Unstructured(body) => remove_unused_locals(body),
122            Body::Structured(body) => remove_unused_locals(body),
123            _ => {}
124        });
125    }
126}