charon_lib/transform/resugar/
reconstruct_static_accesses.rs1use rustc_hash::FxHashMap as HashMap;
7
8use crate::transform::TransformCtx;
9use crate::transform::ctx::UllbcPass;
10use crate::ullbc_ast::*;
11
12struct StaticInfo {
14 global: GlobalDeclRef,
15 assign_loc: StmtLoc,
16 uses: usize,
17 derefs: usize,
18}
19
20pub struct Transform;
21impl UllbcPass for Transform {
22 fn transform_body(&self, ctx: &mut TransformCtx, body: &mut ExprBody) {
23 let mut statics: HashMap<LocalId, StaticInfo> = body
25 .body
26 .iter_enumerated()
27 .flat_map(|(block_id, block)| {
28 let locs = (0..).map(move |i| StmtLoc::new(block_id, i));
29 locs.zip(&block.statements)
30 })
31 .filter_map(|(loc, st)| {
32 let (dest, rvalue) = &st.kind.as_assign()?;
33 let local = dest
34 .as_local()
35 .filter(|l| !body.locals.is_return_or_arg(*l))?;
36 let global = match rvalue {
39 Rvalue::Use(Operand::Const(c), _)
40 if let ConstantExprKind::Ptr(_, pointee, _) = c.kind()
41 && let GlobalPlaceKind::Global(GlobalProvenance::Global(global)) =
42 &pointee.kind =>
43 {
44 global
45 }
46 Rvalue::RawPtr { place, .. } => place.kind.as_global()?,
48 _ => return None,
49 };
50 let decl = ctx.translated.global_decls.get(global.id)?;
51 if !matches!(decl.global_kind, GlobalKind::Static { .. }) {
52 return None;
53 }
54 let info = StaticInfo {
55 global: global.clone(),
56 assign_loc: loc,
57 uses: 0,
58 derefs: 0,
59 };
60 Some((local, info))
61 })
62 .collect();
63 body.locals.dyn_visit_in_body(|place: &Place| {
65 if let Some(local) = place.as_local() {
66 statics.remove(&local);
67 }
68 });
69 if statics.is_empty() {
70 return;
71 }
72
73 body.body.dyn_visit_in_body(|place: &Place| {
76 if let Some(local) = place.as_local()
77 && let Some(info) = statics.get_mut(&local)
78 {
79 info.uses += 1;
80 } else if let Some((sub, ProjectionElem::Deref)) = place.as_projection()
81 && let Some(local) = sub.as_local()
82 && let Some(info) = statics.get_mut(&local)
83 {
84 info.derefs += 1;
85 }
86 });
87 statics.retain(|_, info| info.uses == info.derefs + 1);
88 if statics.is_empty() {
89 return;
90 }
91
92 for info in statics.values() {
94 body[info.assign_loc].kind = StatementKind::Nop;
95 }
96 body.body.dyn_visit_in_body_mut(|place: &mut Place| {
98 if let Some((sub, ProjectionElem::Deref)) = place.as_projection()
99 && let Some(local) = sub.as_local()
100 && let Some(info) = statics.get(&local)
101 {
102 *place = Place::new_global(info.global.clone(), place.ty.clone());
103 }
104 });
105 }
106}