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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use std::collections::HashMap;

use vlk_ir::ir::{Block, Expr, FunctionIr, Stmt};

/// Whether the function at an address returns only 32-bit values.
pub type NarrowReturn<'a> = &'a dyn Fn(u64) -> bool;

/// The widths each register is written at. A write is 32-bit when the
/// lifter wrapped the value in a zero-extension mask, or when it is the
/// result of a call to a function returning 32 bits; a constant that fits
/// in 32 bits is width 0, as wide as whatever else the register holds;
/// anything else writes all 64 bits.
fn register_writes(blocks: &[Block], narrow_return: NarrowReturn<'_>) -> HashMap<u16, Vec<u8>> {
    use vlk_ir::ir::BinOp;

    let mut writes: HashMap<u16, Vec<u8>> = HashMap::new();
    for block in blocks {
        for stmt in &block.stmts {
            match stmt {
                Stmt::Assign { dest, value, .. } => {
                    let width = match value {
                        Expr::Bin {
                            op: BinOp::And,
                            rhs,
                            ..
                        } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => 32,
                        Expr::Const(value) if *value <= 0xffff_ffff => 0,
                        _ => 64,
                    };
                    writes.entry(dest.index).or_default().push(width);
                }
                Stmt::Call { target, .. } => {
                    let narrow = !stmt.has_declared_call() && target.is_some_and(narrow_return);
                    let returned = stmt.primary_call_output().map(|output| output.dest.index);
                    for written in vlk_ir::ir::visit::statement_registers(stmt).0 {
                        let width = if narrow && Some(written) == returned {
                            32
                        } else {
                            64
                        };
                        writes.entry(written).or_default().push(width);
                    }
                }
                _ => {
                    for written in vlk_ir::ir::visit::statement_registers(stmt).0 {
                        writes.entry(written).or_default().push(64);
                    }
                }
            }
        }
    }
    writes
}

fn only_32_bit_writes(writes: &HashMap<u16, Vec<u8>>, register: u16) -> bool {
    writes
        .get(&register)
        .is_some_and(|widths| !widths.is_empty() && widths.iter().all(|width| *width == 32))
}

/// Whether every return of the lifted `blocks` returns a register written
/// at 32 bits, and otherwise only with constants that fit, so the function
/// returns 32-bit values.
pub fn returns_32(blocks: &[Block], narrow_return: NarrowReturn<'_>) -> bool {
    let writes = register_writes(blocks, narrow_return);
    let mut returns = blocks
        .iter()
        .filter_map(|block| match block.stmts.last() {
            Some(Stmt::Ret { value, .. }) => Some(value),
            _ => None,
        })
        .peekable();
    returns.peek().is_some()
        && returns.all(|value| {
            let Expr::Reg { index, width: 64 } = value else {
                return false;
            };
            writes.get(index).is_some_and(|widths| {
                widths.contains(&32) && widths.iter().all(|width| *width <= 32)
            })
        })
}

