Skip to main content

wasi_virt_layer_cli/
instrs.rs

1use eyre::Context as _;
2use walrus::ir::*;
3use walrus::*;
4
5/// Trait for rewriting or modifying instructions sequentially in a local function.
6pub trait InstrRewrite {
7    // todo!(); Change it to match "read"
8    /// Rewrites instructions using a callback that returns `T`, tracking sequence IDs.
9    fn rewrite<T>(
10        &mut self,
11        find: impl FnMut(&mut Instr, (usize, InstrSeqId)) -> T,
12    ) -> eyre::Result<Vec<T>>;
13
14    /// Retains instructions that match the specified callback condition.
15    fn retain(&mut self, keep: impl FnMut(&Instr, (usize, InstrSeqId)) -> bool);
16}
17
18/// Trait for reading instructions sequentially in a local function without modifying them.
19pub trait InstrRead {
20    /// Reads and iterates over instructions using a callback, tracking sequence IDs.
21    fn read<T>(&self, find: impl FnMut(&Instr, (usize, InstrSeqId)) -> T) -> eyre::Result<Vec<T>>;
22}
23
24impl InstrRead for LocalFunction {
25    fn read<T>(
26        &self,
27        mut find: impl FnMut(&Instr, (usize, InstrSeqId)) -> T,
28    ) -> eyre::Result<Vec<T>> {
29        fn add<'a>(
30            func: &'a LocalFunction,
31            next_instrs: &mut std::collections::VecDeque<(InstrSeqId, &'a Instr, usize)>,
32            id: InstrSeqId,
33        ) -> eyre::Result<()> {
34            for (i, (blk_id, _)) in func.block(id).instrs.iter().enumerate() {
35                next_instrs.push_back((id, blk_id, i));
36            }
37            Ok(())
38        }
39
40        let mut visited_instrs = vec![];
41        let mut next_instrs = std::collections::VecDeque::new();
42        let mut ret = vec![];
43
44        add(self, &mut next_instrs, self.entry_block())?;
45
46        while let Some((blk_id, instr, instr_idx)) = next_instrs.pop_front() {
47            if visited_instrs.contains(&(blk_id, instr_idx)) {
48                continue;
49            } else {
50                visited_instrs.push((blk_id, instr_idx));
51            }
52
53            ret.push(find(instr, (instr_idx, blk_id)));
54
55            match instr {
56                Instr::Block(block) => {
57                    add(self, &mut next_instrs, block.seq)?;
58                }
59                Instr::Loop(r#loop) => {
60                    add(self, &mut next_instrs, r#loop.seq)?;
61                }
62                Instr::Br(br) => {
63                    add(self, &mut next_instrs, br.block)?;
64                }
65                Instr::BrIf(br_if) => {
66                    add(self, &mut next_instrs, br_if.block)?;
67                }
68                Instr::IfElse(if_else) => {
69                    add(self, &mut next_instrs, if_else.consequent)?;
70                    add(self, &mut next_instrs, if_else.alternative)?;
71                }
72                Instr::BrTable(br_table) => {
73                    add(self, &mut next_instrs, br_table.default)?;
74                    for block in &br_table.blocks {
75                        add(self, &mut next_instrs, *block)?;
76                    }
77                }
78                _ => {}
79            }
80        }
81
82        Ok(ret)
83    }
84}
85
86fn gen_next_instrs(instr: &Instr, next_instrs: &mut Vec<InstrSeqId>) {
87    match instr {
88        Instr::Block(block) => {
89            next_instrs.push(block.seq);
90        }
91        Instr::Loop(r#loop) => {
92            next_instrs.push(r#loop.seq);
93        }
94        Instr::Br(br) => {
95            next_instrs.push(br.block);
96        }
97        Instr::BrIf(br_if) => {
98            next_instrs.push(br_if.block);
99        }
100        Instr::IfElse(if_else) => {
101            next_instrs.push(if_else.consequent);
102            next_instrs.push(if_else.alternative);
103        }
104        Instr::BrTable(br_table) => {
105            next_instrs.push(br_table.default);
106            next_instrs.extend_from_slice(&br_table.blocks);
107        }
108        _ => {}
109    }
110}
111
112fn rewrite_inner<'a, T>(
113    builder: &mut InstrSeqBuilder<'a>,
114    find: &mut impl FnMut(&mut Instr, (usize, InstrSeqId)) -> T,
115) -> eyre::Result<Vec<T>> {
116    let mut visited_instrs = std::collections::HashSet::new();
117    let mut work_stack = vec![builder.id()];
118    let mut ret = vec![];
119
120    while let Some(seq_id) = work_stack.pop() {
121        if visited_instrs.contains(&seq_id) {
122            continue;
123        }
124        visited_instrs.insert(seq_id);
125
126        let mut next_instrs = vec![];
127        let mut builder_mut = builder.instr_seq(seq_id);
128        let id = builder_mut.id();
129
130        for (i, (instr, _)) in builder_mut.instrs_mut().iter_mut().enumerate() {
131            ret.push(find(instr, (i, id)));
132            gen_next_instrs(instr, &mut next_instrs);
133        }
134
135        // Push child sequences in reverse order to maintain processing order
136        for instr_seq_id in next_instrs.into_iter().rev() {
137            if !visited_instrs.contains(&instr_seq_id) {
138                work_stack.push(instr_seq_id);
139            }
140        }
141    }
142
143    Ok(ret)
144}
145
146fn retain_inner<'a>(
147    builder: &mut InstrSeqBuilder<'a>,
148    keep: &mut impl FnMut(&Instr, (usize, InstrSeqId)) -> bool,
149) -> eyre::Result<()> {
150    let mut visited_instrs = std::collections::HashSet::new();
151    let mut work_stack = vec![builder.id()];
152
153    while let Some(seq_id) = work_stack.pop() {
154        if visited_instrs.contains(&seq_id) {
155            continue;
156        }
157        visited_instrs.insert(seq_id);
158
159        let mut next_instrs = vec![];
160        let mut instr_seq = builder.instr_seq(seq_id);
161        let id = instr_seq.id();
162
163        instr_seq.instrs_mut().retain(|(instr, _)| {
164            let should_keep = keep(instr, (0, id));
165            gen_next_instrs(instr, &mut next_instrs);
166            should_keep
167        });
168
169        // Push child sequences in reverse order to maintain processing order
170        for instr_seq_id in next_instrs.into_iter().rev() {
171            if !visited_instrs.contains(&instr_seq_id) {
172                work_stack.push(instr_seq_id);
173            }
174        }
175    }
176
177    Ok(())
178}
179
180impl<'a> InstrRewrite for InstrSeqBuilder<'a> {
181    fn rewrite<T>(
182        &mut self,
183        mut find: impl FnMut(&mut Instr, (usize, InstrSeqId)) -> T,
184    ) -> eyre::Result<Vec<T>> {
185        rewrite_inner(self, &mut find).wrap_err_with(|| eyre::eyre!("Failed to rewrite instrs"))
186    }
187
188    fn retain(&mut self, mut keep: impl FnMut(&Instr, (usize, InstrSeqId)) -> bool) {
189        retain_inner(self, &mut keep)
190            .wrap_err_with(|| eyre::eyre!("Failed to retain instrs"))
191            .unwrap();
192    }
193}