vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Variables joined where a copy moves a value from one to the other and
//! their lives do not overlap. Leaving SSA form names each value apart and
//! connects them with copies, as `v4 = v1; ... v1 = v4;` around a loop;
//! when no point needs both, they are one variable, and the copies go.

use std::collections::{HashMap, HashSet};

use vlk_ir::ir::cfg::{live_in, live_out, opaque};
use vlk_ir::ir::visit::statement_registers;
use vlk_ir::ir::{Expr, FunctionIr, Stmt, VARIABLE_BASE};

const MIN_RENDER_COPY_CANDIDATES: usize = 3;

mod pointers;
pub(crate) use pointers::reuse_pointers;

#[derive(Clone, Copy)]
enum CoalesceMode {
    Analysis,
    Rendering,
}

pub fn coalesce_copies(ir: &mut FunctionIr) {
    crate::passes::checked(
        "passes::coalesce::coalesce_copies",
        ir,
        coalesce_copies_unchecked,
    )
}

fn coalesce_copies_unchecked(ir: &mut FunctionIr) {
    let _ = coalesce(ir, CoalesceMode::Analysis, None);
}

/// Joins renderer-created values without moving or removing statements, whose
/// positions still identify the structured nodes that came from them.
pub fn coalesce_render_copies(
    ir: &mut FunctionIr,
    types: &std::collections::BTreeMap<u16, vlk_types::types::CType>,
) -> Option<Vec<Vec<bool>>> {
    if ir.blocks.iter().any(opaque) || !has_compatible_copy_candidate(ir, types) {
        return None;
    }
    let removable = coalesce(ir, CoalesceMode::Rendering, Some(types));
    removable
        .iter()
        .any(|block| block.iter().any(|remove| *remove))
        .then_some(removable)
}

fn has_compatible_copy_candidate(
    ir: &FunctionIr,
    types: &std::collections::BTreeMap<u16, vlk_types::types::CType>,
) -> bool {
    let mut count = 0;
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        let Stmt::Assign { dest, value, .. } = stmt else {
            continue;
        };
        if dest.index < VARIABLE_BASE {
            continue;
        }
        let source = match value {
            Expr::Reg { index, .. } => Some(*index),
            Expr::Bin {
                op: vlk_ir::ir::BinOp::And,
                lhs,
                rhs,
            } => match (lhs.as_ref(), rhs.as_ref()) {
                (Expr::Reg { index, .. }, Expr::Const(_))
                | (Expr::Const(_), Expr::Reg { index, .. }) => Some(*index),
                _ => None,
            },
            _ => None,
        };
        let Some(source) = source else {
            continue;
        };
        if source < VARIABLE_BASE
            || source == dest.index
            || !types
                .get(&dest.index)
                .is_some_and(|ty| types.get(&source) == Some(ty))
        {
            continue;
        }
        count += 1;
        if count == MIN_RENDER_COPY_CANDIDATES {
            return true;
        }
    }
    false
}

