use std::collections::{BTreeMap, BTreeSet};
use binbun_ast::ir::{Expr, ExprId, Function as Ast, Node, Origin, StmtId, VarId};
use binbun_decompile::mapping::{Mapping, Source};
use binbun_semantics::Declarations;
use binbun_semantics::ir::{Binary, RegisterId};
use binbun_ssa::constant::Constants;
use binbun_ssa::ir::{BlockId, Definition, Function, Op, Terminator, Type, Value};
use binbun_ssa::stack::Stack;
use super::{Lowered, constant, defined_at, lower, values_of};
use crate::Database;
use crate::cfg::FunctionId;
use crate::decompile::View;
use crate::references::Kind as Reference;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Query {
pub view: View,
pub depth: usize,
pub steps: usize,
}
impl Default for Query {
fn default() -> Self {
Self {
view: View::Exact,
depth: 1,
steps: 128,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Start {
Var(VarId),
Node(Node),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Trivial {
Truncation,
Extension,
Copy,
Reload,
BlockArgument,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Folded {
pub kind: Trivial,
pub value: Value,
pub address: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Kind {
Constant(u64),
Undefined,
Parameter {
register: String,
index: Option<usize>,
sites: Vec<Remote>,
},
Load {
address: String,
bytes: u16,
},
Call {
call: u64,
callee: Option<u64>,
name: Option<String>,
returns: Vec<Remote>,
},
Operation(String),
Join,
Other(String),
Cut,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Remote {
pub function: u64,
pub name: Option<String>,
pub address: u64,
pub chain: Option<Box<Step>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Step {
pub value: Value,
pub kind: Kind,
pub addresses: Vec<u64>,
pub nodes: Vec<Node>,
pub folded: Vec<Folded>,
pub inputs: Vec<Self>,
}
impl Step {
pub fn size(&self) -> usize {
1 + self.inputs.iter().map(Self::size).sum::<usize>()
}
pub fn depth(&self) -> usize {
1 + self.inputs.iter().map(Self::depth).max().unwrap_or(0)
}
pub fn folds(&self) -> usize {
self.folded.len() + self.inputs.iter().map(Self::folds).sum::<usize>()
}
pub fn folds_kind(&self, kind: Trivial) -> bool {
self.folded.iter().any(|folded| folded.kind == kind)
|| self.inputs.iter().any(|input| input.folds_kind(kind))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Use {
pub address: u64,
pub kind: String,
pub nodes: Vec<Node>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origins {
pub entry: u64,
pub values: Vec<Value>,
pub chains: Vec<Step>,
pub uses: Vec<Use>,
}
const VALUES: usize = 8;
const REMOTES: usize = 4;
const USES: usize = 64;
const NESTING: usize = 32;
pub fn origins(
database: &Database<'_>,
id: FunctionId,
start: Start,
query: &Query,
) -> Result<Origins, String> {
let (lowered, _) = lower(database, id, query.view, &[])?;
let mut budget = query.steps;
Ok(origins_lowered(
database,
&lowered,
start,
query,
&mut budget,
))
}
pub fn origins_lowered(
database: &Database<'_>,
lowered: &Lowered,
start: Start,
query: &Query,
budget: &mut usize,
) -> Origins {
let tracer = Tracer::new(database, lowered, query, query.depth);
let mut values = tracer.start(start);
let mut bases = BTreeSet::new();
values.retain(|&value| bases.insert(tracer.fold(value).0));
values.truncate(VALUES);
let chains = values
.iter()
.map(|&value| tracer.backward(value, 0, budget))
.collect();
let mut uses = Vec::new();
for &value in &values {
tracer.uses(value, &mut uses);
}
uses.truncate(USES);
Origins {
entry: lowered.entry,
values,
chains,
uses,
}
}
struct Tracer<'a> {
database: &'a Database<'a>,
l1: &'a Function,
l2: &'a Ast,
stack: &'a Stack,
constants: &'a Constants,
mapping: &'a Mapping,
declarations: Option<&'static Declarations>,
query: &'a Query,
depth: usize,
nodes: BTreeMap<Value, Vec<Node>>,
reloads: BTreeMap<Value, Vec<Value>>,
}
impl<'a> Tracer<'a> {
fn new(
database: &'a Database<'a>,
lowered: &'a Lowered,
query: &'a Query,
depth: usize,
) -> Self {
let l1 = &lowered.prepared.l1;
let l2 = &lowered.l2;
let stack = &*lowered.prepared.facts.stack;
let constants = &*lowered.prepared.facts.constants;
let mut nodes: BTreeMap<Value, Vec<Node>> = BTreeMap::new();
let mut name = |origins: &[Origin], node: Node| {
for origin in origins {
if let Origin::Value(value) = origin {
nodes.entry(*value).or_default().push(node);
}
}
};
for (index, variable) in l2.variables.iter().enumerate() {
name(&variable.origins, Node::Var(VarId(number(index))));
}
for index in 0..l2.stmts.len() {
let id = StmtId(number(index));
name(l2.provenance.stmt(id), Node::Stmt(id));
}
for index in 0..l2.exprs.len() {
let id = ExprId(number(index));
name(l2.provenance.expr(id), Node::Expr(id));
}
let mut reloads: BTreeMap<Value, Vec<Value>> = BTreeMap::new();
for inst in &l1.insts {
if let (Op::Load { .. }, Some(&result)) = (&inst.op, inst.results.first()) {
let stored = stack.resolve(l1, result);
if stored != result {
reloads.entry(stored).or_default().push(result);
}
}
}
Self {
database,
l1,
l2,
stack,
constants,
mapping: &lowered.mapping,
declarations: database.declarations(),
query,
depth,
nodes,
reloads,
}
}
fn start(&self, start: Start) -> Vec<Value> {
let of_var = |var: VarId| {
self.l2.var(var).map_or_else(Vec::new, |variable| {
values_of(self.l1, variable.kind, &variable.origins)
})
};
let named = |origins: &[Origin]| -> Vec<Value> {
origins
.iter()
.filter_map(|origin| {
if let Origin::Value(value) = origin {
Some(*value)
} else {
None
}
})
.collect()
};
let mut values = match start {
Start::Var(var) | Start::Node(Node::Var(var)) => of_var(var),
Start::Node(Node::Expr(id)) => {
let values = named(self.l2.provenance.expr(id));
if let (true, Some(&Expr::Var(var))) = (values.is_empty(), self.l2.expr(id)) {
of_var(var)
} else {
values
}
}
Start::Node(Node::Stmt(id)) => named(self.l2.provenance.stmt(id)),
Start::Node(Node::Type(_)) => Vec::new(),
};
values.retain(|&value| matches!(self.l1.ty(value), Some(Type::Bits(_))));
values.sort_unstable();
values.dedup();
values
}
fn backward(&self, value: Value, nesting: usize, budget: &mut usize) -> Step {
let (value, folded) = self.fold(value);
let mut addresses: Vec<u64> = folded.iter().filter_map(|f| f.address).collect();
addresses.extend(defined_at(self.l1, value));
addresses.sort_unstable();
addresses.dedup();
let mut nodes: Vec<Node> = core::iter::once(value)
.chain(folded.iter().map(|f| f.value))
.flat_map(|v| self.nodes.get(&v).into_iter().flatten().copied())
.collect();
nodes.sort_unstable();
nodes.dedup();
let (kind, inputs) = if *budget == 0 || nesting >= NESTING {
(Kind::Cut, Vec::new())
} else {
*budget -= 1;
self.define(value, budget)
};
let inputs = inputs
.into_iter()
.map(|input| self.backward(input, nesting + 1, budget))
.collect();
Step {
value,
kind,
addresses,
nodes,
folded,
inputs,
}
}
fn define(&self, value: Value, budget: &mut usize) -> (Kind, Vec<Value>) {
if let Some(bits) = self.constant(value) {
return (Kind::Constant(bits), Vec::new());
}
let Some(info) = self.l1.value(value) else {
return (Kind::Other("unknown".to_owned()), Vec::new());
};
let (inst, index) = match info.definition {
Definition::Parameter {
block: BlockId(0),
index,
} => return (self.parameter(index, budget), Vec::new()),
Definition::Parameter { block, index } => {
let mut arguments = self.incoming(block, index as usize);
arguments.retain(|&argument| argument != value);
arguments.sort_unstable();
arguments.dedup();
return (Kind::Join, arguments);
}
Definition::Result { inst, index } => (inst, index),
};
let Some(i) = self.l1.inst(inst) else {
return (Kind::Other("unknown".to_owned()), Vec::new());
};
match &i.op {
Op::Const(bits) => (Kind::Constant(bits.low_u64()), Vec::new()),
Op::Undefined(..) => (Kind::Undefined, Vec::new()),
&Op::Load { address, bytes, .. } => (
Kind::Load {
address: self.describe(address, 3),
bytes,
},
Vec::new(),
),
Op::Call {
target, changes, ..
} => {
let register = (index as usize)
.checked_sub(1)
.and_then(|position| changes.get(position))
.copied();
(self.call(i.address, *target, register, budget), Vec::new())
}
&Op::Select {
then, otherwise, ..
} => (Kind::Join, vec![then, otherwise]),
op @ (Op::Unary(..)
| Op::Binary(..)
| Op::Flag(..)
| Op::Extract { .. }
| Op::Concat { .. }
| Op::Extend { .. }
| Op::Lanes { .. }
| Op::Float { .. }) => (Kind::Operation(operation(op)), op.operands()),
op @ (Op::Store { .. }
| Op::Intrinsic { .. }
| Op::SystemCall { .. }
| Op::Landing { .. }) => (Kind::Other(operation(op)), Vec::new()),
}
}
fn fold(&self, mut value: Value) -> (Value, Vec<Folded>) {
let mut folded = Vec::new();
let mut seen = BTreeSet::new();
while seen.insert(value) {
let Some((kind, next)) = self.trivial(value) else {
break;
};
folded.push(Folded {
kind,
value,
address: defined_at(self.l1, value),
});
value = next;
}
(value, folded)
}
fn trivial(&self, value: Value) -> Option<(Trivial, Value)> {
let (inst, block, index) = match self.l1.value(value)?.definition {
Definition::Result { inst, .. } => (Some(inst), None, 0),
Definition::Parameter { block, index } => (None, Some(block), index as usize),
};
if let Some(block) = block {
if block == BlockId(0) {
return None;
}
let mut arguments = self.incoming(block, index);
arguments.retain(|&argument| argument != value);
arguments.sort_unstable();
arguments.dedup();
return match arguments[..] {
[only] => Some((Trivial::BlockArgument, only)),
_ => None,
};
}
let op = &self.l1.inst(inst?)?.op;
let zero = |v: Value| self.constant(v) == Some(0);
match *op {
Op::Extract {
value: source,
offset: 0,
..
} => Some((Trivial::Truncation, source)),
Op::Extend { value: source, .. } => Some((Trivial::Extension, source)),
Op::Binary(Binary::Or | Binary::Xor | Binary::Add | Binary::Sub, a, b) if zero(b) => {
Some((Trivial::Copy, a))
}
Op::Binary(Binary::Or | Binary::Xor | Binary::Add, a, b) if zero(a) => {
Some((Trivial::Copy, b))
}
Op::Binary(Binary::And | Binary::Or, a, b) if a == b => Some((Trivial::Copy, a)),
Op::Load { .. } => {
let stored = self.stack.resolve(self.l1, value);
(stored != value).then_some((Trivial::Reload, stored))
}
Op::Const(_)
| Op::Undefined(..)
| Op::Unary(..)
| Op::Binary(..)
| Op::Flag(..)
| Op::Extract { .. }
| Op::Concat { .. }
| Op::Select { .. }
| Op::Lanes { .. }
| Op::Float { .. }
| Op::Store { .. }
| Op::Intrinsic { .. }
| Op::Call { .. }
| Op::SystemCall { .. }
| Op::Landing { .. } => None,
}
}
fn incoming(&self, block: BlockId, index: usize) -> Vec<Value> {
self.l1
.blocks
.iter()
.flat_map(|b| b.terminator.targets())
.filter(|target| target.block == block)
.filter_map(|target| target.arguments.get(index).copied())
.collect()
}
fn parameter(&self, index: u32, budget: &mut usize) -> Kind {
let register = RegisterId(u16::try_from(index).unwrap_or(u16::MAX));
let name = self
.declarations
.and_then(|declarations| declarations.info(register))
.map_or_else(|| format!("r{index}"), |info| info.name.to_owned());
let position = self.mapping.parameters.iter().position(
|source| matches!(source, Source::Register(piece) if piece.register == register),
);
let mut sites = Vec::new();
if self.depth > 0 {
let entry = self.l1.entry;
let references = self.database.references().to(entry);
for reference in references
.iter()
.filter(|reference| reference.kind == Reference::Call)
.take(REMOTES)
{
let Some(caller) = reference.function else {
continue;
};
let chain = self.remote(caller, budget, |tracer| {
tracer.l1.insts.iter().find_map(|inst| {
if let Op::Call { registers, .. } = &inst.op
&& inst.address == reference.from
{
registers.get(usize::from(register.0)).copied()
} else {
None
}
})
});
sites.push(Remote {
function: self.entry_of(caller),
name: self.database.data_name(self.entry_of(caller)),
address: reference.from,
chain,
});
}
}
Kind::Parameter {
register: name,
index: position,
sites,
}
}
fn call(
&self,
address: u64,
target: Value,
register: Option<RegisterId>,
budget: &mut usize,
) -> Kind {
let callee = self.constant(target);
let mut returns = Vec::new();
let function = callee.and_then(|callee| self.database.function_at(callee));
if let (true, Some(function), Some(register)) = (self.depth > 0, function, register) {
let mut seen = 0;
while seen < REMOTES {
let index = seen;
let mut at = None;
let chain = self.remote(function, budget, |tracer| {
let (block, value) = tracer
.l1
.blocks
.iter()
.filter_map(|block| match &block.terminator {
Terminator::Return { state, .. } => state
.registers
.get(usize::from(register.0))
.map(|&value| (block.address, value)),
Terminator::Jump(_)
| Terminator::Branch { .. }
| Terminator::IndirectJump { .. }
| Terminator::Leave { .. }
| Terminator::Trap(_)
| Terminator::Stop
| Terminator::Invoke { .. }
| Terminator::Open => None,
})
.nth(index)?;
at = Some(block);
Some(value)
});
let Some(at) = at else {
break;
};
returns.push(Remote {
function: self.entry_of(function),
name: self.database.data_name(self.entry_of(function)),
address: at,
chain,
});
seen += 1;
}
}
Kind::Call {
call: address,
callee,
name: callee.and_then(|callee| self.database.data_name(callee)),
returns,
}
}
fn remote(
&self,
id: FunctionId,
budget: &mut usize,
pick: impl FnOnce(&Tracer<'_>) -> Option<Value>,
) -> Option<Box<Step>> {
if *budget == 0 {
return None;
}
let (lowered, _) = lower(self.database, id, self.query.view, &[]).ok()?;
let tracer = Tracer::new(self.database, &lowered, self.query, self.depth - 1);
let value = pick(&tracer)?;
Some(Box::new(tracer.backward(value, 0, budget)))
}
fn entry_of(&self, id: FunctionId) -> u64 {
self.database
.function(id)
.map_or(0, |function| function.entry)
}
fn constant(&self, value: Value) -> Option<u64> {
self.constants
.constant(value)
.map(|bits| bits.low_u64())
.or_else(|| constant(self.l1, value))
}
fn describe(&self, value: Value, depth: usize) -> String {
let (value, _) = self.fold(value);
if let Some(offset) = self.stack.offset(value) {
return match offset {
0 => "sp".to_owned(),
o if o < 0 => format!("sp-{:#x}", o.unsigned_abs()),
o => format!("sp+{o:#x}"),
};
}
if let Some(bits) = self.constant(value) {
return format!("{bits:#x}");
}
let Some(info) = self.l1.value(value) else {
return format!("v{}", value.0);
};
match info.definition {
Definition::Parameter {
block: BlockId(0),
index,
} => self
.declarations
.and_then(|d| d.info(RegisterId(u16::try_from(index).unwrap_or(u16::MAX))))
.map_or_else(|| format!("v{}", value.0), |info| info.name.to_owned()),
Definition::Result { inst, .. } if depth > 0 => {
let op = self.l1.inst(inst).map(|i| &i.op);
if let Some(&Op::Binary(op, a, b)) = op
&& let Some(symbol) = symbol(op)
{
format!(
"({} {symbol} {})",
self.describe(a, depth - 1),
self.describe(b, depth - 1)
)
} else if let Some(&Op::Load { address, .. }) = op {
format!("[{}]", self.describe(address, depth - 1))
} else {
format!("v{}", value.0)
}
}
Definition::Parameter { .. } | Definition::Result { .. } => format!("v{}", value.0),
}
}
fn uses(&self, value: Value, out: &mut Vec<Use>) {
let mut set = BTreeSet::from([value]);
let mut work = vec![value];
while let Some(current) = work.pop() {
if out.len() >= USES {
return;
}
let follow = |next: Value, set: &mut BTreeSet<Value>, work: &mut Vec<Value>| {
if set.insert(next) {
work.push(next);
}
};
for &reload in self.reloads.get(¤t).into_iter().flatten() {
follow(reload, &mut set, &mut work);
}
for inst in &self.l1.insts {
if !inst.op.operands().contains(¤t) {
continue;
}
let result = inst.results.first().copied();
if let Some(result) = result
&& self
.trivial(result)
.is_some_and(|(_, from)| from == current)
{
follow(result, &mut set, &mut work);
continue;
}
let kind = use_kind(&inst.op, current);
out.push(Use {
address: inst.address,
kind,
nodes: result
.and_then(|result| self.nodes.get(&result))
.cloned()
.unwrap_or_default(),
});
}
for block in &self.l1.blocks {
let terminator = &block.terminator;
if terminator.operands().any(|operand| operand == current) {
let kind = match terminator {
Terminator::Branch { .. } => "branch condition",
Terminator::Return { .. } => "returned",
Terminator::Leave { .. } => "passed on (tail call)",
Terminator::IndirectJump { .. } => "jump address",
Terminator::Jump(_)
| Terminator::Trap(_)
| Terminator::Stop
| Terminator::Invoke { .. }
| Terminator::Open => "terminator",
};
out.push(Use {
address: block.address,
kind: kind.to_owned(),
nodes: Vec::new(),
});
}
for target in terminator.targets() {
for (position, &argument) in target.arguments.iter().enumerate() {
if argument != current {
continue;
}
let Some(¶meter) = self
.l1
.block(target.block)
.and_then(|b| b.parameters.get(position))
else {
continue;
};
if self.trivial(parameter).is_some() {
follow(parameter, &mut set, &mut work);
} else {
out.push(Use {
address: block.address,
kind: "joins".to_owned(),
nodes: self.nodes.get(¶meter).cloned().unwrap_or_default(),
});
}
}
}
}
}
}
}
fn operation(op: &Op) -> String {
match op {
Op::Unary(unary, _) => format!("{unary:?}"),
Op::Binary(binary, ..) => format!("{binary:?}"),
Op::Flag(flag, ..) => format!("{flag:?}"),
Op::Float { op, .. } => format!("{op:?}"),
Op::Lanes { op, .. } => format!("{op:?}"),
Op::Extract { offset, width, .. } => format!("Extract {width} bits at {offset}"),
Op::Concat { .. } => "Concat".to_owned(),
Op::Extend { signed, width, .. } => {
format!(
"{} {width}",
if *signed { "SignExtend" } else { "ZeroExtend" }
)
}
Op::Select { .. } => "Select".to_owned(),
Op::Const(_) => "Const".to_owned(),
Op::Undefined(..) => "Undefined".to_owned(),
Op::Load { .. } => "Load".to_owned(),
Op::Store { .. } => "Store".to_owned(),
Op::Intrinsic { intrinsic, .. } => format!("intrinsic {}", intrinsic.0),
Op::Call { .. } => "Call".to_owned(),
Op::SystemCall { .. } => "system call".to_owned(),
Op::Landing { .. } => "exception landing".to_owned(),
}
}
fn use_kind(op: &Op, value: Value) -> String {
match op {
Op::Store { value: stored, .. } if *stored == value => "stored".to_owned(),
Op::Store { .. } => "store address".to_owned(),
Op::Load { .. } => "load address".to_owned(),
Op::Call { target, .. } if *target == value => "called".to_owned(),
Op::Call { .. } => "call argument".to_owned(),
Op::Const(_)
| Op::Undefined(..)
| Op::Unary(..)
| Op::Binary(..)
| Op::Flag(..)
| Op::Extract { .. }
| Op::Concat { .. }
| Op::Extend { .. }
| Op::Select { .. }
| Op::Lanes { .. }
| Op::Float { .. }
| Op::Intrinsic { .. }
| Op::SystemCall { .. }
| Op::Landing { .. } => operation(op),
}
}
fn number(index: usize) -> u32 {
u32::try_from(index).unwrap_or(u32::MAX)
}
fn symbol(op: Binary) -> Option<&'static str> {
[
(Binary::Add, "+"),
(Binary::Sub, "-"),
(Binary::Mul, "*"),
(Binary::Shl, "<<"),
(Binary::And, "&"),
(Binary::Or, "|"),
]
.into_iter()
.find_map(|(candidate, text)| (candidate == op).then_some(text))
}