use crate::image::{Image, SymKind};
use crate::thumb::decode::{Addr, Cond, DpOp, Insn, Offset, Op, Operand, decode};
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum OptLevel {
O0,
O1,
O2,
O3,
Os,
Og,
}
impl OptLevel {
pub const ALL: [OptLevel; 6] = [
OptLevel::O0,
OptLevel::O1,
OptLevel::O2,
OptLevel::O3,
OptLevel::Os,
OptLevel::Og,
];
}
impl fmt::Display for OptLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
OptLevel::O0 => "-O0",
OptLevel::O1 => "-O1",
OptLevel::O2 => "-O2",
OptLevel::O3 => "-O3",
OptLevel::Os => "-Os",
OptLevel::Og => "-Og",
})
}
}
#[derive(Clone, Debug)]
pub struct FlagReport {
pub compiler: Option<String>,
pub declared: Option<String>,
pub candidates: Vec<(OptLevel, f32)>,
pub evidence: Vec<String>,
}
impl FlagReport {
pub fn best(&self) -> Option<OptLevel> {
self.candidates.first().map(|c| c.0)
}
}
#[derive(Clone, Debug, Default)]
pub struct Features {
pub funcs: u32,
pub insns: u32,
pub frame_pointer_funcs: u32,
pub frame_accesses: u32,
pub loops_top_tested: u32,
pub loops_entry_jump: u32,
pub loops_rotated: u32,
pub loops_with_remainder: u32,
pub loop_funcs: u32,
pub loop_func_bytes: u32,
pub branch_adjacent: u32,
pub branch_separated: u32,
pub it_blocks: u32,
pub div_by_immediate: u32,
pub long_multiplies: u32,
pub starts_padded: u32,
pub starts_unpadded: u32,
pub clones: u32,
pub dual_accesses: u32,
pub windows: u32,
pub repeated_windows: u32,
}
struct Decoded {
addr: u32,
insn: Insn,
in_it: bool,
}
fn decode_function(image: &Image, start: u32, size: u32) -> Vec<Decoded> {
let mut out = Vec::new();
let mut pc = start;
let end = start.saturating_add(size);
let mut it_left = 0u32;
while pc < end {
if image.is_data_in_code(pc) {
match image.data_ranges.iter().find(|&&(a, b)| pc >= a && pc < b) {
Some(&(_, b)) => pc = b.max(pc + 2),
None => pc += 2,
}
it_left = 0;
continue;
}
let n = (end - pc).min(4);
let Some(bytes) = image.read(pc, n) else { break };
let in_it = it_left > 0;
let Some(insn) = decode(bytes, pc, in_it) else { break };
if in_it {
it_left -= 1;
} else if let Op::It { mask, .. } = insn.op {
it_left = 4 - (mask & 0xf).trailing_zeros().min(3);
}
out.push(Decoded { addr: pc, insn, in_it });
pc += insn.len as u32;
}
out
}
fn sets_flags(op: &Op) -> bool {
match *op {
Op::Dp { s, rd, .. } => s || rd.is_none(),
Op::ShiftReg { s, .. } | Op::Mul { s, .. } => s,
_ => false,
}
}
fn is_compare(op: &Op) -> bool {
matches!(op, Op::Dp { rd: None, .. })
}
fn shape(op: &Op) -> u32 {
match *op {
Op::Dp { op, s, rd, src, .. } => {
1 | (op as u32) << 8
| (s as u32) << 16
| (rd.is_none() as u32) << 17
| (matches!(src, Operand::Imm { .. }) as u32) << 18
}
Op::Load { size, signed, addr, .. } => 2 | (size as u32) << 8 | (signed as u32) << 16 | addr_shape(&addr) << 17,
Op::Store { size, addr, .. } => 3 | (size as u32) << 8 | addr_shape(&addr) << 17,
Op::B { cond, .. } => 4 | (cond as u32) << 8,
Op::ShiftReg { shift, .. } => 5 | (shift as u32) << 8,
Op::Mul { .. } => 6,
Op::Mla { .. } => 7,
Op::Mls { .. } => 8,
Op::MulLong { signed, accumulate, .. } => 9 | (signed as u32) << 8 | (accumulate as u32) << 9,
Op::Div { signed, .. } => 10 | (signed as u32) << 8,
Op::LoadDual { .. } => 11,
Op::StoreDual { .. } => 12,
Op::LoadMulti { .. } => 13,
Op::StoreMulti { .. } => 14,
Op::Bl { .. } => 15,
Op::Bx { .. } => 16,
Op::Blx { .. } => 17,
Op::Cbz { nonzero, .. } => 18 | (nonzero as u32) << 8,
Op::It { cond, mask } => 19 | (cond as u32) << 8 | (mask as u32) << 16,
Op::Extend { signed, size, .. } => 20 | (signed as u32) << 8 | (size as u32) << 9,
Op::Bfx { signed, .. } => 21 | (signed as u32) << 8,
Op::Movt { .. } => 22,
Op::Adr { .. } => 23,
Op::TableBranch { .. } => 24,
Op::Nop => 25,
_ => 26,
}
}
fn addr_shape(a: &Addr) -> u32 {
match a {
Addr::Lit(_) => 0,
Addr::Base {
offset: Offset::Imm(_),
wback: false,
..
} => 1,
Addr::Base {
offset: Offset::Imm(_), ..
} => 2,
Addr::Base { .. } => 3,
}
}
fn frame_access(addr: &Addr) -> bool {
matches!(
addr,
Addr::Base {
rn: 7 | 13,
offset: Offset::Imm(_),
wback: false,
..
}
)
}
pub fn features(image: &Image) -> Features {
let mut f = Features::default();
let mut funcs: Vec<(u32, u32, &str)> = image
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && s.size >= 2 && image.segment_at(s.addr).is_some_and(|g| g.exec))
.map(|s| (s.addr, s.size, s.name.as_str()))
.collect();
funcs.sort();
funcs.dedup_by_key(|x| x.0);
for &(_, _, name) in &funcs {
if [".constprop", ".isra", ".part"].iter().any(|k| name.contains(k)) {
f.clones += 1;
}
}
for w in funcs.windows(2) {
let end = w[0].0 + w[0].1;
if end % 4 == 2 {
if w[1].0 == end {
f.starts_unpadded += 1;
} else if w[1].0 == end + 2 {
f.starts_padded += 1;
}
}
}
for &(addr, size, _) in &funcs {
let code = decode_function(image, addr, size);
if code.is_empty() {
continue;
}
f.funcs += 1;
f.insns += code.len() as u32;
let is_fp = code.iter().take(6).any(|d| {
matches!(
d.insn.op,
Op::Dp {
op: DpOp::Add,
rd: Some(7),
rn: Some(13),
src: Operand::Imm { .. },
..
} | Op::Dp {
op: DpOp::Mov,
rd: Some(7),
src: Operand::Reg { rm: 13, .. },
..
}
)
});
f.frame_pointer_funcs += is_fp as u32;
let shapes: Vec<u32> = code.iter().map(|d| shape(&d.insn.op)).collect();
let mut seen = std::collections::HashSet::new();
for w in shapes.windows(4) {
f.windows += 1;
if !seen.insert([w[0], w[1], w[2], w[3]]) {
f.repeated_windows += 1;
}
}
let mut has_loop = false;
for (i, d) in code.iter().enumerate() {
let prev = if i > 0 { Some(&code[i - 1]) } else { None };
match d.insn.op {
Op::Load { addr: a, .. } | Op::Store { addr: a, .. } => f.frame_accesses += frame_access(&a) as u32,
Op::LoadDual { addr: a, .. } | Op::StoreDual { addr: a, .. } => {
if frame_access(&a) {
f.frame_accesses += 1;
} else {
f.dual_accesses += 1;
}
}
Op::It { .. } => f.it_blocks += 1,
Op::MulLong { accumulate: false, .. } => f.long_multiplies += 1,
Op::Div { rm, .. } => {
if let Some(p) = prev
&& matches!(p.insn.op, Op::Dp { op: DpOp::Mov, rd: Some(r), src: Operand::Imm { .. }, .. } if r == rm)
{
f.div_by_immediate += 1;
}
}
Op::B { cond, target } => {
if cond != Cond::Al
&& !d.in_it
&& let Some(p) = prev
{
if sets_flags(&p.insn.op) {
f.branch_adjacent += 1;
} else {
f.branch_separated += 1;
}
}
if target <= d.addr && target >= addr && !d.in_it {
if cond == Cond::Al {
let tested = code.iter().skip_while(|e| e.addr < target).take(4).any(|e| {
matches!(e.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > e.addr)
|| matches!(e.insn.op, Op::Cbz { .. })
});
if tested {
has_loop = true;
f.loops_top_tested += 1;
}
} else {
has_loop = true;
let entry = code.iter().any(|e| {
e.addr < target
&& matches!(e.insn.op, Op::B { cond: Cond::Al, target: t } if t > target && t <= d.addr)
});
if entry {
f.loops_entry_jump += 1;
} else {
f.loops_rotated += 1;
let next = &code[i + 1..];
let rem = next.iter().take(2).any(|n| is_compare(&n.insn.op))
&& next.iter().take(3).any(|n| {
matches!(n.insn.op, Op::B { cond: c, target: t } if c != Cond::Al && t > n.addr)
});
f.loops_with_remainder += rem as u32;
}
}
}
}
_ => {}
}
}
if has_loop {
f.loop_funcs += 1;
f.loop_func_bytes += size;
}
}
f
}
fn ratio(a: u32, b: u32) -> f32 {
if a + b == 0 { 0.0 } else { a as f32 / (a + b) as f32 }
}
fn declared_level(producer: &str) -> Option<OptLevel> {
let mut found = None;
for tok in producer.split_whitespace() {
let l = match tok {
"-O0" => OptLevel::O0,
"-O" | "-O1" => OptLevel::O1,
"-O2" => OptLevel::O2,
"-O3" | "-Ofast" => OptLevel::O3,
"-Os" | "-Oz" => OptLevel::Os,
"-Og" => OptLevel::Og,
_ => continue,
};
found = Some(l); }
found
}
pub fn detect(image: &Image) -> FlagReport {
let f = features(image);
let mut report = FlagReport {
compiler: image.comment.clone(),
declared: image.producer.clone(),
candidates: Vec::new(),
evidence: Vec::new(),
};
if let Some(p) = &image.producer {
match declared_level(p) {
Some(l) => report.evidence.push(format!(
"debug info declares {l} (a claim by the binary, not used for the guess)"
)),
None => report
.evidence
.push("debug info records no -O flag (GCC omits it at -O0)".into()),
}
}
if f.funcs == 0 || f.insns == 0 {
report
.evidence
.push("no decodable functions: nothing to base a guess on".into());
return report;
}
let mut s = [0.0f32; 6];
const O0: usize = 0;
const O1: usize = 1;
const O2: usize = 2;
const O3: usize = 3;
const OS: usize = 4;
const OG: usize = 5;
let ev = &mut report.evidence;
let fp = f.frame_pointer_funcs as f32 / f.funcs as f32;
let frame = f.frame_accesses as f32 / f.insns as f32;
if fp >= 0.6 && frame >= 0.2 {
s[O0] += 10.0;
ev.push(format!(
"{} of {} functions keep a frame pointer in r7 and {:.0}% of instructions access the frame: unoptimised code",
f.frame_pointer_funcs,
f.funcs,
frame * 100.0
));
} else {
s[O0] -= 10.0;
ev.push(format!(
"{} of {} functions use a frame pointer, {:.0}% of instructions access the frame: optimised code",
f.frame_pointer_funcs,
f.funcs,
frame * 100.0
));
}
let loops = f.loops_top_tested + f.loops_entry_jump + f.loops_rotated;
if loops > 0 {
let (top, entry, rot) = (
f.loops_top_tested as f32 / loops as f32,
f.loops_entry_jump as f32 / loops as f32,
f.loops_rotated as f32 / loops as f32,
);
ev.push(format!(
"{loops} loops: {} test at the top (-Os), {} jump to a bottom test (-Og/-O0), {} guarded bottom-tested (-O1 and up)",
f.loops_top_tested, f.loops_entry_jump, f.loops_rotated
));
s[OS] += 3.0 * top - 2.0 * (rot + entry);
s[OG] += 3.0 * entry - 2.5 * (rot + top);
for l in [O1, O2, O3] {
s[l] += 2.0 * rot - 2.5 * (top + entry);
}
} else {
ev.push("no loops: loop-shape evidence unavailable".into());
}
if f.div_by_immediate + f.long_multiplies > 0 {
ev.push(format!(
"{} divisions by an immediate kept as udiv/sdiv (-Os), {} long multiplies (reciprocal division at speed levels)",
f.div_by_immediate, f.long_multiplies
));
if f.div_by_immediate > 0 && f.long_multiplies == 0 {
s[OS] += 2.5;
for l in [O1, O2, O3, OG] {
s[l] -= 2.0;
}
} else if f.div_by_immediate == 0 {
s[OS] -= 1.5;
}
}
let nb = f.branch_adjacent + f.branch_separated;
if nb >= 4 {
let sep = ratio(f.branch_separated, f.branch_adjacent);
ev.push(format!(
"{} of {nb} conditional branches are separated from their compare (instruction scheduling: -O2/-O3/-Os)",
f.branch_separated
));
if sep >= 0.25 {
s[O2] += 1.5;
s[O3] += 1.5;
s[OS] += 0.5;
s[O1] -= 1.5;
s[OG] -= 1.5;
} else if sep <= 0.10 && nb >= 8 {
s[O1] += 1.0;
s[OG] += 1.0;
s[O2] -= 1.0;
s[O3] -= 1.0;
}
}
let na = f.starts_padded + f.starts_unpadded;
if na > 0 {
ev.push(format!(
"{} of {na} function starts that needed padding for 4-byte alignment received it (-O2/-O3 align functions)",
f.starts_padded
));
let w = na.min(3) as f32 / 3.0;
let padded = f.starts_padded as f32 / na as f32;
if padded >= 0.75 {
s[O2] += 1.5 * w;
s[O3] += 1.5 * w;
for l in [O1, OS, OG] {
s[l] -= 1.5 * w;
}
} else if padded <= 0.34 {
s[O2] -= 2.0 * w;
s[O3] -= 2.0 * w;
for l in [O1, OS, OG] {
s[l] += 0.5 * w;
}
}
}
if f.it_blocks == 0 && nb >= 6 {
ev.push("no IT blocks despite conditional code: little if-conversion (-Og/-O0)".into());
s[OG] += 0.5;
} else if f.it_blocks > 0 {
ev.push(format!("{} IT blocks (if-conversion: -O1 and up, -Os)", f.it_blocks));
s[OG] -= 0.5;
}
let mut o3 = 0.0;
if f.clones > 0 {
ev.push(format!(
"{} function clone symbols (.constprop/.isra/.part): interprocedural cloning",
f.clones
));
o3 += 1.0;
}
if f.windows >= 40 {
let dup = f.repeated_windows as f32 / f.windows as f32;
ev.push(format!(
"{:.0}% of instruction windows repeat within their function (unrolling, peeling and loop versioning duplicate code at -O3)",
dup * 100.0
));
if dup >= 0.08 {
o3 += 2.5;
} else if dup <= 0.04 && loops >= 2 {
o3 -= 1.0;
}
}
if f.loops_rotated > 0 && f.loops_with_remainder > 0 {
ev.push(format!(
"{} of {} bottom-tested loops are followed by remainder handling{}",
f.loops_with_remainder,
f.loops_rotated,
if f.dual_accesses > 0 {
format!("; {} paired memory accesses", f.dual_accesses)
} else {
String::new()
}
));
if f.loops_with_remainder * 4 >= f.loops_rotated {
o3 += 1.0;
}
}
s[O3] += o3;
if o3 > 0.0 {
s[O2] -= o3;
}
if o3 == 0.0 {
ev.push("nothing distinguishes -O2 from -O3 in this code".into());
}
let max = s.iter().cloned().fold(f32::MIN, f32::max);
let exp: Vec<f32> = s.iter().map(|x| (x - max).exp()).collect();
let total: f32 = exp.iter().sum();
let mut cands: Vec<(OptLevel, f32)> = OptLevel::ALL.iter().zip(&exp).map(|(&l, &e)| (l, e / total)).collect();
cands.sort_by(|a, b| b.1.total_cmp(&a.1));
report.candidates = cands;
if let Some(decl) = image.producer.as_deref().and_then(declared_level)
&& let Some(best) = report.best()
{
let conf = report.candidates.iter().find(|c| c.0 == decl).map_or(0.0, |c| c.1);
if conf < report.candidates[0].1 * 0.5 {
report.evidence.push(format!(
"the code looks like {best}, which disagrees with the declared {decl}"
));
}
}
report
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn declared_flag_parsing() {
assert_eq!(
declared_level("GNU C17 16.2.1 -mthumb -mcpu=cortex-m3 -g -O2"),
Some(OptLevel::O2)
);
assert_eq!(declared_level("GNU C17 -Os -O3"), Some(OptLevel::O3));
assert_eq!(declared_level("GNU C17 13.2.1 -mthumb -g"), None);
assert_eq!(OptLevel::Og.to_string(), "-Og");
}
#[test]
fn empty_image_has_no_candidates() {
let r = detect(&Image::default());
assert!(r.candidates.is_empty());
assert_eq!(r.best(), None);
}
}