fn coalesce(
    ir: &mut FunctionIr,
    mode: CoalesceMode,
    types: Option<&std::collections::BTreeMap<u16, vlk_types::types::CType>>,
) -> Vec<Vec<bool>> {
    if ir.blocks.iter().any(opaque) {
        return no_copies(ir);
    }
    // How many low bits each variable's values can have: a read of fewer
    // bits of another variable holds the same value only when it covers
    // them all.
    let mut bits: HashMap<u16, u32> = HashMap::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if let Stmt::Assign { dest, value, .. } = stmt {
            let hi = crate::ssa::ranges::of(value).hi;
            let held = (64 - hi.leading_zeros()).min(u32::from(dest.width));
            let most = bits.entry(dest.index).or_default();
            *most = (*most).max(held);
        }
        for output in stmt.call_outputs() {
            let most = bits.entry(output.dest.index).or_default();
            *most = (*most).max(u32::from(output.dest.width));
        }
    }
    // A copy of another variable's value, as itself or masked to bits that
    // cover it.
    let same_value = |stmt: &Stmt| {
        let Stmt::Assign { dest, value, .. } = stmt else {
            return None;
        };
        let (index, read) = match value {
            Expr::Reg { index, width } => (*index, u32::from(*width)),
            Expr::Bin {
                op: vlk_ir::ir::BinOp::And,
                lhs,
                rhs,
            } => match (lhs.as_ref(), rhs.as_ref()) {
                (Expr::Reg { index, width }, Expr::Const(mask))
                    if mask.wrapping_add(1) & mask == 0 =>
                {
                    (*index, u32::from(*width).min(mask.count_ones()))
                }
                _ => return None,
            },
            _ => return None,
        };
        (dest.index >= VARIABLE_BASE
            && index >= VARIABLE_BASE
            && index != dest.index
            && read.min(u32::from(dest.width)) >= bits.get(&index).copied().unwrap_or(64))
        .then_some((dest.index, index))
    };

    if matches!(mode, CoalesceMode::Analysis) {
        for block in &mut ir.blocks {
            sink_copied_definitions(&mut block.stmts, &same_value);
        }
    }

    let (interferes, copies, entry) = interference(ir, &same_value);
    let same_type = |a: u16, b: u16| {
        types.is_none_or(|types| types.get(&a).is_some_and(|ty| types.get(&b) == Some(ty)))
    };

    let mut groups = Groups::default();
    let mut joined = false;
    for (dest, source) in copies {
        if same_type(dest, source) {
            joined |= groups.join(dest, source, &interferes, &entry);
        }
    }
    // Values a register held one after another, of one width, are one
    // variable too where their lives do not overlap, as the register is
    // in the machine code: a counter reused for a second loop.
    let mut addresses = HashSet::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        if let Stmt::Store { addr, .. } = stmt {
            vlk_ir::ir::visit::collect_reads(addr, &mut addresses);
        }
        for operand in stmt.operands() {
            address_reads(operand, &mut addresses);
        }
    }
    // Only plain values: one that takes part in an address, as a base or
    // an index, would give its pointer type to the other's values.
    if matches!(mode, CoalesceMode::Analysis) {
        let mut kinds: HashMap<(u16, bool), Vec<u16>> = HashMap::new();
        for (variable, register) in &ir.variable_registers {
            if !bits.contains_key(variable) || addresses.contains(variable) {
                continue;
            }
            let wide = bits[variable] > 32;
            kinds.entry((*register, wide)).or_default().push(*variable);
        }
        let mut kinds: Vec<Vec<u16>> = kinds.into_values().collect();
        kinds.sort();
        for kind in kinds {
            for (at, variable) in kind.iter().enumerate() {
                for earlier in &kind[..at] {
                    // Nor through a copy already joined to one.
                    let addressed = |member: u16| {
                        groups
                            .group(member)
                            .iter()
                            .any(|other| addresses.contains(other))
                    };
                    if addressed(*earlier) || addressed(*variable) {
                        continue;
                    }
                    if groups.join(*earlier, *variable, &interferes, &entry) {
                        joined = true;
                        break;
                    }
                }
            }
        }
    }
    if !joined {
        return no_copies(ir);
    }
    let renamed: HashMap<u16, u16> = groups
        .leader
        .keys()
        .map(|variable| (*variable, groups.find(*variable)))
        .collect();
    let class = |variable: u16| renamed.get(&variable).copied().unwrap_or(variable);
    let removable: Vec<Vec<bool>> = ir
        .blocks
        .iter()
        .map(|block| {
            block
                .stmts
                .iter()
                .map(|stmt| {
                    same_value(stmt).is_some_and(|(dest, source)| class(dest) == class(source))
                })
                .collect()
        })
        .collect();
    for (index, block) in ir.blocks.iter_mut().enumerate() {
        // A copy within one variable now moves nothing.
        if matches!(mode, CoalesceMode::Analysis) {
            let mut at = 0;
            block.stmts.retain(|_| {
                let keep = !removable[index][at];
                at += 1;
                keep
            });
        }
        for stmt in &mut block.stmts {
            rename(stmt, &renamed);
        }
    }
    removable
}

fn no_copies(ir: &FunctionIr) -> Vec<Vec<bool>> {
    ir.blocks
        .iter()
        .map(|block| vec![false; block.stmts.len()])
        .collect()
}

type Interference = HashMap<u16, HashSet<u16>>;

fn interference(
    ir: &FunctionIr,
    same_value: &impl Fn(&Stmt) -> Option<(u16, u16)>,
) -> (Interference, Vec<(u16, u16)>, HashSet<u16>) {
    let live_in = live_in(ir);
    let mut interferes: Interference = HashMap::new();
    let mut copies = Vec::new();
    for index in 0..ir.blocks.len() {
        let mut live = live_out(ir, &live_in, index);
        for stmt in ir.blocks[index].stmts.iter().rev() {
            let (writes, reads) = statement_registers(stmt);
            let copy = same_value(stmt);
            if let Some(copy) = copy {
                copies.push(copy);
            }
            for written in writes.iter().filter(|written| **written >= VARIABLE_BASE) {
                for other in live.iter().filter(|other| **other >= VARIABLE_BASE) {
                    if other != written && copy.is_none_or(|(_, source)| source != *other) {
                        interferes.entry(*written).or_default().insert(*other);
                        interferes.entry(*other).or_default().insert(*written);
                    }
                }
            }
            for written in &writes {
                live.remove(written);
            }
            live.extend(reads);
        }
    }
    let entry = live_in.first().cloned().unwrap_or_default();
    (interferes, copies, entry)
}

