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 handler_types_for(cfg: &DexCfg, bid: usize) -> Vec<Option<std::sync::Arc<str>>> {
55    cfg.blocks[bid]
56        .handlers
57        .iter()
58        .filter_map(|&ri| cfg.exc_ranges.get(ri).map(|r| r.catch_type.clone()))
59        .collect()
60}
61
62/// Decompile one method. `Err` only for malformed input; unsupported
63/// constructs degrade to comments inside the statement tree.
64pub fn decompile_method(
65    pool: &DexPool,
66    class: &PoolClass,
67    m: &PoolMethod,
68) -> Result<Option<MethodBody>, String> {
69    let t0 = std::time::Instant::now();
70    if m.is_abstract_or_native() {
71        return Ok(None);
72    }
73    let desc = m
74        .parsed_desc()
75        .ok_or_else(|| format!("bad descriptor {}", m.desc))?;
76    let dex = pool.dex(m.dex_idx).ok_or("missing dex image")?;
77    let dex = &*dex;
78    let Some(mut code) = dex.code_at(m.code_off) else {
79        return Ok(None);
80    };
81    let insn_count = code.insns.len();
82    let param_names = dex.parameter_names(m.debug_info_off);
83    // Pool-cached Arc class names: the closure ran dex.class_name
84    // (fresh String) per exception range of every method.
85    let cfg = DexCfg::build(&mut code, &|ty| pool.type_name_arc(m.dex_idx, ty));
86    // Method-wide final-read set for the alloc-inline decisions (the
87    // per-block computation mistook a block-tail read for the
88    // generation's last read — cross-block alloc consumers minted
89    // never-assigned int locals).
90    let method_final_reads = crate::lift::compute_final_reads(&cfg.insns);
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, method_final_reads.clone()) {
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, &class.name);
565        passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
566        passes::fix_ref_null_assigns(&vt, &mut body);
567        passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
568        passes::split_generations(&mut vt, &mut body, pool);
569        passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
570        passes::fix_field_owner_downcasts(&mut body, &vt, pool);
571        passes::fix_incomparable_equality(&mut body, &vt, pool);
572        passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
573        passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
574        passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
575        passes::fix_int_operand_bridges(&mut body, &vt);
576        passes::fix_ref_array_null_consts(&mut body);
577        passes::idiom_compounds(&mut body, &vt);
578        passes::rescue_primitive_receivers(&mut body, &vt, pool);
579        passes::fix_this0_owners(&mut body, &class.name);
580        passes::apply_local_names(&mut vt, &body);
581    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
582        passes::remove_kotlin_checks(&mut body);
583        passes::rewrite_kotlin_facades(&mut body, pool);
584        passes::platform_constants(&mut body);
585        passes::drop_dead_locals(&mut body);
586    passes::drop_dead_raw_news(&mut body);
587    passes::mark_field_owner_concrete(&mut vt, &mut body);
588    passes::ensure_declared(&mut body, &vt);
589    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
590    // AFTER the declaration hoisting: ensure_declared inserts bare
591    // top-of-method declarations, and a local declaration ahead of the
592    // super() call is still "super must be first statement".
593    if &*m.name == "<init>" {
594        // Boolean value-diamond folds ahead of the delegation machinery:
595        // a branched bridge ctor whose else arm COMPUTES the defaulted
596        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
597        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
598        // (interleaved forwarding inlines the impure `u` the fold
599        // exposes) the arm is linear defs and merge_at lifts the this()
600        // (lark MmCreateAudioRequest, this-not-first ×456 family).
601        passes::fold_bool_value_diamonds(&mut body, &vt);
602        passes::fold_value_diamonds(&mut body);
603        passes::fix_ctor_this_aliases(&mut body, &vt);
604        if class.is_enum() {
605            passes::fold_enum_default_arg_bridge(&mut body);
606            // Strip the implicit Enum.<init> super() ONLY for the enum
607            // BASE (super is java/lang/Enum or Object — a true `enum`
608            // decl or the fallback `/* enum */ class`, both get an
609            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
610            // (j$6, super = the enum base j) renders as a plain
611            // `class j$6 extends j`; its ctor MUST forward
612            // `super(name, ordinal, ..)` or the implicit no-arg super()
613            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
614            // TokeniserState ×134).
615            let const_subclass = class
616                .super_name
617                .as_ref()
618                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
619                .unwrap_or(false);
620            if !const_subclass {
621                passes::strip_enum_ctor_super(&mut body);
622            }
623        } else {
624            passes::fix_ctor_delegation_arg_defs(&mut body);
625            passes::fix_ctor_conditional_super(&mut body);
626            passes::fix_ctor_super_first(&mut body, &vt);
627            passes::dedupe_ctor_delegations(&mut body);
628            passes::strip_secondary_delegations(&mut body);
629            passes::extract_branched_delegation_helper(&mut body, &vt, class, &desc.to_string());
630        }
631        // The delegation merges/hoists can leave prelude decls dead
632        // (their defs were inlined into the merged call) — the dropper
633        // ran BEFORE the ctor passes, so re-run it on their output.
634        passes::drop_dead_locals(&mut body);
635    }
636        passes::strip_trailing_void_return(&mut body);
637        passes::cleanup(&mut body);
638        passes::invert_empty_thens(&mut body);
639        passes::fold_short_circuits(&mut body);
640        passes::resolve_dangling_gotos(&mut body);
641    passes::dedupe_multicatch(&mut body, pool);
642        if !errors.is_empty() {
643            passes::prepend_comment(
644                &mut body,
645                format!("$DDC: {} block(s) failed to decompile", errors.len()),
646            );
647        }
648        phase_hit_n(2, n, t_fix);
649        record_bucket(n, t0);
650        return Ok(Some(MethodBody { body, vt, desc }));
651    }
652
653    // ---- structure + convert ----
654    // jcdc's copy-budget degradation: a rendering whose statement tree
655    // explodes past the guard retries at a halved copy budget (the
656    // structurer's tail-copying is the exponential mechanism).
657    const TREE_GUARD: usize = 20_000;
658    let core_cfg = cfg.to_core();
659    #[allow(unused_assignments)]
660    let mut body: Option<Stmt> = None;
661    let mut prev_size: Option<usize> = None;
662    // Copy budget scales with graph size: many-block methods are where the
663    // exponential tail-copy blowups live (weibo: 389 methods >100 blocks
664    // = 40% of all CPU at budget 512). Starting lower converges without
665    // the 6-round halving.
666    let mut budget: u32 = if n > 100 {
667        64
668    } else if n > 20 {
669        128
670    } else {
671        512
672    };
673    // Shared once-per-method artifacts: the O(groups²) exception-group
674    // scan and the full-graph dominator tree used to run TWICE per
675    // method (Structurer + Converter) and once more per copy-budget
676    // retry — monster classes (gson adapters) spent the bulk of their
677    // time there.
678    let groups = jdc_core::structure::group_exceptions_with(&core_cfg, Some(&results));
679    let dom_universe: jdc_core::FxHashSet<usize> = (0..core_cfg.blocks.len()).collect();
680    let dom = jdc_core::structure::compute_dominators(&core_cfg, &dom_universe, core_cfg.entry);
681    if trace_on() {
682        eprintln!("[mshape] {}.{} blocks={}", class.name, m.name, n);
683    }
684    // Deterministic giant-method stub: at ~2.1k+ CFG blocks a single
685    // structuring walk can burn 9s+ of wall time (weibo Gson doRead:
686    // 2,179/3,230 blocks — per-visit dominator-pass cost scales far
687    // faster than the Σ universe.len() charge model can bound, and the
688    // spread across CFG shapes defeats any charge calibration). Healthy
689    // methods below the line (JsonUserInfoTypeAdapter, 1,997 blocks)
690    // structure fully, so stubbing beats both alternatives: burning the
691    // class watchdog DROPS the whole file (every referrer cannot-finds)
692    // and the old wall-clock deadline flipped output nondeterministically
693    // under worker contention.
694    if n >= 2_100 {
695        return Ok(Some(stub_body(
696            format!(
697                "$DDC: method too large ({} blocks) — body elided for determinism",
698                n
699            ),
700            desc,
701        )));
702    }
703    #[cfg(feature = "visit-stats")]
704    {
705        jdc_core::structure::reset_visit_stats();
706    }
707    // Walk-visit budget, proportional to the block count: walk() runs
708    // roughly once per structured scope for sane CFGs, so 40n+512 is
709    // generous headroom — but the EXPONENTIAL explorations (Telegram
710    // SendMessagesHelper family: deep if/loop/try nesting whose scope
711    // count multiplies) consume visits geometrically and get cut to a
712    // Goto, which terminates the walk. Without this a single <16k-insn
713    // method can recurse for effectively forever while the worker (and
714    // the process) never finishes — Telegram's full run wrote every file
715    // yet hung for 300+ seconds on 25 such classes.
716    let walk_budget: u64 = walk_budget_override().unwrap_or(8 * n as u64 + 128);
717    // WORK budget (Σ universe.len() per visit): deterministic bound on
718    // total walk cost — the count budget above under-bounds per-visit
719    // cost for big-block exponential explorations (Telegram family),
720    // which the wall-clock deadline used to catch nondeterministically.
721    // A visit's REAL cost grows with the universe (dominator-style
722    // passes: weibo doRead n=2179 burned 15µs per charge unit vs 5µs at
723    // n=1533), so a flat charge budget still lets giants run 9s+ per
724    // rung and trip the class watchdog (dropped files — every referrer
725    // cannot-finds — are strictly worse than walk-cut degradation).
726    let walk_work_budget: u64 = walk_work_override()
727        .unwrap_or(600_000 + 128 * n as u64);
728    // No wall-clock deadline here: the work budget above bounds walk
729    // cost deterministically, and the old 1500ms guard flipped
730    // borderline giants (weixin vm/a0.n, 28.5k nodes) between full body
731    // and exploded stub run-to-run under worker contention. The
732    // class-level 5s watchdog in classdec remains as the hang safety
733    // net for pathological CFGs.
734    loop {
735        jdc_core::structure::set_budget_override(Some(budget));
736        jdc_core::structure::set_walk_visit_budget(Some(walk_budget));
737        jdc_core::structure::set_walk_work_budget(Some(walk_work_budget));
738        let mut st = Structurer::with_shared_groups(
739            &core_cfg,
740            &results,
741            &groups,
742            Default::default(),
743            Default::default(),
744        );
745        let tw0 = std::time::Instant::now();
746        let region = st.structure_method();
747        let tw1 = std::time::Instant::now();
748        let mut converter = Converter::with_precomputed_ref(&core_cfg, &results, &groups, &dom);
749        let candidate = converter.convert(region);
750        let tw2 = std::time::Instant::now();
751        if trace_on() {
752            eprintln!(
753                "[rung] {}.{} budget={} walk={:?} convert={:?}",
754                class.name, m.name, budget, tw1 - tw0, tw2 - tw1
755            );
756        }
757        jdc_core::structure::set_budget_override(None);
758        jdc_core::structure::set_walk_visit_budget(None);
759        jdc_core::structure::set_walk_work_budget(None);
760        let size = {
761            let mut c = 0usize;
762            passes::count_stmts_deep(&candidate, &mut c);
763            c
764        };
765        if trace_on() {
766            eprintln!("[guard] {}.{} size={} budget={}", class.name, m.name, size, budget);
767        }
768        if size <= TREE_GUARD {
769            body = Some(candidate);
770            break;
771        }
772        // Giant short-circuit: deep in the ladder (budget ≤ 64), a tree
773        // still 3× over the guard will not shrink under further copy-budget
774        // halving (weixin cdp/l1.w: 72,782 nodes at 64, ~2.8s of walk PER
775        // rung) — stub now instead of burning two more rungs and tripping
776        // the classdec 5s watchdog, which DROPS the whole file (every
777        // referrer cannot-finds — strictly worse than one stubbed body).
778        // Deterministic: driven by measured size, not wall-clock.
779        if budget <= 64 && size > 3 * TREE_GUARD {
780            return Ok(Some(stub_body(
781                format!(
782                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
783                    size
784                ),
785                desc,
786            )));
787        }
788        // No-progress short-circuit: the copy budget only bounds tail
789        // duplication — if halving it did not shrink the tree at all,
790        // further rungs cannot either (weixin vm/a0.n sits at ~28.5k
791        // across every rung, burning a full work-budget walk each).
792        // Deterministic, and saves the giant methods ~3 rungs of walk.
793        if budget <= 32 && prev_size.is_some_and(|p| size >= p) {
794            return Ok(Some(stub_body(
795                format!(
796                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
797                    size
798                ),
799                desc,
800            )));
801        }
802        prev_size = Some(size);
803        if budget <= 16 {
804            return Ok(Some(stub_body(
805                format!(
806                    "$DDC: statement tree exploded ({} nodes) even at copy budget 16",
807                    size
808                ),
809                desc,
810            )));
811        }
812        budget /= 2;
813    }
814    #[cfg(feature = "visit-stats")]
815    if trace_on() && n > 3 {
816        let used = jdc_core::structure::walk_visits_consumed();
817        eprintln!(
818            "[visits] {}.{} blocks={} consumed={} ratio={:.1}",
819            class.name,
820            m.name,
821            n,
822            used,
823            used as f64 / n as f64
824        );
825    }
826    phase_hit_n(1, n, t_fix);
827    let mut body = body.unwrap();
828    if !entry_phi_inits.is_empty() {
829        let head: Vec<Stmt> = entry_phi_inits
830            .into_iter()
831            .map(|(v, e)| Stmt::LocalDef {
832                var: v,
833                init: Some(e),
834                is_final: false,
835                force_type: true,
836            })
837            .collect();
838        body = match body {
839            Stmt::Block(v) => {
840                let mut nv = head;
841                nv.extend(v);
842                Stmt::Block(nv)
843            }
844            other => {
845                let mut nv = head;
846                nv.push(other);
847                Stmt::Block(nv)
848            }
849        };
850    }
851
852    passes::bind_catches(&mut body, &mut vt);
853    passes::prune_unreachable(&mut body);
854    // One traversal for cmp residuals + null compares + const-first flips
855    // (three separate full-tree walks before).
856    passes::fused_expr_rewrites(&mut body, &vt);
857    if mflags.has_sb() {
858        passes::fold_string_builders(&mut body, &vt);
859    }
860    passes::ternary_fold(&mut body);
861    if mflags.has_monitor() {
862        passes::fold_synchronized(&mut body);
863    }
864    passes::forward_single_use(&mut body, &vt);
865    passes::cleanup(&mut body);
866    passes::inline_accessors(&mut body, pool, &class.name);
867    passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
868    passes::fix_ref_null_assigns(&vt, &mut body);
869    passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
870    passes::split_generations(&mut vt, &mut body, pool);
871    // Post-booleanize re-split, gated on a nonzero conversion count:
872    // conversions expose register reuse across boolean/numeric kinds no
873    // earlier pass could see (`int v150` copying converted `boolean
874    // v131` — weixin ConstraintLayout ×1.4k); with nothing converted
875    // the fixpoint walk is pure decomp-time cost (the weixin 16→24s
876    // regression).
877    // Booleanize ↔ split fixpoint, bounded, ENDING on a booleanize:
878    // each split MINTS fresh generation vars that inherit the stale int
879    // type while receiving boolean values (`int v264_g160_g7_g3 =
880    // !v200` with `!= 0` reads — weixin bool→int assign family, 2.8k
881    // lines). Only a FOLLOWING booleanize retypes them and folds their
882    // `v != 0` reads; a trailing split would leave the folds undone.
883    {
884        let rb = matches!(desc.ret, JavaType::Boolean);
885        let mut rounds = 0;
886        loop {
887            let c = passes::booleanize(&mut vt, &mut body, rb);
888            rounds += 1;
889            if c == 0 || rounds >= 3 {
890                break;
891            }
892            passes::split_generations(&mut vt, &mut body, pool);
893        }
894    }
895    if matches!(
896        desc.ret,
897        JavaType::Int | JavaType::Long | JavaType::Short | JavaType::Byte | JavaType::Float | JavaType::Double
898    ) {
899        passes::fix_int_returns(&vt, &mut body);
900    }
901    if matches!(desc.ret, JavaType::Boolean) {
902        passes::fix_bool_returns(&vt, &mut body);
903    }
904    passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
905    passes::fix_field_owner_downcasts(&mut body, &vt, pool);
906    passes::fix_incomparable_equality(&mut body, &vt, pool);
907    passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
908    passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
909    passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
910    passes::fix_int_operand_bridges(&mut body, &vt);
911    passes::fix_ref_array_null_consts(&mut body);
912    passes::idiom_compounds(&mut body, &vt);
913    passes::rescue_primitive_receivers(&mut body, &vt, pool);
914    passes::fix_this0_owners(&mut body, &class.name);
915    passes::apply_local_names(&mut vt, &body);
916    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
917    passes::remove_kotlin_checks(&mut body);
918    passes::rewrite_kotlin_facades(&mut body, pool);
919    passes::platform_constants(&mut body);
920    passes::drop_dead_locals(&mut body);
921    passes::drop_dead_raw_news(&mut body);
922    passes::mark_field_owner_concrete(&mut vt, &mut body);
923    passes::ensure_declared(&mut body, &vt);
924    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
925    // AFTER the declaration hoisting: ensure_declared inserts bare
926    // top-of-method declarations, and a local declaration ahead of the
927    // super() call is still "super must be first statement".
928    if &*m.name == "<init>" {
929        // Boolean value-diamond folds ahead of the delegation machinery:
930        // a branched bridge ctor whose else arm COMPUTES the defaulted
931        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
932        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
933        // (interleaved forwarding inlines the impure `u` the fold
934        // exposes) the arm is linear defs and merge_at lifts the this()
935        // (lark MmCreateAudioRequest, this-not-first ×456 family).
936        passes::fold_bool_value_diamonds(&mut body, &vt);
937        passes::fold_value_diamonds(&mut body);
938        passes::fix_ctor_this_aliases(&mut body, &vt);
939        if class.is_enum() {
940            passes::fold_enum_default_arg_bridge(&mut body);
941            // Strip the implicit Enum.<init> super() ONLY for the enum
942            // BASE (super is java/lang/Enum or Object — a true `enum`
943            // decl or the fallback `/* enum */ class`, both get an
944            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
945            // (j$6, super = the enum base j) renders as a plain
946            // `class j$6 extends j`; its ctor MUST forward
947            // `super(name, ordinal, ..)` or the implicit no-arg super()
948            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
949            // TokeniserState ×134).
950            let const_subclass = class
951                .super_name
952                .as_ref()
953                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
954                .unwrap_or(false);
955            if !const_subclass {
956                passes::strip_enum_ctor_super(&mut body);
957            }
958        } else {
959            passes::fix_ctor_delegation_arg_defs(&mut body);
960            passes::fix_ctor_conditional_super(&mut body);
961            passes::fix_ctor_super_first(&mut body, &vt);
962            passes::dedupe_ctor_delegations(&mut body);
963            passes::strip_secondary_delegations(&mut body);
964            passes::extract_branched_delegation_helper(&mut body, &vt, class, &desc.to_string());
965        }
966        // The delegation merges/hoists can leave prelude decls dead
967        // (their defs were inlined into the merged call) — the dropper
968        // ran BEFORE the ctor passes, so re-run it on their output.
969        passes::drop_dead_locals(&mut body);
970    }
971    if &*m.name == "<clinit>" {
972        passes::strip_clinit_returns(&mut body);
973    }
974    passes::strip_trailing_void_return(&mut body);
975    passes::cleanup(&mut body);
976    // Short-circuit folding last: the diamond shapes are final only
977    // after cleanup merges singleton blocks.
978    passes::invert_empty_thens(&mut body);
979    passes::fold_short_circuits(&mut body);
980    passes::resolve_dangling_gotos(&mut body);
981    passes::dedupe_multicatch(&mut body, pool);
982
983    if !errors.is_empty() {
984        passes::prepend_comment(
985            &mut body,
986            format!("$DDC: {} block(s) failed to decompile", errors.len()),
987        );
988    }
989
990    phase_hit_n(2, n, t_fix);
991    record_bucket(n, t0);
992    Ok(Some(MethodBody { body, vt, desc }))
993}
994
995static PHASE_MICROS: [std::sync::atomic::AtomicU64; 5] = [
996    std::sync::atomic::AtomicU64::new(0),
997    std::sync::atomic::AtomicU64::new(0),
998    std::sync::atomic::AtomicU64::new(0),
999    std::sync::atomic::AtomicU64::new(0),
1000    std::sync::atomic::AtomicU64::new(0),
1001];
1002/// Phase × bucket attribution (5 phases × 5 buckets, row-major).
1003static PHASE_BUCKET_MICROS: [std::sync::atomic::AtomicU64; 25] = [
1004    std::sync::atomic::AtomicU64::new(0),
1005    std::sync::atomic::AtomicU64::new(0),
1006    std::sync::atomic::AtomicU64::new(0),
1007    std::sync::atomic::AtomicU64::new(0),
1008    std::sync::atomic::AtomicU64::new(0),
1009    std::sync::atomic::AtomicU64::new(0),
1010    std::sync::atomic::AtomicU64::new(0),
1011    std::sync::atomic::AtomicU64::new(0),
1012    std::sync::atomic::AtomicU64::new(0),
1013    std::sync::atomic::AtomicU64::new(0),
1014    std::sync::atomic::AtomicU64::new(0),
1015    std::sync::atomic::AtomicU64::new(0),
1016    std::sync::atomic::AtomicU64::new(0),
1017    std::sync::atomic::AtomicU64::new(0),
1018    std::sync::atomic::AtomicU64::new(0),
1019    std::sync::atomic::AtomicU64::new(0),
1020    std::sync::atomic::AtomicU64::new(0),
1021    std::sync::atomic::AtomicU64::new(0),
1022    std::sync::atomic::AtomicU64::new(0),
1023    std::sync::atomic::AtomicU64::new(0),
1024    std::sync::atomic::AtomicU64::new(0),
1025    std::sync::atomic::AtomicU64::new(0),
1026    std::sync::atomic::AtomicU64::new(0),
1027    std::sync::atomic::AtomicU64::new(0),
1028    std::sync::atomic::AtomicU64::new(0),
1029];
1030static PHASE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1031
1032fn bucket_of(n: usize) -> usize {
1033    if n <= 1 {
1034        0
1035    } else if n <= 5 {
1036        1
1037    } else if n <= 20 {
1038        2
1039    } else if n <= 100 {
1040        3
1041    } else {
1042        4
1043    }
1044}
1045
1046pub(crate) fn phase_hit_n(i: usize, n: usize, t: std::time::Instant) {
1047    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1048        return;
1049    }
1050    let us = t.elapsed().as_micros() as u64;
1051    PHASE_MICROS[i].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1052    PHASE_BUCKET_MICROS[i * 5 + bucket_of(n)].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1053}
1054
1055pub(crate) fn phase_hit(i: usize, t: std::time::Instant) {
1056    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1057        return;
1058    }
1059    PHASE_MICROS[i].fetch_add(
1060        t.elapsed().as_micros() as u64,
1061        std::sync::atomic::Ordering::Relaxed,
1062    );
1063}
1064
1065/// Enable phase timers (DDC_PHASES=1).
1066pub fn phases_enable() {
1067    PHASE_ON.store(true, std::sync::atomic::Ordering::Relaxed);
1068}
1069
1070/// (fixpoint, structure+convert, passes, print, total) in micros.
1071pub fn phases_dump() -> [u64; 5] {
1072    let mut out = [0u64; 5];
1073    for i in 0..5 {
1074        out[i] = PHASE_MICROS[i].load(std::sync::atomic::Ordering::Relaxed);
1075    }
1076    out
1077}
1078
1079/// Per-bucket phase micros: 5 phases × 5 buckets, row-major.
1080pub fn phases_bucket_dump() -> [[u64; 5]; 5] {
1081    let mut out = [[0u64; 5]; 5];
1082    for i in 0..5 {
1083        for b in 0..5 {
1084            out[i][b] = PHASE_BUCKET_MICROS[i * 5 + b].load(std::sync::atomic::Ordering::Relaxed);
1085        }
1086    }
1087    out
1088}
1089
1090static CAP_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1091static CAP_INSNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1092
1093static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1094static INSN_LIFTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1095
1096static BUCKET_COUNT: [std::sync::atomic::AtomicU64; 5] = [
1097    std::sync::atomic::AtomicU64::new(0),
1098    std::sync::atomic::AtomicU64::new(0),
1099    std::sync::atomic::AtomicU64::new(0),
1100    std::sync::atomic::AtomicU64::new(0),
1101    std::sync::atomic::AtomicU64::new(0),
1102];
1103static BUCKET_MICROS: [std::sync::atomic::AtomicU64; 5] = [
1104    std::sync::atomic::AtomicU64::new(0),
1105    std::sync::atomic::AtomicU64::new(0),
1106    std::sync::atomic::AtomicU64::new(0),
1107    std::sync::atomic::AtomicU64::new(0),
1108    std::sync::atomic::AtomicU64::new(0),
1109];
1110
1111/// Dump build/insn counters.
1112pub fn dump_builds() -> (u64, u64) {
1113    (
1114        BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed),
1115        INSN_LIFTED.load(std::sync::atomic::Ordering::Relaxed),
1116    )
1117}
1118
1119/// (cap-hit methods, sum of insns*1000+blocks for cap-hit methods).
1120pub fn dump_caps() -> (u64, u64) {
1121    (
1122        CAP_HITS.load(std::sync::atomic::Ordering::Relaxed),
1123        CAP_INSNS.load(std::sync::atomic::Ordering::Relaxed),
1124    )
1125}
1126
1127/// Dump DDC_BUCKETS statistics (global atomics).
1128pub fn dump_buckets() -> [(u64, u64); 5] {
1129    let mut out = [(0u64, 0u64); 5];
1130    for i in 0..5 {
1131        out[i] = (
1132            BUCKET_COUNT[i].load(std::sync::atomic::Ordering::Relaxed),
1133            BUCKET_MICROS[i].load(std::sync::atomic::Ordering::Relaxed),
1134        );
1135    }
1136    out
1137}
1138
1139/// Dominator-recompute counters from jdc-core (perf diagnostics).
1140pub fn dom_counters() -> (u64, u64) {
1141    (
1142        jdc_core::structure::DOM_CALLS.load(std::sync::atomic::Ordering::Relaxed),
1143        jdc_core::structure::DOM_BLOCKS.load(std::sync::atomic::Ordering::Relaxed),
1144    )
1145}
1146
1147/// Enable dominator-recompute counters (diagnostics; jdc-core gate).
1148pub fn dom_counters_enable() {
1149    jdc_core::structure::set_dom_counters(true);
1150}
1151
1152/// A minimal body carrying a diagnostic comment.
1153fn stub_body(msg: String, desc: MethodDescriptor) -> MethodBody {
1154    MethodBody {
1155        body: Stmt::Block(vec![Stmt::Comment(msg)]),
1156        vt: VarTable::default(),
1157        desc,
1158    }
1159}
1160
1161/// True when any phi belongs to merge block `bid`.
1162fn phis_for_merge(bid: usize, phis: &HashMap<(usize, u16), u32>) -> bool {
1163    phis.keys().any(|(b, _)| *b == bid)
1164}
1165
1166/// Phi materialization records for `bid`'s predecessors (pred-tagged).
1167fn record_appends(
1168    cfg: &DexCfg,
1169    bid: usize,
1170    out_states: &[Option<OutState>],
1171    phis: &HashMap<(usize, u16), u32>,
1172    vt: &jdc_core::var::VarTable,
1173    out: &mut Vec<(usize, u32, u32, Expr)>,
1174) {
1175    for p in cfg.blocks[bid].pred.clone() {
1176        let Some(o) = &out_states[p] else { continue };
1177        for (r, st) in o.regs.iter().enumerate() {
1178            if let Some(&phi) = phis.get(&(bid, r as u16)) {
1179                let value = match st {
1180                    Reg::Live(v) if *v == phi => continue,
1181                    Reg::Live(v) => Expr::Local {
1182                        var: *v,
1183                        ty: vt.var(*v).ty.clone(),
1184                    },
1185                    Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
1186                    Reg::Undef | Reg::WideHi => continue,
1187                };
1188                out.push((p, o.write_pc.get(r).copied().unwrap_or(0), phi, value));
1189            }
1190        }
1191    }
1192}
1193
1194#[allow(unused)]
1195fn record_bucket(n: usize, t0: std::time::Instant) {
1196    // (Perf: env::var is a lock+lookup — per-METHOD cost on 716k-method
1197    // runs; resolve once via OnceLock.)
1198    static BUCKETS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1199    if !*BUCKETS_ON.get_or_init(|| std::env::var("DDC_BUCKETS").is_ok()) {
1200        return;
1201    }
1202    let bucket = if n <= 1 {
1203        0
1204    } else if n <= 5 {
1205        1
1206    } else if n <= 20 {
1207        2
1208    } else if n <= 100 {
1209        3
1210    } else {
1211        4
1212    };
1213    BUCKET_COUNT[bucket].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1214    BUCKET_MICROS[bucket].fetch_add(
1215        t0.elapsed().as_micros() as u64,
1216        std::sync::atomic::Ordering::Relaxed,
1217    );
1218}
1219
1220/// True when the expression references any of the phi vars.
1221fn visit_phi_refs(e: &Expr, phis: &std::collections::HashSet<u32>, hit: &mut bool) {
1222    if *hit {
1223        return;
1224    }
1225    if let Expr::Local { var, .. } = e {
1226        if phis.contains(var) {
1227            *hit = true;
1228        }
1229        return;
1230    }
1231    let mut kids: Vec<&Expr> = Vec::new();
1232    match e {
1233        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => kids.push(e),
1234        Expr::Bin { l, r, .. } => {
1235            kids.push(l);
1236            kids.push(r);
1237        }
1238        Expr::Cond { c, t, f } => {
1239            kids.push(c);
1240            kids.push(t);
1241            kids.push(f);
1242        }
1243        Expr::Assign { target, value, .. } => {
1244            kids.push(target);
1245            kids.push(value);
1246        }
1247        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => kids.push(e),
1248        Expr::Field { owner: Some(o), .. } => kids.push(o),
1249        Expr::Method {
1250            owner: Some(o),
1251            args,
1252            ..
1253        } => {
1254            kids.push(o);
1255            kids.extend(args.iter());
1256        }
1257        Expr::ArrayIndex { array, index } => {
1258            kids.push(array);
1259            kids.push(index);
1260        }
1261        Expr::New { args, .. } => kids.extend(args.iter()),
1262        Expr::NewArray { dims, init, .. } => {
1263            kids.extend(dims.iter());
1264            if let Some(v) = init {
1265                kids.extend(v.iter());
1266            }
1267        }
1268        Expr::NewMultiArray { dims, .. } => kids.extend(dims.iter()),
1269        _ => {}
1270    }
1271    for k in kids {
1272        visit_phi_refs(k, phis, hit);
1273        if *hit {
1274            return;
1275        }
1276    }
1277}
1278
1279/// Merge several predecessor register states: pass identical values
1280/// through, otherwise materialize into a phi var for `(block, register)`.
1281/// Debug-info name covering `(pc, slot)`, sanitized (shared by the
1282/// lifter and the merge path).
1283fn debug_name_at(
1284    locals: &[ddc_dex::DebugLocal],
1285    slot: u16,
1286    pc: u32,
1287    ty: &jdc_core::types::JavaType,
1288) -> Option<String> {
1289    if locals.is_empty() {
1290        return None;
1291    }
1292    let hit = locals.iter().find(|l| {
1293        l.reg == slot
1294            && pc >= l.start
1295            && pc < l.end
1296            && l.ty.as_deref().map(|d| &crate::desc_type(d) == ty).unwrap_or(true)
1297    })?;
1298    let n = crate::classdec::java_ident(&hit.name);
1299    if n.is_empty() {
1300        None
1301    } else {
1302        Some(n.into_owned())
1303    }
1304}
1305
1306fn merge_states(
1307    vt: &mut VarTable,
1308    phis: &mut HashMap<(usize, u16), u32>,
1309    bid: usize,
1310    sides: &[&[Reg]],
1311    debug_locals: &[ddc_dex::DebugLocal],
1312    merge_pc: u32,
1313) -> Vec<Reg> {
1314    let len = sides.iter().map(|s| s.len()).max().unwrap_or(0);
1315    let mut out = vec![Reg::Undef; len];
1316    for (r, slot) in out.iter_mut().enumerate() {
1317        let mut all_eq = true;
1318        let mut first: Option<&Reg> = None;
1319        for s in sides {
1320            let v = s.get(r);
1321            match (first, v) {
1322                (None, v) => first = v,
1323                (Some(f), Some(v)) if f == v => {}
1324                _ => all_eq = false,
1325            }
1326        }
1327        if all_eq {
1328            *slot = first.cloned().unwrap_or(Reg::Undef);
1329            continue;
1330        }
1331        // Diverged: phi var.
1332        let key = (bid, r as u16);
1333        let phi = match phis.get(&key) {
1334            Some(&v) => v,
1335            None => {
1336                let ty = join_side_types(vt, sides, r);
1337                // Loop-carried values are usually THE source local (the
1338                // `char[] out` / `int i` of a loop): name the phi from the
1339                // debug range covering the merge block's head. When a var
1340                // of that name+type already exists, REUSE it — per-block
1341                // copies of one source local degrade to out/out2/out3
1342                // suffix soup, and one register+type = one Java local is
1343                // exactly Dalvik semantics.
1344                if let Some(n) = debug_name_at(debug_locals, r as u16, merge_pc, &ty.erased()) {
1345                    let unified = vt
1346                        .vars
1347                        .iter()
1348                        .find(|v| {
1349                            v.slot == r as u16
1350                                && !v.synthetic_name
1351                                && v.name == n
1352                                && v.ty.erased() == ty.erased()
1353                        })
1354                        .map(|v| v.id);
1355                    let id = match unified {
1356                        Some(id) => id,
1357                        None => {
1358                            let id = vt.vars.len() as u32;
1359                            vt.vars.push(jdc_core::var::VarInfo {
1360                                id,
1361                                slot: r as u16,
1362                                name: n,
1363                                ty,
1364                                is_param: false,
1365                                range_start: 0,
1366                                range_end: u16::MAX,
1367                                synthetic_name: false,
1368                            });
1369                            while vt.by_slot.len() <= r {
1370                                vt.by_slot.push(Vec::new());
1371                            }
1372                            vt.by_slot[r].push((0, u16::MAX, id));
1373                            id
1374                        }
1375                    };
1376                    phis.insert(key, id);
1377                    id
1378                } else {
1379                    let id = vt.vars.len() as u32;
1380                    vt.vars.push(jdc_core::var::VarInfo {
1381                        id,
1382                        slot: r as u16,
1383                        name: format!("v{}", id),
1384                        ty,
1385                        is_param: false,
1386                        range_start: 0,
1387                        range_end: u16::MAX,
1388                        synthetic_name: true,
1389                    });
1390                    while vt.by_slot.len() <= r {
1391                        vt.by_slot.push(Vec::new());
1392                    }
1393                    vt.by_slot[r].push((0, u16::MAX, id));
1394                    phis.insert(key, id);
1395                    id
1396                }
1397            }
1398        };
1399        *slot = Reg::Live(phi);
1400    }
1401    out
1402}
1403
1404/// Type of a phi var: join of the non-null side values' erased types.
1405fn join_side_types(vt: &VarTable, sides: &[&[Reg]], r: usize) -> TypeRef {
1406    let mut ty: Option<JavaType> = None;
1407    for s in sides {
1408        let st = s.get(r).cloned().unwrap_or(Reg::Undef);
1409        let e = match st {
1410            Reg::Pending(e) | Reg::PendingCall(e) => e,
1411            Reg::Live(v) => Expr::Local {
1412                var: v,
1413                ty: vt.var(v).ty.clone(),
1414            },
1415            _ => continue,
1416        };
1417        let t = e.type_ref().erased();
1418        ty = Some(match ty {
1419            None => t,
1420            Some(prev) => join_types(&prev, &t),
1421        });
1422    }
1423    TypeRef::J(ty.unwrap_or(JavaType::Int))
1424}
1425
1426fn join_types(a: &JavaType, b: &JavaType) -> JavaType {
1427    if a == b {
1428        return a.clone();
1429    }
1430    let num = |t: &JavaType| {
1431        matches!(
1432            t,
1433            JavaType::Boolean
1434                | JavaType::Byte
1435                | JavaType::Char
1436                | JavaType::Short
1437                | JavaType::Int
1438                | JavaType::Long
1439                | JavaType::Float
1440                | JavaType::Double
1441        )
1442    };
1443    if num(a) && num(b) {
1444        // Numeric promotion.
1445        return match (a, b) {
1446            (JavaType::Double, _) | (_, JavaType::Double) => JavaType::Double,
1447            (JavaType::Float, _) | (_, JavaType::Float) => JavaType::Float,
1448            (JavaType::Long, _) | (_, JavaType::Long) => JavaType::Long,
1449            _ => JavaType::Int,
1450        };
1451    }
1452    if let (JavaType::Object(x), JavaType::Object(y)) = (a, b) {
1453        if x == y {
1454            return a.clone();
1455        }
1456        // Char/int ternaries join to int; otherwise objects join to Object.
1457        return JavaType::Object("java/lang/Object".into());
1458    }
1459    JavaType::Object("java/lang/Object".into())
1460}
1461
1462/// True when the block's terminator exits (used by callers to skip appends).
1463#[allow(dead_code)]
1464fn is_exit_term(term: &jdc_core::ir::build::Term) -> bool {
1465    matches!(
1466        term,
1467        jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
1468    )
1469}
1470
1471#[allow(dead_code)]
1472fn unused(_: &InsnKind) {}