/// Registers read and written only as 32-bit values become 32-bit variables
/// without the lifter's zero-extension masks; returns those registers.
pub fn specialize_widths(
    ir: &mut FunctionIr,
    narrow_return: NarrowReturn<'_>,
) -> std::collections::HashSet<u16> {
    use std::collections::HashSet;
    use vlk_ir::ir::BinOp;

    let writes = register_writes(&ir.blocks, narrow_return);

    // A returned register that is only ever written at 32 bits returns its
    // 32-bit view.
    for block in &mut ir.blocks {
        for stmt in &mut block.stmts {
            let Stmt::Ret { value, .. } = stmt else {
                continue;
            };
            let Expr::Reg { index, width: 64 } = value else {
                continue;
            };
            if only_32_bit_writes(&writes, *index) {
                *value = Expr::Reg {
                    index: *index,
                    width: 32,
                };
            }
        }
    }

    // A register under a `& 0xffffffff` mask is a 32-bit read; any other
    // reference reads at its own width.
    let mut reads: HashMap<u16, Vec<u8>> = HashMap::new();
    for block in &mut ir.blocks {
        for stmt in &mut block.stmts {
            map_stmt(stmt, &mut |expr| {
                let expr = expr.clone();
                fn visit(expr: &Expr, reads: &mut HashMap<u16, Vec<u8>>) {
                    match expr {
                        Expr::Const(_) => {}
                        Expr::Reg { index, width } => {
                            reads.entry(*index).or_default().push(*width);
                        }
                        Expr::Bin {
                            op: BinOp::And,
                            lhs,
                            rhs,
                            ..
                        } if matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => match lhs.as_ref()
                        {
                            Expr::Reg { index, .. } => {
                                reads.entry(*index).or_default().push(32);
                            }
                            other => visit(other, reads),
                        },
                        Expr::Bin { lhs, rhs, .. } => {
                            visit(lhs, reads);
                            visit(rhs, reads);
                        }
                        Expr::Load { addr, .. } => visit(addr, reads),
                        Expr::SignExtend { value, .. } => visit(value, reads),
                        Expr::Select {
                            lhs,
                            rhs,
                            then,
                            els,
                            ..
                        } => {
                            visit(lhs, reads);
                            visit(rhs, reads);
                            visit(then, reads);
                            visit(els, reads);
                        }
                        Expr::Apply { args, .. } => {
                            for arg in args {
                                visit(arg, reads);
                            }
                        }
                    }
                }
                visit(&expr, &mut reads);
                expr
            });
        }
    }

    let registers_used_only_at_32_bits: HashSet<u16> = reads
        .keys()
        .chain(writes.keys())
        .copied()
        .filter(|index| {
            let read_all_32 = reads
                .get(index)
                .is_none_or(|widths| widths.iter().all(|width| *width == 32));
            let write_all_32 = writes
                .get(index)
                .is_none_or(|widths| widths.iter().all(|width| *width == 32));
            *index != u16::MAX && read_all_32 && write_all_32
        })
        .collect();

    for block in &mut ir.blocks {
        for stmt in &mut block.stmts {
            map_stmt(stmt, &mut |expr| {
                rewrite_read_masks(expr, &registers_used_only_at_32_bits)
            });
            for dest in vlk_ir::ir::visit::statement_destinations_mut(stmt) {
                if registers_used_only_at_32_bits.contains(&dest.index) {
                    dest.width = 32;
                }
            }
            if let Stmt::Assign { dest, value, .. } = stmt
                && registers_used_only_at_32_bits.contains(&dest.index)
                && let Expr::Bin {
                    op: BinOp::And,
                    lhs,
                    rhs,
                } = value
                && matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
            {
                *value = (**lhs).clone();
            }
        }
    }

    registers_used_only_at_32_bits
}

/// Whether `value` always is the sign extension of its low 32 bits, given
/// the variables in `words` are.
fn extended_word(value: &Expr, words: &std::collections::HashSet<u16>) -> bool {
    use vlk_ir::ir::{BinOp, Operation};
    match value {
        Expr::SignExtend { width, .. } => *width <= 4,
        Expr::Const(value) => *value as i64 == i64::from(*value as i32),
        Expr::Load { width, signed, .. } => (*signed && *width <= 4) || *width <= 2,
        Expr::Reg { index, width: 64 } => words.contains(index),
        Expr::Select { then, els, .. } => extended_word(then, words) && extended_word(els, words),
        Expr::Bin {
            op: BinOp::And,
            rhs,
            ..
        } => matches!(rhs.as_ref(), Expr::Const(mask) if *mask <= 0x7fff_ffff),
        Expr::Apply { op, .. } => matches!(
            op,
            Operation::FloatEqual(_)
                | Operation::FloatLess(_)
                | Operation::FloatLessEqual(_)
                | Operation::FloatUnordered(_)
        ),
        _ => false,
    }
}

/// `value` with the sign extensions from 32 bits dropped that its low 32
/// bits do not depend on: under sums, products, bitwise operations and the
/// shifted operand of a left shift.
fn low_word(value: Expr) -> Expr {
    use vlk_ir::ir::BinOp;
    match value {
        Expr::SignExtend { value, width: 4 } => low_word(*value),
        Expr::Bin { op, lhs, rhs }
            if matches!(
                op,
                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::And | BinOp::Or | BinOp::Xor
            ) =>
        {
            Expr::Bin {
                op,
                lhs: Box::new(low_word(*lhs)),
                rhs: Box::new(low_word(*rhs)),
            }
        }
        Expr::Bin {
            op: BinOp::Shl,
            lhs,
            rhs,
        } if matches!(rhs.as_ref(), Expr::Const(count) if *count < 32) => Expr::Bin {
            op: BinOp::Shl,
            lhs: Box::new(low_word(*lhs)),
            rhs,
        },
        Expr::Select {
            cond,
            lhs,
            rhs,
            then,
            els,
        } => Expr::Select {
            cond,
            lhs,
            rhs,
            then: Box::new(low_word(*then)),
            els: Box::new(low_word(*els)),
        },
        other => other,
    }
}

