Skip to main content

ddc_dec/
method.rs

1//! Per-method decompilation pipeline:
2//! DEX code units → CFG → register→IR lifting (fixpoint with merge phis) →
3//! `jdc-core` structuring → statement conversion → refinement passes.
4
5use jdc_core::FxHashMap as HashMap;
6
7use ddc_dex::insn::InsnKind;
8use jdc_core::convert::Converter;
9use jdc_core::ir::build::BlockResult;
10use jdc_core::ir::expr::{Expr, TypeRef};
11use jdc_core::ir::stmt::Stmt;
12use jdc_core::structure::{reverse_postorder, Structurer};
13use jdc_core::types::{JavaType, MethodDescriptor};
14use jdc_core::var::VarTable;
15
16use crate::cfg::DexCfg;
17use crate::lift::{entry_regs, Lifter, MethodEnv, OutState, Reg};
18use crate::passes;
19use crate::{DexPool, PoolClass, PoolMethod};
20
21pub struct MethodBody {
22    pub body: Stmt,
23    pub vt: VarTable,
24    pub desc: MethodDescriptor,
25}
26
27/// Catch types for the ranges a block handles (drives move-exception typing).
28/// Debug-env reads, cached: `env::var` is an environ lock+scan — a
29/// per-METHOD cost across 716k methods shows up as __NSGetEnviron in
30/// profiles. Once per process is the right granularity.
31fn trace_on() -> bool {
32    static T: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
33    *T.get_or_init(|| std::env::var("DDC_TRACE").is_ok())
34}
35
36fn walk_budget_override() -> Option<u64> {
37    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
38    *T.get_or_init(|| {
39        std::env::var("DDC_WALKBUDGET")
40            .ok()
41            .and_then(|v| v.parse().ok())
42    })
43}
44
45fn walk_work_override() -> Option<u64> {
46    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
47    *T.get_or_init(|| {
48        std::env::var("DDC_WALKWORK")
49            .ok()
50            .and_then(|v| v.parse().ok())
51    })
52}
53
54fn walk_ms_override() -> Option<u64> {
55    static T: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
56    *T.get_or_init(|| std::env::var("DDC_WALKMS").ok().and_then(|v| v.parse().ok()))
57}
58
59fn handler_types_for(cfg: &DexCfg, bid: usize) -> Vec<Option<std::sync::Arc<str>>> {
60    cfg.blocks[bid]
61        .handlers
62        .iter()
63        .filter_map(|&ri| cfg.exc_ranges.get(ri).map(|r| r.catch_type.clone()))
64        .collect()
65}
66
67/// Decompile one method. `Err` only for malformed input; unsupported
68/// constructs degrade to comments inside the statement tree.
69pub fn decompile_method(
70    pool: &DexPool,
71    class: &PoolClass,
72    m: &PoolMethod,
73) -> Result<Option<MethodBody>, String> {
74    let t0 = std::time::Instant::now();
75    if m.is_abstract_or_native() {
76        return Ok(None);
77    }
78    let desc = m
79        .parsed_desc()
80        .ok_or_else(|| format!("bad descriptor {}", m.desc))?;
81    let dex = pool.dex(m.dex_idx).ok_or("missing dex image")?;
82    let dex = &*dex;
83    let Some(mut code) = dex.code_at(m.code_off) else {
84        return Ok(None);
85    };
86    let insn_count = code.insns.len();
87    let param_names = dex.parameter_names(m.debug_info_off);
88    // Pool-cached Arc class names: the closure ran dex.class_name
89    // (fresh String) per exception range of every method.
90    let cfg = DexCfg::build(&mut code, &|ty| pool.type_name_arc(m.dex_idx, ty));
91    let n = cfg.blocks.len();
92    let env = MethodEnv {
93        pool,
94        di: m.dex_idx,
95        dex,
96        code: &code,
97        class_name: class.name.clone(),
98        method_name: m.name.clone(),
99        desc: desc.clone(),
100        debug_locals: dex.debug_locals(m.debug_info_off),
101        is_static: m.is_static(),
102        code_units: cfg.code_units,
103    };
104    let mut vt = VarTable::default();
105    let entry = entry_regs(&mut vt, &env, &param_names);
106    if n == 0 {
107        return Ok(None);
108    }
109    // Pathological inputs (R8-merged model classes, obfuscated switch
110    // cascades) can explode the copied-tail rendering; guard up front.
111    if insn_count > 30_000 || n > 8_000 {
112        return Ok(Some(stub_body(
113            format!(
114                "$DDC: method too large to decompile ({} insns, {} blocks)",
115                insn_count, n
116            ),
117            desc,
118        )));
119    }
120
121    // Visiting order: reverse postorder, then any stragglers (so every block
122    // is built at least once even when unreachable).
123    let core_for_order = cfg.to_core();
124    let universe: jdc_core::FxHashSet<usize> = (0..n).collect();
125    let mut order = reverse_postorder(&core_for_order, core_for_order.entry, &universe);
126    {
127        let mut seen: jdc_core::FxHashSet<usize> = order.iter().copied().collect();
128        for b in &cfg.blocks {
129            if seen.insert(b.id) {
130                order.push(b.id);
131            }
132        }
133    }
134
135    // Handler blocks: entry state approximated by the try-entry state (the
136    // dominant pattern: catch reads values established before the try).
137    let mut handler_entry_block: HashMap<usize, usize> = HashMap::default();
138    for b in &cfg.blocks {
139        if b.handlers.is_empty() {
140            continue;
141        }
142        let mut best: Option<(u32, usize)> = None;
143        for &ri in &b.handlers {
144            if let Some(r) = cfg.exc_ranges.get(ri) {
145                if best.map(|(s, _)| r.start < s).unwrap_or(true) {
146                    if let Some(eb) = cfg.block_at(r.start) {
147                        best = Some((r.start, eb));
148                    }
149                }
150            }
151        }
152        if let Some((_, eb)) = best {
153            handler_entry_block.insert(b.id, eb);
154        }
155    }
156
157    // ---- fixpoint: register states across blocks ----
158    let mut results: Vec<BlockResult> = Vec::with_capacity(n);
159    results.resize_with(n, || BlockResult {
160        stmts: vec![],
161        out_stack: vec![],
162        term: jdc_core::ir::build::Term::Return(None),
163    });
164    let mut out_states: Vec<Option<OutState>> = vec![None; n];
165    // Stable (block, register) → var ids across worklist rebuilds: keeps
166    // re-lifts id-deterministic so the fixpoint CONVERGES instead of
167    // cascading (was: 30M block-lifts on weibo, ~60 per block).
168    let mut stable_vars: HashMap<(usize, u16, u64), u32> = HashMap::default();
169    // Method feature flags OR-merged from every block lift: gates
170    // post-lift passes that can only match if the bytecode contained the
171    // feature (most methods contain none).
172    let mut mflags = crate::lift::MethodFlags::none();
173    // Try-entry INPUT snapshots (for handler-block approximation) — only
174    // try-entry starts (rare) keep their input state; no persistent
175    // per-block copies.
176    let mut try_entry_snapshots: HashMap<usize, Vec<Reg>> = HashMap::default();
177    let mut built_once = vec![false; n];
178    let mut errors: HashMap<usize, String> = HashMap::default();
179    // (merge block, register) → phi var id.
180    let mut phis: HashMap<(usize, u16), u32> = HashMap::default();
181    // pred → (write_pc, phi var, value) materializations.
182
183    let entry_is_handler = handler_entry_block.contains_key(&0);
184
185    // Per-visit costs hoisted out of the worklist loop: the try-entry scan
186    // (all exc ranges × a binary search per range) and the handler catch
187    // types (String clones) re-ran on EVERY visit — visits average 2.5×
188    // blocks on real code, far more on monsters.
189    let try_entry_flags: Vec<bool> = (0..n)
190        .map(|b| {
191            !cfg.blocks[b].handlers.is_empty()
192                || cfg
193                    .exc_ranges
194                    .iter()
195                    .any(|r| cfg.block_at(r.start) == Some(b))
196        })
197        .collect();
198    let handler_types: Vec<Vec<Option<std::sync::Arc<str>>>> =
199        (0..n).map(|b| handler_types_for(&cfg, b)).collect();
200
201    // Worklist fixpoint with version stamps: a block rebuilds only when the
202    // OUT-state versions of its inputs changed. This avoids the previous
203    // every-round full pass, which deep-cloned and deep-compared the whole
204    // register state (Expr trees) of every block — the dominant cost of
205    // large methods.
206    let mut ver: Vec<u64> = vec![0; n]; // out-state version per block
207    let mut built_ver: Vec<u64> = vec![u64::MAX; n]; // input signature when built
208                                                     // input signature: entry=0; otherwise XOR/sum of (pred, ver[pred]) pairs.
209    fn input_sig(cfg: &DexCfg, bid: usize, ver: &[u64]) -> u64 {
210        let mut h: u64 = 1;
211        for &p in &cfg.blocks[bid].pred {
212            h = h
213                .wrapping_mul(31)
214                .wrapping_add(p as u64)
215                .wrapping_mul(31)
216                .wrapping_add(ver[p]);
217        }
218        // Handler blocks also depend on their try-entry block's input.
219        h
220    }
221    let mut queue: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
222    let mut queued: Vec<bool> = vec![false; n];
223    for &bid in &order {
224        queue.push_back(bid);
225        queued[bid] = true;
226    }
227    // merge bid → [(pred, write_pc, phi var, value)] — re-recorded whole on
228    // each visit of the merge block (stale rounds must not accumulate).
229    let mut appends: HashMap<usize, Vec<(usize, u32, u32, Expr)>> = HashMap::default();
230    let mut total_visits: usize = 0;
231    let visit_cap: usize = 64 * n + 256;
232
233    while let Some(bid) = queue.pop_front() {
234        queued[bid] = false;
235        total_visits += 1;
236        if total_visits > visit_cap {
237            CAP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
238            CAP_INSNS.fetch_add(
239                insn_count as u64 * 1000 + n as u64,
240                std::sync::atomic::Ordering::Relaxed,
241            );
242            break; // degenerate oscillation guard
243        }
244        let is_handler = handler_entry_block.contains_key(&bid);
245        // 1. Signature gate FIRST: a visit whose input versions are
246        //    unchanged skips the (clone-heavy) input-state computation
247        //    entirely — that clone was the fixpoint's dominant cost.
248        let sig = input_sig(&cfg, bid, &ver)
249            ^ (if is_handler {
250                let eb = handler_entry_block[&bid];
251                (eb as u64) << 32
252            } else {
253                0
254            });
255        let need_build = !built_once[bid] || built_ver[bid] != sig;
256        if !need_build {
257            // Handler blocks depend on their try-entry block's INPUT —
258            // when that entry is re-visited, the handler is re-queued; a
259            // skipped visit here means the recorded state is current.
260            continue;
261        }
262        // 2. Input register state (only on rebuild).
263        let ins: Vec<Reg> = if bid == cfg.entry {
264            if cfg.blocks[0].pred.is_empty() || entry_is_handler {
265                entry.clone()
266            } else {
267                // A loop back into pc 0: params are one side of the merge.
268                // Sides are BORROWED (cloning each pred's state here was a
269                // top fixpoint cost).
270                let mut sides: Vec<&[Reg]> = vec![entry.as_slice()];
271                for p in cfg.blocks[bid].pred.clone() {
272                    if let Some(o) = &out_states[p] {
273                        sides.push(o.regs.as_slice());
274                    }
275                }
276                let merged =
277                    merge_states(&mut vt, &mut phis, bid, &sides, &env.debug_locals, cfg.blocks[bid].start);
278                // The entry side's phi contributions become leading
279                // assignments in the entry block (virtual pred). The entry
280                // block may be re-visited by the worklist — each visit
281                // replaces (not appends) its records.
282                let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
283                for (r, st) in entry.iter().enumerate() {
284                    if let Some(&phi) = phis.get(&(bid, r as u16)) {
285                        let value = match st {
286                            Reg::Live(v) if *v == phi => continue,
287                            Reg::Live(v) => Expr::Local {
288                                var: *v,
289                                ty: vt.var(*v).ty.clone(),
290                            },
291                            Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
292                            Reg::Undef | Reg::WideHi => continue,
293                        };
294                        recs.push((usize::MAX, 0, phi, value));
295                    }
296                }
297                appends.insert(bid, recs);
298                merged
299            }
300        } else if is_handler {
301            let eb = handler_entry_block[&bid];
302            try_entry_snapshots
303                .get(&eb)
304                .cloned()
305                .unwrap_or_else(|| vec![Reg::Undef; env.code.registers_size as usize])
306        } else {
307            // Borrowed sides; the single-pred fast path clones once (the
308            // lifter needs an owned copy anyway).
309            let mut sides: Vec<&[Reg]> = Vec::new();
310            for p in cfg.blocks[bid].pred.clone() {
311                if let Some(o) = &out_states[p] {
312                    sides.push(o.regs.as_slice());
313                }
314            }
315            if sides.is_empty() {
316                vec![Reg::Undef; env.code.registers_size as usize]
317            } else if sides.len() == 1 {
318                sides[0].to_vec()
319            } else {
320                merge_states(
321                    &mut vt,
322                    &mut phis,
323                    bid,
324                    &sides,
325                    &env.debug_locals,
326                    cfg.blocks[bid].start,
327                )
328            }
329        };
330
331        // 3. Phi materialization records for predecessors — recomputed for
332        //    this block only; later pred rebuilds re-visit the merge and
333        //    refresh them (the last visit wins).
334        if phis_for_merge(bid, &phis) {
335            let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
336            record_appends(&cfg, bid, &out_states, &phis, &vt, &mut recs);
337            // Entry-merge visits also carry the entry-side contributions —
338            // preserve those (recorded above when bid == entry).
339            if bid == cfg.entry {
340                if let Some(prev) = appends.get(&bid) {
341                    for (p, pc, v, e) in prev.iter() {
342                        if *p == usize::MAX {
343                            recs.push((*p, *pc, *v, e.clone()));
344                        }
345                    }
346                }
347            }
348            appends.insert(bid, recs);
349        }
350
351        // 4. Build (signature known changed). The lifter CONSUMES `ins`
352        //    (moved, not cloned); try-entry snapshots preserve the input
353        //    state for the handler blocks approximating from it.
354        built_once[bid] = true;
355        built_ver[bid] = sig;
356        if try_entry_flags[bid] {
357            try_entry_snapshots.insert(bid, ins.clone());
358        }
359        BUILD_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
360        INSN_LIFTED.fetch_add(
361            cfg.block_ins(&cfg.blocks[bid]).len() as u64,
362            std::sync::atomic::Ordering::Relaxed,
363        );
364        let htypes = &handler_types[bid];
365        let block_ins = cfg.block_ins(&cfg.blocks[bid]);
366        let lifter = Lifter::new(&env, &mut vt, ins, bid, &mut stable_vars, &mut mflags);
367        let rebuilt = match lifter.build_block(block_ins, htypes) {
368            Ok((r, out)) => {
369                results[bid] = r;
370                let changed = match &out_states[bid] {
371                    Some(prev) => prev.regs != out.regs,
372                    None => true,
373                };
374                out_states[bid] = Some(out);
375                changed
376            }
377            Err(msg) => {
378                results[bid] = BlockResult {
379                    stmts: vec![Stmt::Comment(format!("$DDC-BLOCK-ERROR: {msg}"))],
380                    out_stack: vec![],
381                    term: jdc_core::ir::build::Term::Return(None),
382                };
383                out_states[bid] = Some(OutState {
384                    regs: vec![Reg::Undef; env.code.registers_size as usize],
385                    write_pc: vec![0; env.code.registers_size as usize],
386                });
387                errors.insert(bid, msg);
388                false
389            }
390        };
391        if rebuilt {
392            ver[bid] += 1;
393            // Successors re-check their input signature.
394            for &succ in &cfg.blocks[bid].succ {
395                if !queued[succ] && succ < n {
396                    queue.push_back(succ);
397                    queued[succ] = true;
398                }
399            }
400            // Handler blocks watch their try-entry block's INPUT — cheap
401            // approximation: also queue the handler of every range this
402            // block belongs to.
403            if is_handler {
404                let eb = handler_entry_block[&bid];
405                if !queued[eb] && eb < n {
406                    queue.push_back(eb);
407                    queued[eb] = true;
408                }
409            }
410            // Try-entry inputs: when this block feeds a handler entry via a
411            // try range, queue that handler.
412            for &ri in &cfg.blocks[bid].handlers {
413                if let Some(r) = cfg.exc_ranges.get(ri) {
414                    if let Some(hb) = cfg.block_at(r.handler) {
415                        if !queued[hb] && hb < n {
416                            queue.push_back(hb);
417                            queued[hb] = true;
418                        }
419                    }
420                }
421            }
422        }
423    }
424
425    // Entry-side phi contributions: carried as declaration-with-init and
426    // prepended to the method body AFTER conversion (the entry block may be
427    // a loop header — its statements re-execute per iteration).
428    // Entry-side phi contributions (the virtual pred): captured for the
429    // method-top declarations; the REAL preds' records stay in `appends`
430    // for the commit loop (removing the whole entry key would lose the
431    // loop-body assignments — the phis would collapse to their entry
432    // values).
433    let mut entry_phi_inits: Vec<(u32, Expr)> = Vec::new();
434    if let Some(recs) = appends.get_mut(&cfg.entry) {
435        let mut entry_side: Vec<(u32, Expr)> = Vec::new();
436        recs.retain(|(p, _, v, e)| {
437            if *p == usize::MAX {
438                entry_side.push((*v, e.clone()));
439                false
440            } else {
441                true
442            }
443        });
444        entry_side.sort_by_key(|(v, _)| *v);
445        entry_phi_inits = entry_side;
446    }
447
448    // Commit phi materializations: each pred assigns its outgoing value to
449    // the merge var, ordered by the pc of the instruction that produced it.
450    // Values that REFERENCE a sibling phi are snapshotted into a fresh temp
451    // first: register rotations (`a = b; b = a % b`) would otherwise read
452    // the already-reassigned phi (stale capture).
453    // Regroup: merge-keyed records → per-pred statement lists.
454    //
455    // Deterministic order: `adds.sort_by_key(pc)` below is a STABLE sort,
456    // so same-pc records (one jump feeding several merge vars) keep
457    // their push order — iterating `appends` in map order made that
458    // order hasher-dependent (SipHash seeds per process: output was NOT
459    // byte-stable across runs; 243/5579 files wobbled on reqable).
460    // Sorted block ids here + sorted preds below pin every tie.
461    let mut merge_order: Vec<usize> = appends.keys().copied().collect();
462    merge_order.sort_unstable();
463    let mut per_pred: HashMap<usize, Vec<(u32, u32, Expr)>> = HashMap::default();
464    for bid in merge_order {
465        for (p, pc, v, e) in &appends[&bid] {
466            per_pred.entry(*p).or_default().push((*pc, *v, e.clone()));
467        }
468    }
469    let mut pred_order: Vec<usize> = per_pred.keys().copied().collect();
470    pred_order.sort_unstable();
471    for p in pred_order {
472        let mut adds = per_pred.remove(&p).unwrap();
473        if p == usize::MAX {
474            continue;
475        }
476        adds.sort_by_key(|(pc, _, _)| *pc);
477        let term_is_exit = matches!(
478            results[p].term,
479            jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
480        );
481        if term_is_exit {
482            continue;
483        }
484        let phi_set: std::collections::HashSet<u32> = adds.iter().map(|(_, v, _)| *v).collect();
485        let mut snapshots: Vec<Stmt> = Vec::new();
486        // (phi, value) pairs with snapshot temps substituted.
487        let mut emitted: Vec<(u32, Expr)> = Vec::new();
488        for (_, v, e) in &adds {
489            let mut e = e.clone();
490            let mut refs_phi = false;
491            visit_phi_refs(&e, &phi_set, &mut refs_phi);
492            if refs_phi {
493                // Snapshot: emit `temp = value` BEFORE any phi assignment.
494                let ty = e.type_ref();
495                let id = vt.vars.len() as u32;
496                let name = format!("v{}", id);
497                vt.vars.push(jdc_core::var::VarInfo {
498                    id,
499                    slot: u16::MAX,
500                    name,
501                    ty: ty.clone(),
502                    is_param: false,
503                    range_start: 0,
504                    range_end: u16::MAX,
505                    synthetic_name: true,
506                });
507                snapshots.push(Stmt::LocalDef {
508                    var: id,
509                    init: Some(e),
510                    is_final: false,
511                    force_type: true,
512                });
513                e = Expr::Local { var: id, ty };
514            }
515            emitted.push((*v, e));
516        }
517        for st in snapshots {
518            results[p].stmts.push(st);
519        }
520        for (v, e) in emitted {
521            results[p].stmts.push(Stmt::ExprStmt(Expr::Assign {
522                target: Box::new(Expr::Local {
523                    var: v,
524                    ty: vt.var(v).ty.clone(),
525                }),
526                op: jdc_core::ir::expr::AssignOp::Plain,
527                value: Box::new(e),
528            }));
529        }
530    }
531
532    let t_fix = t0;
533    phase_hit_n(0, n, t_fix);
534    // ---- single-block fast path ----
535    // A lone basic block is straight-line code (any branch/switch/handler
536    // splits the graph): no merges, no phis, no control flow to structure.
537    // Bypassing the structurer + converter + the control-flow passes for
538    // these (over half of R8-produced methods) cuts the dominant cost.
539    if n == 1 && !entry_is_handler && cfg.blocks[0].pred.is_empty() {
540        let r = std::mem::replace(
541            &mut results[0],
542            BlockResult {
543                stmts: vec![],
544                out_stack: vec![],
545                term: jdc_core::ir::build::Term::Goto,
546            },
547        );
548        let mut body = r.stmts;
549        match r.term {
550            jdc_core::ir::build::Term::Return(Some(e)) => {
551                body.push(Stmt::Return(Some(e)));
552            }
553            jdc_core::ir::build::Term::Return(None) => {}
554            jdc_core::ir::build::Term::Throw(e) => body.push(Stmt::Throw(e)),
555            _ => {}
556        }
557        let mut body = Stmt::Block(body);
558        passes::fused_expr_rewrites(&mut body, &vt);
559        if mflags.has_sb() {
560            passes::fold_string_builders(&mut body, &vt);
561        }
562        passes::forward_single_use(&mut body, &vt);
563        passes::cleanup(&mut body);
564        passes::inline_accessors(&mut body, pool);
565        passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
566        passes::insert_object_narrowing_casts(&vt, &mut body);
567        passes::apply_local_names(&mut vt, &body);
568        passes::remove_kotlin_checks(&mut body);
569        passes::platform_constants(&mut body);
570        passes::drop_dead_locals(&mut body);
571    passes::ensure_declared(&mut body, &vt);
572    // AFTER the declaration hoisting: ensure_declared inserts bare
573    // top-of-method declarations, and a local declaration ahead of the
574    // super() call is still "super must be first statement".
575    if &*m.name == "<init>" {
576        if class.is_enum() {
577            passes::strip_enum_ctor_super(&mut body);
578        } else {
579            passes::fix_ctor_conditional_super(&mut body);
580            passes::fix_ctor_super_first(&mut body);
581            passes::dedupe_ctor_delegations(&mut body);
582        }
583    }
584        passes::strip_trailing_void_return(&mut body);
585        passes::cleanup(&mut body);
586        passes::invert_empty_thens(&mut body);
587        passes::fold_short_circuits(&mut body);
588        if !errors.is_empty() {
589            passes::prepend_comment(
590                &mut body,
591                format!("$DDC: {} block(s) failed to decompile", errors.len()),
592            );
593        }
594        phase_hit_n(2, n, t_fix);
595        record_bucket(n, t0);
596        return Ok(Some(MethodBody { body, vt, desc }));
597    }
598
599    // ---- structure + convert ----
600    // jcdc's copy-budget degradation: a rendering whose statement tree
601    // explodes past the guard retries at a halved copy budget (the
602    // structurer's tail-copying is the exponential mechanism).
603    const TREE_GUARD: usize = 20_000;
604    let core_cfg = cfg.to_core();
605    #[allow(unused_assignments)]
606    let mut body: Option<Stmt> = None;
607    // Copy budget scales with graph size: many-block methods are where the
608    // exponential tail-copy blowups live (weibo: 389 methods >100 blocks
609    // = 40% of all CPU at budget 512). Starting lower converges without
610    // the 6-round halving.
611    let mut budget: u32 = if n > 100 {
612        64
613    } else if n > 20 {
614        128
615    } else {
616        512
617    };
618    // Shared once-per-method artifacts: the O(groups²) exception-group
619    // scan and the full-graph dominator tree used to run TWICE per
620    // method (Structurer + Converter) and once more per copy-budget
621    // retry — monster classes (gson adapters) spent the bulk of their
622    // time there.
623    let groups = jdc_core::structure::group_exceptions_with(&core_cfg, Some(&results));
624    let dom_universe: jdc_core::FxHashSet<usize> = (0..core_cfg.blocks.len()).collect();
625    let dom = jdc_core::structure::compute_dominators(&core_cfg, &dom_universe, core_cfg.entry);
626    if trace_on() {
627        eprintln!("[mshape] {}.{} blocks={}", class.name, m.name, n);
628    }
629    #[cfg(feature = "visit-stats")]
630    {
631        jdc_core::structure::reset_visit_stats();
632    }
633    // Walk-visit budget, proportional to the block count: walk() runs
634    // roughly once per structured scope for sane CFGs, so 40n+512 is
635    // generous headroom — but the EXPONENTIAL explorations (Telegram
636    // SendMessagesHelper family: deep if/loop/try nesting whose scope
637    // count multiplies) consume visits geometrically and get cut to a
638    // Goto, which terminates the walk. Without this a single <16k-insn
639    // method can recurse for effectively forever while the worker (and
640    // the process) never finishes — Telegram's full run wrote every file
641    // yet hung for 300+ seconds on 25 such classes.
642    let walk_budget: u64 = walk_budget_override().unwrap_or(8 * n as u64 + 128);
643    // WORK budget (Σ universe.len() per visit): deterministic bound on
644    // total walk cost — the count budget above under-bounds per-visit
645    // cost for big-block exponential explorations (Telegram family),
646    // which the wall-clock deadline used to catch nondeterministically.
647    // 2M sits 10× above the 4-corpus legit census max (~203k work), so
648    // it never fires on healthy classes (battery outputs stay
649    // byte-identical — the count budget keeps cutting exactly where it
650    // always did) while bounding Telegram-scale explosions at ~2M work
651    // units regardless of machine load.
652    let walk_work_budget: u64 = walk_work_override()
653        .unwrap_or(2_000_000 + 128 * n as u64);
654    // Wall-clock guard — UNCHANGED original 1500ms. (It was briefly
655    // suspected of the run-to-run output flips under worker contention
656    // and scaled up; the real culprit was the shared static DUMMY in
657    // VarTable::var — fixed in jdc-core — and the larger deadlines only
658    // let pathological walks burn seconds longer: weixin +3s at 5.5s,
659    // +3.5s more at 46s. Legit methods finish ~10× under this bound.)
660    let walk_deadline = std::time::Instant::now()
661        + std::time::Duration::from_millis(
662            walk_ms_override().unwrap_or(1500),
663        );
664    loop {
665        jdc_core::structure::set_budget_override(Some(budget));
666        jdc_core::structure::set_walk_visit_budget(Some(walk_budget));
667        jdc_core::structure::set_walk_work_budget(Some(walk_work_budget));
668        jdc_core::structure::set_walk_deadline(Some(walk_deadline));
669        let mut st = Structurer::with_shared_groups(
670            &core_cfg,
671            &results,
672            &groups,
673            Default::default(),
674            Default::default(),
675        );
676        let region = st.structure_method();
677        let mut converter = Converter::with_precomputed_ref(&core_cfg, &results, &groups, &dom);
678        let candidate = converter.convert(region);
679        jdc_core::structure::set_budget_override(None);
680        jdc_core::structure::set_walk_visit_budget(None);
681        jdc_core::structure::set_walk_work_budget(None);
682        jdc_core::structure::set_walk_deadline(None);
683        let size = {
684            let mut c = 0usize;
685            passes::count_stmts_deep(&candidate, &mut c);
686            c
687        };
688        if trace_on() {
689            eprintln!("[guard] {}.{} size={} budget={}", class.name, m.name, size, budget);
690        }
691        if size <= TREE_GUARD {
692            body = Some(candidate);
693            break;
694        }
695        if budget <= 16 {
696            return Ok(Some(stub_body(
697                format!(
698                    "$DDC: statement tree exploded ({} nodes) even at copy budget 16",
699                    size
700                ),
701                desc,
702            )));
703        }
704        budget /= 2;
705    }
706    #[cfg(feature = "visit-stats")]
707    if trace_on() && n > 3 {
708        let used = jdc_core::structure::walk_visits_consumed();
709        eprintln!(
710            "[visits] {}.{} blocks={} consumed={} ratio={:.1}",
711            class.name,
712            m.name,
713            n,
714            used,
715            used as f64 / n as f64
716        );
717    }
718    phase_hit_n(1, n, t_fix);
719    let mut body = body.unwrap();
720    if !entry_phi_inits.is_empty() {
721        let head: Vec<Stmt> = entry_phi_inits
722            .into_iter()
723            .map(|(v, e)| Stmt::LocalDef {
724                var: v,
725                init: Some(e),
726                is_final: false,
727                force_type: true,
728            })
729            .collect();
730        body = match body {
731            Stmt::Block(v) => {
732                let mut nv = head;
733                nv.extend(v);
734                Stmt::Block(nv)
735            }
736            other => {
737                let mut nv = head;
738                nv.push(other);
739                Stmt::Block(nv)
740            }
741        };
742    }
743
744    passes::bind_catches(&mut body, &mut vt);
745    passes::prune_unreachable(&mut body);
746    // One traversal for cmp residuals + null compares + const-first flips
747    // (three separate full-tree walks before).
748    passes::fused_expr_rewrites(&mut body, &vt);
749    if mflags.has_sb() {
750        passes::fold_string_builders(&mut body, &vt);
751    }
752    passes::ternary_fold(&mut body);
753    if mflags.has_monitor() {
754        passes::fold_synchronized(&mut body);
755    }
756    passes::forward_single_use(&mut body, &vt);
757    passes::cleanup(&mut body);
758    passes::inline_accessors(&mut body, pool);
759    passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
760    passes::booleanize(&mut vt, &mut body, matches!(desc.ret, JavaType::Boolean));
761    passes::insert_object_narrowing_casts(&vt, &mut body);
762    passes::apply_local_names(&mut vt, &body);
763    passes::remove_kotlin_checks(&mut body);
764    passes::platform_constants(&mut body);
765    passes::drop_dead_locals(&mut body);
766    passes::ensure_declared(&mut body, &vt);
767    // AFTER the declaration hoisting: ensure_declared inserts bare
768    // top-of-method declarations, and a local declaration ahead of the
769    // super() call is still "super must be first statement".
770    if &*m.name == "<init>" {
771        if class.is_enum() {
772            passes::strip_enum_ctor_super(&mut body);
773        } else {
774            passes::fix_ctor_conditional_super(&mut body);
775            passes::fix_ctor_super_first(&mut body);
776            passes::dedupe_ctor_delegations(&mut body);
777        }
778    }
779    if &*m.name == "<clinit>" {
780        passes::strip_clinit_returns(&mut body);
781    }
782    passes::strip_trailing_void_return(&mut body);
783    passes::cleanup(&mut body);
784    // Short-circuit folding last: the diamond shapes are final only
785    // after cleanup merges singleton blocks.
786    passes::invert_empty_thens(&mut body);
787    passes::fold_short_circuits(&mut body);
788
789    if !errors.is_empty() {
790        passes::prepend_comment(
791            &mut body,
792            format!("$DDC: {} block(s) failed to decompile", errors.len()),
793        );
794    }
795
796    phase_hit_n(2, n, t_fix);
797    record_bucket(n, t0);
798    Ok(Some(MethodBody { body, vt, desc }))
799}
800
801static PHASE_MICROS: [std::sync::atomic::AtomicU64; 5] = [
802    std::sync::atomic::AtomicU64::new(0),
803    std::sync::atomic::AtomicU64::new(0),
804    std::sync::atomic::AtomicU64::new(0),
805    std::sync::atomic::AtomicU64::new(0),
806    std::sync::atomic::AtomicU64::new(0),
807];
808/// Phase × bucket attribution (5 phases × 5 buckets, row-major).
809static PHASE_BUCKET_MICROS: [std::sync::atomic::AtomicU64; 25] = [
810    std::sync::atomic::AtomicU64::new(0),
811    std::sync::atomic::AtomicU64::new(0),
812    std::sync::atomic::AtomicU64::new(0),
813    std::sync::atomic::AtomicU64::new(0),
814    std::sync::atomic::AtomicU64::new(0),
815    std::sync::atomic::AtomicU64::new(0),
816    std::sync::atomic::AtomicU64::new(0),
817    std::sync::atomic::AtomicU64::new(0),
818    std::sync::atomic::AtomicU64::new(0),
819    std::sync::atomic::AtomicU64::new(0),
820    std::sync::atomic::AtomicU64::new(0),
821    std::sync::atomic::AtomicU64::new(0),
822    std::sync::atomic::AtomicU64::new(0),
823    std::sync::atomic::AtomicU64::new(0),
824    std::sync::atomic::AtomicU64::new(0),
825    std::sync::atomic::AtomicU64::new(0),
826    std::sync::atomic::AtomicU64::new(0),
827    std::sync::atomic::AtomicU64::new(0),
828    std::sync::atomic::AtomicU64::new(0),
829    std::sync::atomic::AtomicU64::new(0),
830    std::sync::atomic::AtomicU64::new(0),
831    std::sync::atomic::AtomicU64::new(0),
832    std::sync::atomic::AtomicU64::new(0),
833    std::sync::atomic::AtomicU64::new(0),
834    std::sync::atomic::AtomicU64::new(0),
835];
836static PHASE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
837
838fn bucket_of(n: usize) -> usize {
839    if n <= 1 {
840        0
841    } else if n <= 5 {
842        1
843    } else if n <= 20 {
844        2
845    } else if n <= 100 {
846        3
847    } else {
848        4
849    }
850}
851
852pub(crate) fn phase_hit_n(i: usize, n: usize, t: std::time::Instant) {
853    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
854        return;
855    }
856    let us = t.elapsed().as_micros() as u64;
857    PHASE_MICROS[i].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
858    PHASE_BUCKET_MICROS[i * 5 + bucket_of(n)].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
859}
860
861pub(crate) fn phase_hit(i: usize, t: std::time::Instant) {
862    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
863        return;
864    }
865    PHASE_MICROS[i].fetch_add(
866        t.elapsed().as_micros() as u64,
867        std::sync::atomic::Ordering::Relaxed,
868    );
869}
870
871/// Enable phase timers (DDC_PHASES=1).
872pub fn phases_enable() {
873    PHASE_ON.store(true, std::sync::atomic::Ordering::Relaxed);
874}
875
876/// (fixpoint, structure+convert, passes, print, total) in micros.
877pub fn phases_dump() -> [u64; 5] {
878    let mut out = [0u64; 5];
879    for i in 0..5 {
880        out[i] = PHASE_MICROS[i].load(std::sync::atomic::Ordering::Relaxed);
881    }
882    out
883}
884
885/// Per-bucket phase micros: 5 phases × 5 buckets, row-major.
886pub fn phases_bucket_dump() -> [[u64; 5]; 5] {
887    let mut out = [[0u64; 5]; 5];
888    for i in 0..5 {
889        for b in 0..5 {
890            out[i][b] = PHASE_BUCKET_MICROS[i * 5 + b].load(std::sync::atomic::Ordering::Relaxed);
891        }
892    }
893    out
894}
895
896static CAP_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
897static CAP_INSNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
898
899static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
900static INSN_LIFTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
901
902static BUCKET_COUNT: [std::sync::atomic::AtomicU64; 5] = [
903    std::sync::atomic::AtomicU64::new(0),
904    std::sync::atomic::AtomicU64::new(0),
905    std::sync::atomic::AtomicU64::new(0),
906    std::sync::atomic::AtomicU64::new(0),
907    std::sync::atomic::AtomicU64::new(0),
908];
909static BUCKET_MICROS: [std::sync::atomic::AtomicU64; 5] = [
910    std::sync::atomic::AtomicU64::new(0),
911    std::sync::atomic::AtomicU64::new(0),
912    std::sync::atomic::AtomicU64::new(0),
913    std::sync::atomic::AtomicU64::new(0),
914    std::sync::atomic::AtomicU64::new(0),
915];
916
917/// Dump build/insn counters.
918pub fn dump_builds() -> (u64, u64) {
919    (
920        BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed),
921        INSN_LIFTED.load(std::sync::atomic::Ordering::Relaxed),
922    )
923}
924
925/// (cap-hit methods, sum of insns*1000+blocks for cap-hit methods).
926pub fn dump_caps() -> (u64, u64) {
927    (
928        CAP_HITS.load(std::sync::atomic::Ordering::Relaxed),
929        CAP_INSNS.load(std::sync::atomic::Ordering::Relaxed),
930    )
931}
932
933/// Dump DDC_BUCKETS statistics (global atomics).
934pub fn dump_buckets() -> [(u64, u64); 5] {
935    let mut out = [(0u64, 0u64); 5];
936    for i in 0..5 {
937        out[i] = (
938            BUCKET_COUNT[i].load(std::sync::atomic::Ordering::Relaxed),
939            BUCKET_MICROS[i].load(std::sync::atomic::Ordering::Relaxed),
940        );
941    }
942    out
943}
944
945/// Dominator-recompute counters from jdc-core (perf diagnostics).
946pub fn dom_counters() -> (u64, u64) {
947    (
948        jdc_core::structure::DOM_CALLS.load(std::sync::atomic::Ordering::Relaxed),
949        jdc_core::structure::DOM_BLOCKS.load(std::sync::atomic::Ordering::Relaxed),
950    )
951}
952
953/// Enable dominator-recompute counters (diagnostics; jdc-core gate).
954pub fn dom_counters_enable() {
955    jdc_core::structure::set_dom_counters(true);
956}
957
958/// A minimal body carrying a diagnostic comment.
959fn stub_body(msg: String, desc: MethodDescriptor) -> MethodBody {
960    MethodBody {
961        body: Stmt::Block(vec![Stmt::Comment(msg)]),
962        vt: VarTable::default(),
963        desc,
964    }
965}
966
967/// True when any phi belongs to merge block `bid`.
968fn phis_for_merge(bid: usize, phis: &HashMap<(usize, u16), u32>) -> bool {
969    phis.keys().any(|(b, _)| *b == bid)
970}
971
972/// Phi materialization records for `bid`'s predecessors (pred-tagged).
973fn record_appends(
974    cfg: &DexCfg,
975    bid: usize,
976    out_states: &[Option<OutState>],
977    phis: &HashMap<(usize, u16), u32>,
978    vt: &jdc_core::var::VarTable,
979    out: &mut Vec<(usize, u32, u32, Expr)>,
980) {
981    for p in cfg.blocks[bid].pred.clone() {
982        let Some(o) = &out_states[p] else { continue };
983        for (r, st) in o.regs.iter().enumerate() {
984            if let Some(&phi) = phis.get(&(bid, r as u16)) {
985                let value = match st {
986                    Reg::Live(v) if *v == phi => continue,
987                    Reg::Live(v) => Expr::Local {
988                        var: *v,
989                        ty: vt.var(*v).ty.clone(),
990                    },
991                    Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
992                    Reg::Undef | Reg::WideHi => continue,
993                };
994                out.push((p, o.write_pc.get(r).copied().unwrap_or(0), phi, value));
995            }
996        }
997    }
998}
999
1000#[allow(unused)]
1001fn record_bucket(n: usize, t0: std::time::Instant) {
1002    // (Perf: env::var is a lock+lookup — per-METHOD cost on 716k-method
1003    // runs; resolve once via OnceLock.)
1004    static BUCKETS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1005    if !*BUCKETS_ON.get_or_init(|| std::env::var("DDC_BUCKETS").is_ok()) {
1006        return;
1007    }
1008    let bucket = if n <= 1 {
1009        0
1010    } else if n <= 5 {
1011        1
1012    } else if n <= 20 {
1013        2
1014    } else if n <= 100 {
1015        3
1016    } else {
1017        4
1018    };
1019    BUCKET_COUNT[bucket].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1020    BUCKET_MICROS[bucket].fetch_add(
1021        t0.elapsed().as_micros() as u64,
1022        std::sync::atomic::Ordering::Relaxed,
1023    );
1024}
1025
1026/// True when the expression references any of the phi vars.
1027fn visit_phi_refs(e: &Expr, phis: &std::collections::HashSet<u32>, hit: &mut bool) {
1028    if *hit {
1029        return;
1030    }
1031    if let Expr::Local { var, .. } = e {
1032        if phis.contains(var) {
1033            *hit = true;
1034        }
1035        return;
1036    }
1037    let mut kids: Vec<&Expr> = Vec::new();
1038    match e {
1039        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => kids.push(e),
1040        Expr::Bin { l, r, .. } => {
1041            kids.push(l);
1042            kids.push(r);
1043        }
1044        Expr::Cond { c, t, f } => {
1045            kids.push(c);
1046            kids.push(t);
1047            kids.push(f);
1048        }
1049        Expr::Assign { target, value, .. } => {
1050            kids.push(target);
1051            kids.push(value);
1052        }
1053        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => kids.push(e),
1054        Expr::Field { owner: Some(o), .. } => kids.push(o),
1055        Expr::Method {
1056            owner: Some(o),
1057            args,
1058            ..
1059        } => {
1060            kids.push(o);
1061            kids.extend(args.iter());
1062        }
1063        Expr::ArrayIndex { array, index } => {
1064            kids.push(array);
1065            kids.push(index);
1066        }
1067        Expr::New { args, .. } => kids.extend(args.iter()),
1068        Expr::NewArray { dims, init, .. } => {
1069            kids.extend(dims.iter());
1070            if let Some(v) = init {
1071                kids.extend(v.iter());
1072            }
1073        }
1074        Expr::NewMultiArray { dims, .. } => kids.extend(dims.iter()),
1075        _ => {}
1076    }
1077    for k in kids {
1078        visit_phi_refs(k, phis, hit);
1079        if *hit {
1080            return;
1081        }
1082    }
1083}
1084
1085/// Merge several predecessor register states: pass identical values
1086/// through, otherwise materialize into a phi var for `(block, register)`.
1087/// Debug-info name covering `(pc, slot)`, sanitized (shared by the
1088/// lifter and the merge path).
1089fn debug_name_at(
1090    locals: &[ddc_dex::DebugLocal],
1091    slot: u16,
1092    pc: u32,
1093    ty: &jdc_core::types::JavaType,
1094) -> Option<String> {
1095    if locals.is_empty() {
1096        return None;
1097    }
1098    let hit = locals.iter().find(|l| {
1099        l.reg == slot
1100            && pc >= l.start
1101            && pc < l.end
1102            && l.ty.as_deref().map(|d| &crate::desc_type(d) == ty).unwrap_or(true)
1103    })?;
1104    let n = crate::classdec::java_ident(&hit.name);
1105    if n.is_empty() {
1106        None
1107    } else {
1108        Some(n.into_owned())
1109    }
1110}
1111
1112fn merge_states(
1113    vt: &mut VarTable,
1114    phis: &mut HashMap<(usize, u16), u32>,
1115    bid: usize,
1116    sides: &[&[Reg]],
1117    debug_locals: &[ddc_dex::DebugLocal],
1118    merge_pc: u32,
1119) -> Vec<Reg> {
1120    let len = sides.iter().map(|s| s.len()).max().unwrap_or(0);
1121    let mut out = vec![Reg::Undef; len];
1122    for (r, slot) in out.iter_mut().enumerate() {
1123        let mut all_eq = true;
1124        let mut first: Option<&Reg> = None;
1125        for s in sides {
1126            let v = s.get(r);
1127            match (first, v) {
1128                (None, v) => first = v,
1129                (Some(f), Some(v)) if f == v => {}
1130                _ => all_eq = false,
1131            }
1132        }
1133        if all_eq {
1134            *slot = first.cloned().unwrap_or(Reg::Undef);
1135            continue;
1136        }
1137        // Diverged: phi var.
1138        let key = (bid, r as u16);
1139        let phi = match phis.get(&key) {
1140            Some(&v) => v,
1141            None => {
1142                let ty = join_side_types(vt, sides, r);
1143                // Loop-carried values are usually THE source local (the
1144                // `char[] out` / `int i` of a loop): name the phi from the
1145                // debug range covering the merge block's head. When a var
1146                // of that name+type already exists, REUSE it — per-block
1147                // copies of one source local degrade to out/out2/out3
1148                // suffix soup, and one register+type = one Java local is
1149                // exactly Dalvik semantics.
1150                if let Some(n) = debug_name_at(debug_locals, r as u16, merge_pc, &ty.erased()) {
1151                    let unified = vt
1152                        .vars
1153                        .iter()
1154                        .find(|v| {
1155                            v.slot == r as u16
1156                                && !v.synthetic_name
1157                                && v.name == n
1158                                && v.ty.erased() == ty.erased()
1159                        })
1160                        .map(|v| v.id);
1161                    let id = match unified {
1162                        Some(id) => id,
1163                        None => {
1164                            let id = vt.vars.len() as u32;
1165                            vt.vars.push(jdc_core::var::VarInfo {
1166                                id,
1167                                slot: r as u16,
1168                                name: n,
1169                                ty,
1170                                is_param: false,
1171                                range_start: 0,
1172                                range_end: u16::MAX,
1173                                synthetic_name: false,
1174                            });
1175                            while vt.by_slot.len() <= r {
1176                                vt.by_slot.push(Vec::new());
1177                            }
1178                            vt.by_slot[r].push((0, u16::MAX, id));
1179                            id
1180                        }
1181                    };
1182                    phis.insert(key, id);
1183                    id
1184                } else {
1185                    let id = vt.vars.len() as u32;
1186                    vt.vars.push(jdc_core::var::VarInfo {
1187                        id,
1188                        slot: r as u16,
1189                        name: format!("v{}", id),
1190                        ty,
1191                        is_param: false,
1192                        range_start: 0,
1193                        range_end: u16::MAX,
1194                        synthetic_name: true,
1195                    });
1196                    while vt.by_slot.len() <= r {
1197                        vt.by_slot.push(Vec::new());
1198                    }
1199                    vt.by_slot[r].push((0, u16::MAX, id));
1200                    phis.insert(key, id);
1201                    id
1202                }
1203            }
1204        };
1205        *slot = Reg::Live(phi);
1206    }
1207    out
1208}
1209
1210/// Type of a phi var: join of the non-null side values' erased types.
1211fn join_side_types(vt: &VarTable, sides: &[&[Reg]], r: usize) -> TypeRef {
1212    let mut ty: Option<JavaType> = None;
1213    for s in sides {
1214        let st = s.get(r).cloned().unwrap_or(Reg::Undef);
1215        let e = match st {
1216            Reg::Pending(e) | Reg::PendingCall(e) => e,
1217            Reg::Live(v) => Expr::Local {
1218                var: v,
1219                ty: vt.var(v).ty.clone(),
1220            },
1221            _ => continue,
1222        };
1223        let t = e.type_ref().erased();
1224        ty = Some(match ty {
1225            None => t,
1226            Some(prev) => join_types(&prev, &t),
1227        });
1228    }
1229    TypeRef::J(ty.unwrap_or(JavaType::Int))
1230}
1231
1232fn join_types(a: &JavaType, b: &JavaType) -> JavaType {
1233    if a == b {
1234        return a.clone();
1235    }
1236    let num = |t: &JavaType| {
1237        matches!(
1238            t,
1239            JavaType::Boolean
1240                | JavaType::Byte
1241                | JavaType::Char
1242                | JavaType::Short
1243                | JavaType::Int
1244                | JavaType::Long
1245                | JavaType::Float
1246                | JavaType::Double
1247        )
1248    };
1249    if num(a) && num(b) {
1250        // Numeric promotion.
1251        return match (a, b) {
1252            (JavaType::Double, _) | (_, JavaType::Double) => JavaType::Double,
1253            (JavaType::Float, _) | (_, JavaType::Float) => JavaType::Float,
1254            (JavaType::Long, _) | (_, JavaType::Long) => JavaType::Long,
1255            _ => JavaType::Int,
1256        };
1257    }
1258    if let (JavaType::Object(x), JavaType::Object(y)) = (a, b) {
1259        if x == y {
1260            return a.clone();
1261        }
1262        // Char/int ternaries join to int; otherwise objects join to Object.
1263        return JavaType::Object("java/lang/Object".into());
1264    }
1265    JavaType::Object("java/lang/Object".into())
1266}
1267
1268/// True when the block's terminator exits (used by callers to skip appends).
1269#[allow(dead_code)]
1270fn is_exit_term(term: &jdc_core::ir::build::Term) -> bool {
1271    matches!(
1272        term,
1273        jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
1274    )
1275}
1276
1277#[allow(dead_code)]
1278fn unused(_: &InsnKind) {}