1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use std::{
collections::{HashMap, HashSet},
fmt::{self, Display},
mem,
};
use indexmap::IndexMap;
use log::debug;
use crate::{
expr::{Expr, VarId},
simplify::simplify_mba,
};
/// A single instruction defining variable [`Insn::id`].
#[derive(Debug, PartialEq, Eq)]
pub struct Insn {
/// The variable this instruction defines.
pub id: VarId,
/// The bit width of the defined variable.
pub ty: u8,
/// How the variable's value is produced.
pub kind: InsnKind,
}
impl Display for Insn {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
InsnKind::Unknown(args) => f.write_fmt(format_args!(
"u{} v{} = unknown({})",
self.ty,
self.id,
args.iter()
.map(|v| format!("v{}", v))
.collect::<Vec<String>>()
.join(",")
)),
InsnKind::Assign(e) => f.write_fmt(format_args!(
"u{} v{} = {}",
self.ty,
self.id,
e.repr(self.ty, false, false)
)),
}
}
}
/// How an [`Insn`] computes its variable's value.
#[derive(Debug, PartialEq, Eq)]
pub enum InsnKind {
/// The variable is assigned the value of an expression.
Assign(Expr),
/// The variable is an opaque function of the given operands.
Unknown(Vec<VarId>),
}
type Uses = HashSet<VarId>;
/// A sequence of [`Insn`]s together with their use graph.
#[derive(Debug)]
pub struct Program {
insns: IndexMap<VarId, Insn>,
users: HashMap<VarId, Uses>,
}
impl Display for Program {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (_, insn) in &self.insns {
f.write_fmt(format_args!("{}\n", insn))?;
}
Ok(())
}
}
impl<'a> IntoIterator for &'a Program {
type Item = &'a Insn;
type IntoIter = indexmap::map::Values<'a, VarId, Insn>;
fn into_iter(self) -> Self::IntoIter {
self.insns.values()
}
}
impl Default for Program {
fn default() -> Self {
Self {
insns: IndexMap::new(),
users: HashMap::new(),
}
}
}
macro_rules! Errf {
($($arg:tt)*) => {
Err(format!($($arg)*))
};
}
/// A Rumba IR program
impl Program {
fn get_mut_uses(&mut self, caller: VarId, var: VarId) -> Result<&mut Uses, String> {
self.users.get_mut(&var).ok_or(format!(
"ERROR[v{}] Variable {} is not defined",
caller, var
))
}
fn get_insn(&self, caller: VarId, id: VarId) -> Result<&Insn, String> {
self.insns
.get(&id)
.ok_or(format!("ERROR[v{}] Instruction {} is missing", caller, id))
}
/// Adds the uses of a instruction into the program
fn add_uses(&mut self, insn: &Insn) -> Result<(), String> {
let id = insn.id;
let mut add_use = |var: VarId| -> Result<(), String> {
let uses = self.get_mut_uses(id, var)?;
uses.insert(id);
Ok(())
};
match &insn.kind {
InsnKind::Unknown(args) => {
for arg in args {
add_use(*arg)?;
}
}
InsnKind::Assign(expr) => {
let vars = expr.get_vars();
for var in vars {
add_use(var)?;
}
}
}
Ok(())
}
/// Adds the definition of an instruction into the program
fn add_def(&mut self, insn: &Insn) -> Result<(), String> {
if self.users.insert(insn.id, HashSet::new()).is_some() {
return Errf!("Redeclaring previously declared var: v{}", insn.id);
}
Ok(())
}
/// The number of instructions in the program.
pub fn len(&self) -> usize {
self.insns.len()
}
/// Whether the program has no instructions.
pub fn is_empty(&self) -> bool {
self.insns.is_empty()
}
/// The instruction at position `index` in program order, if any.
pub fn get_index(&self, index: usize) -> Option<&Insn> {
self.insns.get_index(index).map(|(_, insn)| insn)
}
/// Adds an instruction at the end of the current program
pub fn push(&mut self, insn: Insn) -> Result<(), String> {
// Updates the users
self.add_uses(&insn)?;
// Update the defs and creates an empty uses set
self.add_def(&insn)?;
self.insns.insert(insn.id, insn);
Ok(())
}
/// Adds multiple instructions at the end of the current program
pub fn append(&mut self, insns: Vec<Insn>) -> Result<(), String> {
for insn in insns {
self.push(insn)?;
}
Ok(())
}
/// Removes an unused assignement instruction
fn remove(&mut self, id: VarId) -> Result<(), String> {
let e = match self
.insns
.shift_remove(&id)
.ok_or(format!(
"Attempting to remove instruction with id `{}` which does not exist!",
id
))?
.kind
{
InsnKind::Assign(e) => e,
_ => {
return Errf!("Attempting to remove an unknown instruction: v{}", id);
}
};
// Verifies this instruction was indeed unused
if cfg!(debug_assertions) && self.users.get(&id).is_none_or(|uses| !uses.is_empty()) {
return Errf!("Attempting to remove v{} which is still used", id);
}
self.users.remove(&id);
// Remove this instruction's uses
let vars = e.get_vars();
for var in vars {
let uses = self.get_mut_uses(id, var)?;
uses.remove(&id);
}
Ok(())
}
/// Removes all unused assignements
fn remove_dead(&mut self) -> Result<(), String> {
loop {
let mut queue = vec![];
for (id, insn) in &self.insns {
if matches!(&insn.kind, InsnKind::Assign(_))
&& self.users.get(id).is_none_or(|uses| uses.is_empty())
{
queue.push(*id);
}
}
if queue.is_empty() {
break;
}
for id in queue {
self.remove(id)?;
}
}
Ok(())
}
/// Attempts to simplify the given instruction
/// This only works on assignements
fn simplify_insn(&mut self, insn: &mut Insn) -> Result<(), String> {
let e = match &mut insn.kind {
InsnKind::Assign(e) => e,
_ => {
return Ok(());
}
};
let id = insn.id;
// Take ownership of the expression
let mut expr = mem::replace(e, Expr::zero());
let vars = expr.get_vars();
for var in vars {
// Replace variables by their expressions if we know their values
let insn = self.get_insn(id, var)?;
if let InsnKind::Assign(replacement) = &insn.kind {
// TODO: handle operations between varaibles of different sizes
expr = expr.replace_var(var, replacement);
}
// Removes this use, we will add all remaining uses after we modifying the expression
let uses = self.get_mut_uses(id, var)?;
uses.remove(&id);
}
// Simplify the expression. A region the solver rejects keeps its
// original expression rather than failing the whole program.
*e = match simplify_mba(expr.clone(), insn.ty) {
Ok(simplified) => simplified,
Err(err) => {
debug!("leaving {expr} unsimplified: {err}");
expr
}
};
// Update this instruction's uses
for var in e.get_vars() {
let uses = self.get_mut_uses(id, var)?;
uses.insert(id);
}
Ok(())
}
/// Simplifies the given program
pub fn simplify(&mut self) -> Result<(), String> {
let insns = std::mem::take(&mut self.insns);
for (id, mut insn) in insns {
self.simplify_insn(&mut insn)?;
self.insns.insert(id, insn);
}
self.remove_dead()?;
Ok(())
}
}