/// The operand of a comparison of sign-extended words, as a 32-bit value:
/// comparing the words gives what comparing their extensions gives.
fn compared_word(value: &Expr) -> Option<Expr> {
    use vlk_ir::ir::BinOp;
    match value {
        Expr::SignExtend { value, width: 4 } => Some(match value.as_ref() {
            Expr::Reg { width: 32, .. } => (**value).clone(),
            other => Expr::Bin {
                op: BinOp::And,
                lhs: Box::new(low_word(other.clone())),
                rhs: Box::new(Expr::Const(0xffff_ffff)),
            },
        }),
        Expr::Const(value) if *value as i64 == i64::from(*value as i32) => {
            Some(Expr::Const(value & 0xffff_ffff))
        }
        _ => None,
    }
}

fn compare_words(cond: vlk_ir::ir::Cond, lhs: &mut Expr, rhs: &mut Expr) {
    use vlk_ir::ir::Cond;
    if !matches!(
        cond,
        Cond::Eq
            | Cond::Ne
            | Cond::Lt
            | Cond::Ge
            | Cond::Gt
            | Cond::Le
            | Cond::Cc
            | Cond::Cs
            | Cond::Hi
            | Cond::Ls
    ) || !(matches!(lhs, Expr::SignExtend { .. }) || matches!(rhs, Expr::SignExtend { .. }))
    {
        return;
    }
    if let (Some(left), Some(right)) = (compared_word(lhs), compared_word(rhs)) {
        *lhs = left;
        *rhs = right;
    }
}

/// Rewrites every expression inside `expr`, children first.
fn rewrite_words(expr: &Expr, words: &std::collections::HashSet<u16>) -> Expr {
    let again = |expr: &Expr| rewrite_words(expr, words);
    match expr {
        Expr::Reg { index, width: 64 } if words.contains(index) => Expr::SignExtend {
            value: Box::new(Expr::Reg {
                index: *index,
                width: 32,
            }),
            width: 4,
        },
        Expr::Reg { .. } | Expr::Const(_) => expr.clone(),
        Expr::Bin { op, lhs, rhs } => Expr::Bin {
            op: *op,
            lhs: Box::new(again(lhs)),
            rhs: Box::new(again(rhs)),
        },
        Expr::Load {
            addr,
            width,
            signed,
        } => Expr::Load {
            addr: Box::new(again(addr)),
            width: *width,
            signed: *signed,
        },
        Expr::SignExtend { value, width } => {
            let value = again(value);
            Expr::SignExtend {
                value: Box::new(if *width == 4 { low_word(value) } else { value }),
                width: *width,
            }
        }
        Expr::Select {
            cond,
            lhs,
            rhs,
            then,
            els,
        } => {
            let (mut lhs, mut rhs) = (again(lhs), again(rhs));
            compare_words(*cond, &mut lhs, &mut rhs);
            Expr::Select {
                cond: *cond,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
                then: Box::new(again(then)),
                els: Box::new(again(els)),
            }
        }
        Expr::Apply { op, args } => Expr::Apply {
            op: *op,
            args: args.iter().map(again).collect(),
        },
    }
}