/// Variables joined so far, each group named by its lowest variable.
#[derive(Default)]
struct Groups {
    leader: HashMap<u16, u16>,
    members: HashMap<u16, Vec<u16>>,
}

impl Groups {
    /// The members of the group `variable` is in.
    fn group(&self, variable: u16) -> Vec<u16> {
        let leader = self.find(variable);
        self.members
            .get(&leader)
            .cloned()
            .unwrap_or_else(|| vec![leader])
    }

    fn find(&self, mut variable: u16) -> u16 {
        while let Some(next) = self.leader.get(&variable) {
            variable = *next;
        }
        variable
    }

    /// Joins the groups of `a` and `b` unless a member of one interferes
    /// with a member of the other, or both hold what the caller left.
    fn join(
        &mut self,
        a: u16,
        b: u16,
        interferes: &HashMap<u16, HashSet<u16>>,
        entry: &HashSet<u16>,
    ) -> bool {
        let (a, b) = (self.find(a), self.find(b));
        if a == b {
            return false;
        }
        let (first, second) = (self.group(a), self.group(b));
        if first.iter().any(|x| entry.contains(x)) && second.iter().any(|x| entry.contains(x)) {
            return false;
        }
        let clash = first.iter().any(|x| {
            interferes
                .get(x)
                .is_some_and(|others| second.iter().any(|y| others.contains(y)))
        });
        if clash {
            return false;
        }
        // The lower index names the group, as the earlier variable does.
        let (keep, drop) = if a < b { (a, b) } else { (b, a) };
        self.leader.insert(drop, keep);
        let mut all = first;
        all.extend(second);
        self.members.remove(&drop);
        self.members.insert(keep, all);
        true
    }
}

/// The registers `expr`'s loads read their addresses from.
fn address_reads(expr: &Expr, out: &mut HashSet<u16>) {
    if let Expr::Load { addr, .. } = expr {
        vlk_ir::ir::visit::collect_reads(addr, out);
    }
    for child in vlk_ir::ir::visit::children(expr) {
        address_reads(child, out);
    }
}

/// Moves the definition of a value a copy later in the block moves on down
/// to just before that copy, when nothing between reads what it defines or
/// changes what it reads. A loop computes its next value early, as
/// `v4 = v4 >> 4; v5 = v1 & 0xf; ... v1 = v4;`, and the old value stays in
/// use beside the new one; given just before the copy, the two no longer
/// overlap and can be one variable.
fn sink_copied_definitions(
    stmts: &mut Vec<Stmt>,
    same_value: &impl Fn(&Stmt) -> Option<(u16, u16)>,
) {
    let mut copy = 0;
    while copy < stmts.len() {
        let Some((_, source)) = same_value(&stmts[copy]) else {
            copy += 1;
            continue;
        };
        let defines = |stmt: &Stmt| statement_registers(stmt).0.contains(&source);
        let Some(definition) = stmts[..copy].iter().rposition(defines) else {
            copy += 1;
            continue;
        };
        let Stmt::Assign { value, .. } = &stmts[definition] else {
            copy += 1;
            continue;
        };
        let mut reads = HashSet::new();
        vlk_ir::ir::visit::collect_reads(value, &mut reads);
        let loads = !load_free(value);
        let movable = stmts[definition + 1..copy].iter().all(|stmt| {
            let (writes, read) = statement_registers(stmt);
            !read.contains(&source)
                && writes.iter().all(|register| !reads.contains(register))
                && !(loads && matches!(stmt, Stmt::Store { .. } | Stmt::Call { .. }))
        });
        if movable && definition + 1 < copy {
            let moved = stmts.remove(definition);
            stmts.insert(copy - 1, moved);
        }
        copy += 1;
    }
}

/// Gives each variable `renamed` names the variable it joined.
pub fn rename(stmt: &mut Stmt, renamed: &HashMap<u16, u16>) {
    for dest in vlk_ir::ir::visit::statement_destinations_mut(stmt) {
        if let Some(joined) = renamed.get(&dest.index) {
            dest.index = *joined;
        }
    }
    for expr in stmt.operands_mut() {
        vlk_ir::ir::visit::rename_registers(expr, renamed);
    }
}

fn load_free(expr: &Expr) -> bool {
    !vlk_ir::ir::visit::reads_memory(expr)
}

#[cfg(test)]
mod tests;