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
112#[inline(never)]
113fn rewrite_inner<'a, T>(
114    builder: &mut InstrSeqBuilder<'a>,
115    find: &mut impl FnMut(&mut Instr, (usize, InstrSeqId)) -> T,
116    visited_instrs: &mut Vec<InstrSeqId>,
117) -> eyre::Result<Vec<T>> {
118    let mut next_instrs = vec![];
119    let mut ret = vec![];
120
121    let id = builder.id();
122
123    for (i, (instr, _)) in builder.instrs_mut().iter_mut().enumerate() {
124        ret.push(find(instr, (i, id)));
125
126        gen_next_instrs(instr, &mut next_instrs);
127    }
128
129    for instr_seq_id in next_instrs.into_iter() {
130        if visited_instrs.contains(&instr_seq_id) {
131            continue;
132        }
133        visited_instrs.push(instr_seq_id);
134
135        let mut instr_seq = builder.instr_seq(instr_seq_id);
136        ret.extend(rewrite_inner(&mut instr_seq, find, visited_instrs)?);
137    }
138    Ok(ret)
139}
140
141#[inline(never)]
142fn retain_inner<'a>(
143    builder: &mut InstrSeqBuilder<'a>,
144    keep: &mut impl FnMut(&Instr, (usize, InstrSeqId)) -> bool,
145    visited_instrs: &mut Vec<InstrSeqId>,
146) -> eyre::Result<()> {
147    let mut next_instrs = vec![];
148
149    let id = builder.id();
150
151    builder.instrs_mut().retain(|(instr, _)| {
152        let idx = keep(instr, (0, id));
153
154        gen_next_instrs(instr, &mut next_instrs);
155
156        idx
157    });
158
159    for instr_seq_id in next_instrs.into_iter() {
160        if visited_instrs.contains(&instr_seq_id) {
161            continue;
162        }
163        visited_instrs.push(instr_seq_id);
164
165        let mut instr_seq = builder.instr_seq(instr_seq_id);
166        retain_inner(&mut instr_seq, keep, visited_instrs)?;
167    }
168    Ok(())
169}
170
171impl<'a> InstrRewrite for InstrSeqBuilder<'a> {
172    fn rewrite<T>(
173        &mut self,
174        mut find: impl FnMut(&mut Instr, (usize, InstrSeqId)) -> T,
175    ) -> eyre::Result<Vec<T>> {
176        let mut visited_instrs = vec![];
177
178        rewrite_inner(self, &mut find, &mut visited_instrs)
179            .wrap_err_with(|| eyre::eyre!("Failed to rewrite instrs"))
180    }
181
182    fn retain(&mut self, mut keep: impl FnMut(&Instr, (usize, InstrSeqId)) -> bool) {
183        let mut visited_instrs = vec![];
184
185        retain_inner(self, &mut keep, &mut visited_instrs)
186            .wrap_err_with(|| eyre::eyre!("Failed to retain instrs"))
187            .unwrap();
188    }
189}