/// On a processor that keeps a 32-bit value sign-extended in its 64-bit
/// register, the variables every assignment gives such a value become
/// 32-bit variables: their assignments lose the extension, their reads
/// gain it, and a comparison of two extended words compares the words.
/// Returns those variables.
pub fn narrow_extended_words(ir: &mut FunctionIr) -> std::collections::HashSet<u16> {
    use std::collections::HashSet;

    // A variable a statement other than an assignment writes or reads in
    // a way this does not rewrite stays as it is.
    let mut excluded: HashSet<u16> = HashSet::new();
    let mut words: HashSet<u16> = HashSet::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        match stmt {
            Stmt::Assign { dest, .. } if dest.width == 64 && vlk_ir::ir::is_temp(dest.index) => {
                words.insert(dest.index);
            }
            Stmt::Assign { dest, .. } => {
                excluded.insert(dest.index);
            }
            Stmt::Store { .. }
            | Stmt::Brif { .. }
            | Stmt::Ret { .. }
            | Stmt::BrIndirect { .. }
            | Stmt::Switch { .. } => {}
            Stmt::Call { .. } => {
                excluded.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
            }
            other => {
                excluded.extend(vlk_ir::ir::visit::statement_registers(other).0);
                for value in other.operands() {
                    vlk_ir::ir::visit::expr_reads(value, &mut excluded);
                }
            }
        }
    }
    words.retain(|index| !excluded.contains(index));
    loop {
        let unfit: Vec<u16> = ir
            .blocks
            .iter()
            .flat_map(|block| &block.stmts)
            .filter_map(|stmt| match stmt {
                Stmt::Assign { dest, value, .. }
                    if words.contains(&dest.index) && !extended_word(value, &words) =>
                {
                    Some(dest.index)
                }
                _ => None,
            })
            .collect();
        if unfit.is_empty() {
            break;
        }
        for index in unfit {
            words.remove(&index);
        }
    }
    for stmt in ir.blocks.iter_mut().flat_map(|block| &mut block.stmts) {
        map_stmt(stmt, &mut |expr| rewrite_words(expr, &words));
        match stmt {
            Stmt::Assign { dest, value, .. } if words.contains(&dest.index) => {
                dest.width = 32;
                *value = match low_word(std::mem::replace(value, Expr::Const(0))) {
                    Expr::Const(value) => Expr::Const(value & 0xffff_ffff),
                    other => other,
                };
            }
            Stmt::Store { value, width, .. } if *width <= 4 => {
                *value = low_word(std::mem::replace(value, Expr::Const(0)));
            }
            Stmt::Brif { cond, lhs, rhs, .. } => compare_words(*cond, lhs, rhs),
            _ => {}
        }
    }
    words
}

fn rewrite_read_masks(
    expr: &Expr,
    registers_used_only_at_32_bits: &std::collections::HashSet<u16>,
) -> Expr {
    use vlk_ir::ir::BinOp;

    if let Expr::Bin {
        op: BinOp::And,
        lhs,
        rhs,
    } = expr
        && matches!(rhs.as_ref(), Expr::Const(0xffff_ffff))
        && let Expr::Reg { index, .. } = lhs.as_ref()
        && registers_used_only_at_32_bits.contains(index)
    {
        return Expr::Reg {
            index: *index,
            width: 32,
        };
    }
    match expr {
        Expr::Bin { op, lhs, rhs } => Expr::bin(
            *op,
            rewrite_read_masks(lhs, registers_used_only_at_32_bits),
            rewrite_read_masks(rhs, registers_used_only_at_32_bits),
        ),
        Expr::Load {
            addr,
            width,
            signed,
        } => Expr::Load {
            addr: Box::new(rewrite_read_masks(addr, registers_used_only_at_32_bits)),
            width: *width,
            signed: *signed,
        },
        Expr::SignExtend { value, width } => Expr::SignExtend {
            value: Box::new(rewrite_read_masks(value, registers_used_only_at_32_bits)),
            width: *width,
        },
        Expr::Select {
            cond,
            lhs,
            rhs,
            then,
            els,
        } => Expr::Select {
            cond: *cond,
            lhs: Box::new(rewrite_read_masks(lhs, registers_used_only_at_32_bits)),
            rhs: Box::new(rewrite_read_masks(rhs, registers_used_only_at_32_bits)),
            then: Box::new(rewrite_read_masks(then, registers_used_only_at_32_bits)),
            els: Box::new(rewrite_read_masks(els, registers_used_only_at_32_bits)),
        },
        Expr::Apply { op, args } => Expr::Apply {
            op: *op,
            args: args
                .iter()
                .map(|arg| rewrite_read_masks(arg, registers_used_only_at_32_bits))
                .collect(),
        },
        other => other.clone(),
    }
}

fn map_stmt(stmt: &mut Stmt, map: &mut dyn FnMut(&Expr) -> Expr) {
    match stmt {
        Stmt::Assign { value, .. } => *value = map(&*value),
        Stmt::Store { addr, value, .. } => {
            *addr = map(&*addr);
            *value = map(&*value);
        }
        Stmt::Brif { lhs, rhs, .. } => {
            *lhs = map(&*lhs);
            *rhs = map(&*rhs);
        }
        Stmt::Ret { value, .. } => *value = map(&*value),
        Stmt::BrIndirect { target, .. } => *target = map(&*target),
        Stmt::Switch { index, .. } => *index = map(&*index),
        Stmt::Call { through, args, .. } => {
            for value in through.iter_mut().chain(args.iter_mut().flatten()) {
                *value = map(&*value);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests;