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    // SSA Phase 0 census (read-only, DDC_SSA_REPORT-gated).
122    if crate::ssa_census::enabled() {
123        crate::ssa_census::census_method(&cfg, &env);
124    }
125
126    // Visiting order: reverse postorder, then any stragglers (so every block
127    // is built at least once even when unreachable).
128    let core_for_order = cfg.to_core();
129    let universe: jdc_core::FxHashSet<usize> = (0..n).collect();
130    let mut order = reverse_postorder(&core_for_order, core_for_order.entry, &universe);
131    {
132        let mut seen: jdc_core::FxHashSet<usize> = order.iter().copied().collect();
133        for b in &cfg.blocks {
134            if seen.insert(b.id) {
135                order.push(b.id);
136            }
137        }
138    }
139
140    // Handler blocks: entry state approximated by the try-entry state (the
141    // dominant pattern: catch reads values established before the try).
142    let mut handler_entry_block: HashMap<usize, usize> = HashMap::default();
143    for b in &cfg.blocks {
144        if b.handlers.is_empty() {
145            continue;
146        }
147        let mut best: Option<(u32, usize)> = None;
148        for &ri in &b.handlers {
149            if let Some(r) = cfg.exc_ranges.get(ri) {
150                if best.map(|(s, _)| r.start < s).unwrap_or(true) {
151                    if let Some(eb) = cfg.block_at(r.start) {
152                        best = Some((r.start, eb));
153                    }
154                }
155            }
156        }
157        if let Some((_, eb)) = best {
158            handler_entry_block.insert(b.id, eb);
159        }
160    }
161
162    // ---- fixpoint: register states across blocks ----
163    let mut results: Vec<BlockResult> = Vec::with_capacity(n);
164    results.resize_with(n, || BlockResult {
165        stmts: vec![],
166        out_stack: vec![],
167        term: jdc_core::ir::build::Term::Return(None),
168    });
169    let mut out_states: Vec<Option<OutState>> = vec![None; n];
170    // Stable (block, register) → var ids across worklist rebuilds: keeps
171    // re-lifts id-deterministic so the fixpoint CONVERGES instead of
172    // cascading (was: 30M block-lifts on weibo, ~60 per block).
173    let mut stable_vars: HashMap<(usize, u16, u64), u32> = HashMap::default();
174    // Method feature flags OR-merged from every block lift: gates
175    // post-lift passes that can only match if the bytecode contained the
176    // feature (most methods contain none).
177    let mut mflags = crate::lift::MethodFlags::none();
178    // Try-entry INPUT snapshots (for handler-block approximation) — only
179    // try-entry starts (rare) keep their input state; no persistent
180    // per-block copies.
181    let mut try_entry_snapshots: HashMap<usize, Vec<Reg>> = HashMap::default();
182    let mut built_once = vec![false; n];
183    let mut errors: HashMap<usize, String> = HashMap::default();
184    // (merge block, register) → phi var id.
185    let mut phis: HashMap<(usize, u16), u32> = HashMap::default();
186    // pred → (write_pc, phi var, value) materializations.
187
188    let entry_is_handler = handler_entry_block.contains_key(&0);
189
190    // Per-visit costs hoisted out of the worklist loop: the try-entry scan
191    // (all exc ranges × a binary search per range) and the handler catch
192    // types (String clones) re-ran on EVERY visit — visits average 2.5×
193    // blocks on real code, far more on monsters.
194    let try_entry_flags: Vec<bool> = (0..n)
195        .map(|b| {
196            !cfg.blocks[b].handlers.is_empty()
197                || cfg
198                    .exc_ranges
199                    .iter()
200                    .any(|r| cfg.block_at(r.start) == Some(b))
201        })
202        .collect();
203    let handler_types: Vec<Vec<Option<std::sync::Arc<str>>>> =
204        (0..n).map(|b| handler_types_for(&cfg, b)).collect();
205
206    // Worklist fixpoint with version stamps: a block rebuilds only when the
207    // OUT-state versions of its inputs changed. This avoids the previous
208    // every-round full pass, which deep-cloned and deep-compared the whole
209    // register state (Expr trees) of every block — the dominant cost of
210    // large methods.
211    let mut ver: Vec<u64> = vec![0; n]; // out-state version per block
212    let mut built_ver: Vec<u64> = vec![u64::MAX; n]; // input signature when built
213                                                     // input signature: entry=0; otherwise XOR/sum of (pred, ver[pred]) pairs.
214    fn input_sig(cfg: &DexCfg, bid: usize, ver: &[u64]) -> u64 {
215        let mut h: u64 = 1;
216        for &p in &cfg.blocks[bid].pred {
217            h = h
218                .wrapping_mul(31)
219                .wrapping_add(p as u64)
220                .wrapping_mul(31)
221                .wrapping_add(ver[p]);
222        }
223        // Handler blocks also depend on their try-entry block's input.
224        h
225    }
226    let mut queue: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
227    let mut queued: Vec<bool> = vec![false; n];
228    for &bid in &order {
229        queue.push_back(bid);
230        queued[bid] = true;
231    }
232    // merge bid → [(pred, write_pc, phi var, value)] — re-recorded whole on
233    // each visit of the merge block (stale rounds must not accumulate).
234    let mut appends: HashMap<usize, Vec<(usize, u32, u32, Expr)>> = HashMap::default();
235    let mut total_visits: usize = 0;
236    let visit_cap: usize = 64 * n + 256;
237
238    while let Some(bid) = queue.pop_front() {
239        queued[bid] = false;
240        total_visits += 1;
241        if total_visits > visit_cap {
242            CAP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
243            CAP_INSNS.fetch_add(
244                insn_count as u64 * 1000 + n as u64,
245                std::sync::atomic::Ordering::Relaxed,
246            );
247            break; // degenerate oscillation guard
248        }
249        let is_handler = handler_entry_block.contains_key(&bid);
250        // 1. Signature gate FIRST: a visit whose input versions are
251        //    unchanged skips the (clone-heavy) input-state computation
252        //    entirely — that clone was the fixpoint's dominant cost.
253        let sig = input_sig(&cfg, bid, &ver)
254            ^ (if is_handler {
255                let eb = handler_entry_block[&bid];
256                (eb as u64) << 32
257            } else {
258                0
259            });
260        let need_build = !built_once[bid] || built_ver[bid] != sig;
261        if !need_build {
262            // Handler blocks depend on their try-entry block's INPUT —
263            // when that entry is re-visited, the handler is re-queued; a
264            // skipped visit here means the recorded state is current.
265            continue;
266        }
267        // 2. Input register state (only on rebuild).
268        let ins: Vec<Reg> = if bid == cfg.entry {
269            if cfg.blocks[0].pred.is_empty() || entry_is_handler {
270                entry.clone()
271            } else {
272                // A loop back into pc 0: params are one side of the merge.
273                // Sides are BORROWED (cloning each pred's state here was a
274                // top fixpoint cost).
275                let mut sides: Vec<&[Reg]> = vec![entry.as_slice()];
276                for p in cfg.blocks[bid].pred.clone() {
277                    if let Some(o) = &out_states[p] {
278                        sides.push(o.regs.as_slice());
279                    }
280                }
281                let merged =
282                    merge_states(&mut vt, &mut phis, bid, &sides, &env.debug_locals, cfg.blocks[bid].start);
283                // The entry side's phi contributions become leading
284                // assignments in the entry block (virtual pred). The entry
285                // block may be re-visited by the worklist — each visit
286                // replaces (not appends) its records.
287                let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
288                for (r, st) in entry.iter().enumerate() {
289                    if let Some(&phi) = phis.get(&(bid, r as u16)) {
290                        let value = match st {
291                            Reg::Live(v) if *v == phi => continue,
292                            Reg::Live(v) => Expr::Local {
293                                var: *v,
294                                ty: vt.var(*v).ty.clone(),
295                            },
296                            Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
297                            Reg::Undef | Reg::WideHi => continue,
298                        };
299                        recs.push((usize::MAX, 0, phi, value));
300                    }
301                }
302                appends.insert(bid, recs);
303                merged
304            }
305        } else if is_handler {
306            let eb = handler_entry_block[&bid];
307            try_entry_snapshots
308                .get(&eb)
309                .cloned()
310                .unwrap_or_else(|| vec![Reg::Undef; env.code.registers_size as usize])
311        } else {
312            // Borrowed sides; the single-pred fast path clones once (the
313            // lifter needs an owned copy anyway).
314            let mut sides: Vec<&[Reg]> = Vec::new();
315            for p in cfg.blocks[bid].pred.clone() {
316                if let Some(o) = &out_states[p] {
317                    sides.push(o.regs.as_slice());
318                }
319            }
320            if sides.is_empty() {
321                vec![Reg::Undef; env.code.registers_size as usize]
322            } else if sides.len() == 1 {
323                sides[0].to_vec()
324            } else {
325                merge_states(
326                    &mut vt,
327                    &mut phis,
328                    bid,
329                    &sides,
330                    &env.debug_locals,
331                    cfg.blocks[bid].start,
332                )
333            }
334        };
335
336        // 3. Phi materialization records for predecessors — recomputed for
337        //    this block only; later pred rebuilds re-visit the merge and
338        //    refresh them (the last visit wins).
339        if phis_for_merge(bid, &phis) {
340            let mut recs: Vec<(usize, u32, u32, Expr)> = Vec::new();
341            record_appends(&cfg, bid, &out_states, &phis, &vt, &mut recs);
342            // Entry-merge visits also carry the entry-side contributions —
343            // preserve those (recorded above when bid == entry).
344            if bid == cfg.entry {
345                if let Some(prev) = appends.get(&bid) {
346                    for (p, pc, v, e) in prev.iter() {
347                        if *p == usize::MAX {
348                            recs.push((*p, *pc, *v, e.clone()));
349                        }
350                    }
351                }
352            }
353            appends.insert(bid, recs);
354        }
355
356        // 4. Build (signature known changed). The lifter CONSUMES `ins`
357        //    (moved, not cloned); try-entry snapshots preserve the input
358        //    state for the handler blocks approximating from it.
359        built_once[bid] = true;
360        built_ver[bid] = sig;
361        if try_entry_flags[bid] {
362            try_entry_snapshots.insert(bid, ins.clone());
363        }
364        BUILD_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
365        INSN_LIFTED.fetch_add(
366            cfg.block_ins(&cfg.blocks[bid]).len() as u64,
367            std::sync::atomic::Ordering::Relaxed,
368        );
369        let htypes = &handler_types[bid];
370        let block_ins = cfg.block_ins(&cfg.blocks[bid]);
371        let lifter = Lifter::new(&env, &mut vt, ins, bid, &mut stable_vars, &mut mflags);
372        let rebuilt = match lifter.build_block(block_ins, htypes, method_final_reads.clone()) {
373            Ok((r, out)) => {
374                results[bid] = r;
375                let changed = match &out_states[bid] {
376                    Some(prev) => prev.regs != out.regs,
377                    None => true,
378                };
379                out_states[bid] = Some(out);
380                changed
381            }
382            Err(msg) => {
383                results[bid] = BlockResult {
384                    stmts: vec![Stmt::Comment(format!("$DDC-BLOCK-ERROR: {msg}"))],
385                    out_stack: vec![],
386                    term: jdc_core::ir::build::Term::Return(None),
387                };
388                out_states[bid] = Some(OutState {
389                    regs: vec![Reg::Undef; env.code.registers_size as usize],
390                    write_pc: vec![0; env.code.registers_size as usize],
391                });
392                errors.insert(bid, msg);
393                false
394            }
395        };
396        if rebuilt {
397            ver[bid] += 1;
398            // Successors re-check their input signature.
399            for &succ in &cfg.blocks[bid].succ {
400                if !queued[succ] && succ < n {
401                    queue.push_back(succ);
402                    queued[succ] = true;
403                }
404            }
405            // Handler blocks watch their try-entry block's INPUT — cheap
406            // approximation: also queue the handler of every range this
407            // block belongs to.
408            if is_handler {
409                let eb = handler_entry_block[&bid];
410                if !queued[eb] && eb < n {
411                    queue.push_back(eb);
412                    queued[eb] = true;
413                }
414            }
415            // Try-entry inputs: when this block feeds a handler entry via a
416            // try range, queue that handler.
417            for &ri in &cfg.blocks[bid].handlers {
418                if let Some(r) = cfg.exc_ranges.get(ri) {
419                    if let Some(hb) = cfg.block_at(r.handler) {
420                        if !queued[hb] && hb < n {
421                            queue.push_back(hb);
422                            queued[hb] = true;
423                        }
424                    }
425                }
426            }
427        }
428    }
429
430    // Entry-side phi contributions: carried as declaration-with-init and
431    // prepended to the method body AFTER conversion (the entry block may be
432    // a loop header — its statements re-execute per iteration).
433    // Entry-side phi contributions (the virtual pred): captured for the
434    // method-top declarations; the REAL preds' records stay in `appends`
435    // for the commit loop (removing the whole entry key would lose the
436    // loop-body assignments — the phis would collapse to their entry
437    // values).
438    let mut entry_phi_inits: Vec<(u32, Expr)> = Vec::new();
439    if let Some(recs) = appends.get_mut(&cfg.entry) {
440        let mut entry_side: Vec<(u32, Expr)> = Vec::new();
441        recs.retain(|(p, _, v, e)| {
442            if *p == usize::MAX {
443                entry_side.push((*v, e.clone()));
444                false
445            } else {
446                true
447            }
448        });
449        entry_side.sort_by_key(|(v, _)| *v);
450        entry_phi_inits = entry_side;
451    }
452
453    // Commit phi materializations: each pred assigns its outgoing value to
454    // the merge var, ordered by the pc of the instruction that produced it.
455    // Values that REFERENCE a sibling phi are snapshotted into a fresh temp
456    // first: register rotations (`a = b; b = a % b`) would otherwise read
457    // the already-reassigned phi (stale capture).
458    // Regroup: merge-keyed records → per-pred statement lists.
459    //
460    // Deterministic order: `adds.sort_by_key(pc)` below is a STABLE sort,
461    // so same-pc records (one jump feeding several merge vars) keep
462    // their push order — iterating `appends` in map order made that
463    // order hasher-dependent (SipHash seeds per process: output was NOT
464    // byte-stable across runs; 243/5579 files wobbled on reqable).
465    // Sorted block ids here + sorted preds below pin every tie.
466    let mut merge_order: Vec<usize> = appends.keys().copied().collect();
467    merge_order.sort_unstable();
468    let mut per_pred: HashMap<usize, Vec<(u32, u32, Expr)>> = HashMap::default();
469    for bid in merge_order {
470        for (p, pc, v, e) in &appends[&bid] {
471            per_pred.entry(*p).or_default().push((*pc, *v, e.clone()));
472        }
473    }
474    let mut pred_order: Vec<usize> = per_pred.keys().copied().collect();
475    pred_order.sort_unstable();
476    for p in pred_order {
477        let mut adds = per_pred.remove(&p).unwrap();
478        if p == usize::MAX {
479            continue;
480        }
481        adds.sort_by_key(|(pc, _, _)| *pc);
482        let term_is_exit = matches!(
483            results[p].term,
484            jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
485        );
486        if term_is_exit {
487            continue;
488        }
489        let phi_set: std::collections::HashSet<u32> = adds.iter().map(|(_, v, _)| *v).collect();
490        let mut snapshots: Vec<Stmt> = Vec::new();
491        // (phi, value) pairs with snapshot temps substituted.
492        let mut emitted: Vec<(u32, Expr)> = Vec::new();
493        for (_, v, e) in &adds {
494            let mut e = e.clone();
495            let mut refs_phi = false;
496            visit_phi_refs(&e, &phi_set, &mut refs_phi);
497            if refs_phi {
498                // Snapshot: emit `temp = value` BEFORE any phi assignment.
499                let ty = e.type_ref();
500                let id = vt.vars.len() as u32;
501                let name = format!("v{}", id);
502                vt.vars.push(jdc_core::var::VarInfo {
503                    id,
504                    slot: u16::MAX,
505                    name,
506                    ty: ty.clone(),
507                    is_param: false,
508                    range_start: 0,
509                    range_end: u16::MAX,
510                    synthetic_name: true,
511                });
512                snapshots.push(Stmt::LocalDef {
513                    var: id,
514                    init: Some(e),
515                    is_final: false,
516                    force_type: true,
517                });
518                e = Expr::Local { var: id, ty };
519            }
520            emitted.push((*v, e));
521        }
522        for st in snapshots {
523            results[p].stmts.push(st);
524        }
525        for (v, e) in emitted {
526            results[p].stmts.push(Stmt::ExprStmt(Expr::Assign {
527                target: Box::new(Expr::Local {
528                    var: v,
529                    ty: vt.var(v).ty.clone(),
530                }),
531                op: jdc_core::ir::expr::AssignOp::Plain,
532                value: Box::new(e),
533            }));
534        }
535    }
536
537    let t_fix = t0;
538    phase_hit_n(0, n, t_fix);
539    // ---- single-block fast path ----
540    // A lone basic block is straight-line code (any branch/switch/handler
541    // splits the graph): no merges, no phis, no control flow to structure.
542    // Bypassing the structurer + converter + the control-flow passes for
543    // these (over half of R8-produced methods) cuts the dominant cost.
544    if n == 1 && !entry_is_handler && cfg.blocks[0].pred.is_empty() {
545        let r = std::mem::replace(
546            &mut results[0],
547            BlockResult {
548                stmts: vec![],
549                out_stack: vec![],
550                term: jdc_core::ir::build::Term::Goto,
551            },
552        );
553        let mut body = r.stmts;
554        match r.term {
555            jdc_core::ir::build::Term::Return(Some(e)) => {
556                body.push(Stmt::Return(Some(e)));
557            }
558            jdc_core::ir::build::Term::Return(None) => {}
559            jdc_core::ir::build::Term::Throw(e) => body.push(Stmt::Throw(e)),
560            _ => {}
561        }
562        let mut body = Stmt::Block(body);
563        passes::fused_expr_rewrites(&mut body, &vt);
564        if mflags.has_sb() {
565            passes::fold_string_builders(&mut body, &vt);
566        }
567        passes::forward_single_use(&mut body, &vt);
568        passes::cleanup(&mut body);
569        passes::inline_accessors(&mut body, pool, &class.name);
570        passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
571        passes::fix_ref_null_assigns(&vt, &mut body);
572        passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
573        passes::split_generations(&mut vt, &mut body, pool);
574        passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
575        passes::fix_field_owner_downcasts(&mut body, &vt, pool);
576        passes::fix_shadowed_super_fields(&mut body, &vt, pool, &class.name);
577        passes::fix_incomparable_equality(&mut body, &vt, pool);
578        passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
579        passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
580        passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
581        passes::fix_int_operand_bridges(&mut body, &vt);
582        passes::fix_ref_array_null_consts(&mut body);
583        passes::idiom_compounds(&mut body, &vt);
584        passes::rescue_primitive_receivers(&mut body, &vt, pool);
585        passes::fix_this0_owners(&mut body, &class.name);
586        passes::apply_local_names(&mut vt, &body);
587    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
588        passes::remove_kotlin_checks(&mut body);
589        passes::rewrite_kotlin_facades(&mut body, pool);
590        passes::platform_constants(&mut body);
591        passes::drop_dead_locals(&mut body);
592    passes::drop_dead_raw_news(&mut body);
593    passes::mark_field_owner_concrete(&mut vt, &mut body);
594    passes::ensure_declared(&mut body, &vt);
595    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
596    // AFTER the declaration hoisting: ensure_declared inserts bare
597    // top-of-method declarations, and a local declaration ahead of the
598    // super() call is still "super must be first statement".
599    if &*m.name == "<init>" {
600        // Boolean value-diamond folds ahead of the delegation machinery:
601        // a branched bridge ctor whose else arm COMPUTES the defaulted
602        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
603        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
604        // (interleaved forwarding inlines the impure `u` the fold
605        // exposes) the arm is linear defs and merge_at lifts the this()
606        // (lark MmCreateAudioRequest, this-not-first ×456 family).
607        passes::fold_bool_value_diamonds(&mut body, &vt);
608        passes::fold_value_diamonds(&mut body, &vt);
609        passes::fix_ctor_this_aliases(&mut body, &vt);
610        // Vendor hotfix ctor guards wrap the delegation inside an If and
611        // fire for ENUM ctors too (alipay InstantRun fallback enums are
612        // the whole 1,436 ctor-not-first population) — run before the
613        // enum/regular split, and before the classdec trace-param store
614        // injection whose delegation-first probe must see the real head.
615        passes::strip_ctor_hotfix_guards(&mut body);
616        if class.is_enum() {
617            passes::fold_enum_default_arg_bridge(&mut body);
618            // Strip the implicit Enum.<init> super() ONLY for the enum
619            // BASE (super is java/lang/Enum or Object — a true `enum`
620            // decl or the fallback `/* enum */ class`, both get an
621            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
622            // (j$6, super = the enum base j) renders as a plain
623            // `class j$6 extends j`; its ctor MUST forward
624            // `super(name, ordinal, ..)` or the implicit no-arg super()
625            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
626            // TokeniserState ×134).
627            let const_subclass = class
628                .super_name
629                .as_ref()
630                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
631                .unwrap_or(false);
632            if !const_subclass {
633                passes::strip_enum_ctor_super(&mut body);
634            }
635        } else {
636            passes::fix_ctor_delegation_arg_defs(&mut body);
637            passes::fix_ctor_conditional_super(&mut body);
638            passes::fix_ctor_super_first(&mut body, &vt);
639            passes::dedupe_ctor_delegations(&mut body);
640            passes::strip_secondary_delegations(&mut body);
641            passes::hoist_branch_delegations(&mut body, &vt);
642            passes::extract_branched_delegation_helper(&mut body, &vt, pool, class, &desc.to_string());
643        }
644        // The delegation merges/hoists can leave prelude decls dead
645        // (their defs were inlined into the merged call) — the dropper
646        // ran BEFORE the ctor passes, so re-run it on their output.
647        passes::drop_dead_locals(&mut body);
648    }
649        passes::strip_trailing_void_return(&mut body);
650        passes::cleanup(&mut body);
651        passes::invert_empty_thens(&mut body);
652        passes::fold_short_circuits(&mut body);
653        passes::resolve_dangling_gotos(&mut body);
654    passes::dedupe_multicatch(&mut body, pool);
655    passes::strip_phantom_field_writes(&mut body, pool);
656    passes::init_bare_decls(&mut body, &vt);
657        if !errors.is_empty() {
658            passes::prepend_comment(
659                &mut body,
660                format!("$DDC: {} block(s) failed to decompile", errors.len()),
661            );
662        }
663        phase_hit_n(2, n, t_fix);
664        record_bucket(n, t0);
665        return Ok(Some(MethodBody { body, vt, desc }));
666    }
667
668    // ---- structure + convert ----
669    // jcdc's copy-budget degradation: a rendering whose statement tree
670    // explodes past the guard retries at a halved copy budget (the
671    // structurer's tail-copying is the exponential mechanism).
672    const TREE_GUARD: usize = 20_000;
673    let core_cfg = cfg.to_core();
674    #[allow(unused_assignments)]
675    let mut body: Option<Stmt> = None;
676    let mut prev_size: Option<usize> = None;
677    // Copy budget scales with graph size: many-block methods are where the
678    // exponential tail-copy blowups live (weibo: 389 methods >100 blocks
679    // = 40% of all CPU at budget 512). Starting lower converges without
680    // the 6-round halving.
681    let mut budget: u32 = if n > 100 {
682        64
683    } else if n > 20 {
684        128
685    } else {
686        512
687    };
688    // Shared once-per-method artifacts: the O(groups²) exception-group
689    // scan and the full-graph dominator tree used to run TWICE per
690    // method (Structurer + Converter) and once more per copy-budget
691    // retry — monster classes (gson adapters) spent the bulk of their
692    // time there.
693    let groups = jdc_core::structure::group_exceptions_with(&core_cfg, Some(&results));
694    let dom_universe: jdc_core::FxHashSet<usize> = (0..core_cfg.blocks.len()).collect();
695    let dom = jdc_core::structure::compute_dominators(&core_cfg, &dom_universe, core_cfg.entry);
696    if trace_on() {
697        eprintln!("[mshape] {}.{} blocks={}", class.name, m.name, n);
698    }
699    // Deterministic giant-method stub: at ~2.1k+ CFG blocks a single
700    // structuring walk can burn 9s+ of wall time (weibo Gson doRead:
701    // 2,179/3,230 blocks — per-visit dominator-pass cost scales far
702    // faster than the Σ universe.len() charge model can bound, and the
703    // spread across CFG shapes defeats any charge calibration). Healthy
704    // methods below the line (JsonUserInfoTypeAdapter, 1,997 blocks)
705    // structure fully, so stubbing beats both alternatives: burning the
706    // class watchdog DROPS the whole file (every referrer cannot-finds)
707    // and the old wall-clock deadline flipped output nondeterministically
708    // under worker contention.
709    if n >= 2_100 {
710        return Ok(Some(stub_body(
711            format!(
712                "$DDC: method too large ({} blocks) — body elided for determinism",
713                n
714            ),
715            desc,
716        )));
717    }
718    #[cfg(feature = "visit-stats")]
719    {
720        jdc_core::structure::reset_visit_stats();
721    }
722    // Walk-visit budget, proportional to the block count: walk() runs
723    // roughly once per structured scope for sane CFGs, so 40n+512 is
724    // generous headroom — but the EXPONENTIAL explorations (Telegram
725    // SendMessagesHelper family: deep if/loop/try nesting whose scope
726    // count multiplies) consume visits geometrically and get cut to a
727    // Goto, which terminates the walk. Without this a single <16k-insn
728    // method can recurse for effectively forever while the worker (and
729    // the process) never finishes — Telegram's full run wrote every file
730    // yet hung for 300+ seconds on 25 such classes.
731    let walk_budget: u64 = walk_budget_override().unwrap_or(8 * n as u64 + 128);
732    // WORK budget (Σ universe.len() per visit): deterministic bound on
733    // total walk cost — the count budget above under-bounds per-visit
734    // cost for big-block exponential explorations (Telegram family),
735    // which the wall-clock deadline used to catch nondeterministically.
736    // A visit's REAL cost grows with the universe (dominator-style
737    // passes: weibo doRead n=2179 burned 15µs per charge unit vs 5µs at
738    // n=1533), so a flat charge budget still lets giants run 9s+ per
739    // rung and trip the class watchdog (dropped files — every referrer
740    // cannot-finds — are strictly worse than walk-cut degradation).
741    let walk_work_budget: u64 = walk_work_override()
742        .unwrap_or(600_000 + 128 * n as u64);
743    // No wall-clock deadline here: the work budget above bounds walk
744    // cost deterministically, and the old 1500ms guard flipped
745    // borderline giants (weixin vm/a0.n, 28.5k nodes) between full body
746    // and exploded stub run-to-run under worker contention. The
747    // class-level 5s watchdog in classdec remains as the hang safety
748    // net for pathological CFGs.
749    loop {
750        jdc_core::structure::set_budget_override(Some(budget));
751        jdc_core::structure::set_walk_visit_budget(Some(walk_budget));
752        jdc_core::structure::set_walk_work_budget(Some(walk_work_budget));
753        let mut st = Structurer::with_shared_groups(
754            &core_cfg,
755            &results,
756            &groups,
757            Default::default(),
758            Default::default(),
759        );
760        let tw0 = std::time::Instant::now();
761        let region = st.structure_method();
762        let tw1 = std::time::Instant::now();
763        let mut converter = Converter::with_precomputed_ref(&core_cfg, &results, &groups, &dom);
764        let candidate = converter.convert(region);
765        let tw2 = std::time::Instant::now();
766        if trace_on() {
767            eprintln!(
768                "[rung] {}.{} budget={} walk={:?} convert={:?}",
769                class.name, m.name, budget, tw1 - tw0, tw2 - tw1
770            );
771        }
772        jdc_core::structure::set_budget_override(None);
773        jdc_core::structure::set_walk_visit_budget(None);
774        jdc_core::structure::set_walk_work_budget(None);
775        let size = {
776            let mut c = 0usize;
777            passes::count_stmts_deep(&candidate, &mut c);
778            c
779        };
780        if trace_on() {
781            eprintln!("[guard] {}.{} size={} budget={}", class.name, m.name, size, budget);
782        }
783        if size <= TREE_GUARD {
784            body = Some(candidate);
785            break;
786        }
787        // Giant short-circuit: deep in the ladder (budget ≤ 64), a tree
788        // still 3× over the guard will not shrink under further copy-budget
789        // halving (weixin cdp/l1.w: 72,782 nodes at 64, ~2.8s of walk PER
790        // rung) — stub now instead of burning two more rungs and tripping
791        // the classdec 5s watchdog, which DROPS the whole file (every
792        // referrer cannot-finds — strictly worse than one stubbed body).
793        // Deterministic: driven by measured size, not wall-clock.
794        if budget <= 64 && size > 3 * TREE_GUARD {
795            return Ok(Some(stub_body(
796                format!(
797                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
798                    size
799                ),
800                desc,
801            )));
802        }
803        // No-progress short-circuit: the copy budget only bounds tail
804        // duplication — if halving it did not shrink the tree at all,
805        // further rungs cannot either (weixin vm/a0.n sits at ~28.5k
806        // across every rung, burning a full work-budget walk each).
807        // Deterministic, and saves the giant methods ~3 rungs of walk.
808        if budget <= 32 && prev_size.is_some_and(|p| size >= p) {
809            return Ok(Some(stub_body(
810                format!(
811                    "$DDC: statement tree exploded ({} nodes) — pathological CFG, body elided",
812                    size
813                ),
814                desc,
815            )));
816        }
817        prev_size = Some(size);
818        if budget <= 16 {
819            return Ok(Some(stub_body(
820                format!(
821                    "$DDC: statement tree exploded ({} nodes) even at copy budget 16",
822                    size
823                ),
824                desc,
825            )));
826        }
827        budget /= 2;
828    }
829    #[cfg(feature = "visit-stats")]
830    if trace_on() && n > 3 {
831        let used = jdc_core::structure::walk_visits_consumed();
832        eprintln!(
833            "[visits] {}.{} blocks={} consumed={} ratio={:.1}",
834            class.name,
835            m.name,
836            n,
837            used,
838            used as f64 / n as f64
839        );
840    }
841    phase_hit_n(1, n, t_fix);
842    let mut body = body.unwrap();
843    if !entry_phi_inits.is_empty() {
844        let head: Vec<Stmt> = entry_phi_inits
845            .into_iter()
846            .map(|(v, e)| Stmt::LocalDef {
847                var: v,
848                init: Some(e),
849                is_final: false,
850                force_type: true,
851            })
852            .collect();
853        body = match body {
854            Stmt::Block(v) => {
855                let mut nv = head;
856                nv.extend(v);
857                Stmt::Block(nv)
858            }
859            other => {
860                let mut nv = head;
861                nv.push(other);
862                Stmt::Block(nv)
863            }
864        };
865    }
866
867    passes::bind_catches(&mut body, &mut vt);
868    passes::prune_unreachable(&mut body);
869    // One traversal for cmp residuals + null compares + const-first flips
870    // (three separate full-tree walks before).
871    passes::fused_expr_rewrites(&mut body, &vt);
872    if mflags.has_sb() {
873        passes::fold_string_builders(&mut body, &vt);
874    }
875    passes::ternary_fold(&mut body);
876    if mflags.has_monitor() {
877        passes::fold_synchronized(&mut body);
878    }
879    passes::forward_single_use(&mut body, &vt);
880    passes::cleanup(&mut body);
881    passes::inline_accessors(&mut body, pool, &class.name);
882    passes::infer_types(&mut vt, &mut body, &desc.ret, &env);
883    passes::fix_ref_null_assigns(&vt, &mut body);
884    passes::fix_null_sentinels(&mut body, &vt, &desc.ret);
885    passes::split_generations(&mut vt, &mut body, pool);
886    // Post-booleanize re-split, gated on a nonzero conversion count:
887    // conversions expose register reuse across boolean/numeric kinds no
888    // earlier pass could see (`int v150` copying converted `boolean
889    // v131` — weixin ConstraintLayout ×1.4k); with nothing converted
890    // the fixpoint walk is pure decomp-time cost (the weixin 16→24s
891    // regression).
892    // Booleanize ↔ split fixpoint, bounded, ENDING on a booleanize:
893    // each split MINTS fresh generation vars that inherit the stale int
894    // type while receiving boolean values (`int v264_g160_g7_g3 =
895    // !v200` with `!= 0` reads — weixin bool→int assign family, 2.8k
896    // lines). Only a FOLLOWING booleanize retypes them and folds their
897    // `v != 0` reads; a trailing split would leave the folds undone.
898    {
899        let rb = matches!(desc.ret, JavaType::Boolean);
900        let mut rounds = 0;
901        loop {
902            let c = passes::booleanize(&mut vt, &mut body, rb);
903            rounds += 1;
904            if c == 0 || rounds >= 3 {
905                break;
906            }
907            passes::split_generations(&mut vt, &mut body, pool);
908        }
909    }
910    if matches!(
911        desc.ret,
912        JavaType::Int | JavaType::Long | JavaType::Short | JavaType::Byte | JavaType::Float | JavaType::Double
913    ) {
914        passes::fix_int_returns(&vt, &mut body);
915    }
916    if matches!(desc.ret, JavaType::Boolean) {
917        passes::fix_bool_returns(&vt, &mut body);
918    }
919    passes::insert_object_narrowing_casts(&vt, &mut body, pool, &desc.ret);
920    passes::fix_field_owner_downcasts(&mut body, &vt, pool);
921    passes::fix_shadowed_super_fields(&mut body, &vt, pool, &class.name);
922    passes::fix_incomparable_equality(&mut body, &vt, pool);
923    passes::fix_primitive_assign_casts(&vt, &mut body, &desc.ret);
924    passes::fix_primitive_arg_bridges(&mut body, &vt, pool);
925    passes::fix_bool_xor(&mut body, &vt, matches!(desc.ret, JavaType::Boolean));
926    passes::fix_int_operand_bridges(&mut body, &vt);
927    passes::fix_ref_array_null_consts(&mut body);
928    passes::idiom_compounds(&mut body, &vt);
929    passes::rescue_primitive_receivers(&mut body, &vt, pool);
930    passes::fix_this0_owners(&mut body, &class.name);
931    passes::apply_local_names(&mut vt, &body);
932    passes::deshadow_locals(&mut vt, pool, &class.name, &body);
933    passes::remove_kotlin_checks(&mut body);
934    passes::rewrite_kotlin_facades(&mut body, pool);
935    passes::platform_constants(&mut body);
936    passes::drop_dead_locals(&mut body);
937    passes::drop_dead_raw_news(&mut body);
938    passes::mark_field_owner_concrete(&mut vt, &mut body);
939    passes::ensure_declared(&mut body, &vt);
940    passes::rescue_arg_return_swaps(&mut body, &vt, pool, &desc.ret);
941    // AFTER the declaration hoisting: ensure_declared inserts bare
942    // top-of-method declarations, and a local declaration ahead of the
943    // super() call is still "super must be first statement".
944    if &*m.name == "<init>" {
945        // Boolean value-diamond folds ahead of the delegation machinery:
946        // a branched bridge ctor whose else arm COMPUTES the defaulted
947        // boolean (`v=false; if(x!=null){u=x.m(); v=false; if(u){v=true}}`)
948        // is Dirty for split_branch — folded to `v = x!=null && x.m()`
949        // (interleaved forwarding inlines the impure `u` the fold
950        // exposes) the arm is linear defs and merge_at lifts the this()
951        // (lark MmCreateAudioRequest, this-not-first ×456 family).
952        passes::fold_bool_value_diamonds(&mut body, &vt);
953        passes::fold_value_diamonds(&mut body, &vt);
954        passes::fix_ctor_this_aliases(&mut body, &vt);
955        // Vendor hotfix ctor guards wrap the delegation inside an If and
956        // fire for ENUM ctors too (alipay InstantRun fallback enums are
957        // the whole 1,436 ctor-not-first population) — run before the
958        // enum/regular split, and before the classdec trace-param store
959        // injection whose delegation-first probe must see the real head.
960        passes::strip_ctor_hotfix_guards(&mut body);
961        if class.is_enum() {
962            passes::fold_enum_default_arg_bridge(&mut body);
963            // Strip the implicit Enum.<init> super() ONLY for the enum
964            // BASE (super is java/lang/Enum or Object — a true `enum`
965            // decl or the fallback `/* enum */ class`, both get an
966            // implicit Object/Enum super). An enum CONSTANT SUBCLASS
967            // (j$6, super = the enum base j) renders as a plain
968            // `class j$6 extends j`; its ctor MUST forward
969            // `super(name, ordinal, ..)` or the implicit no-arg super()
970            // fails ("对于j(没有参数), 找不到合适的构造器", weibo jsoup
971            // TokeniserState ×134).
972            let const_subclass = class
973                .super_name
974                .as_ref()
975                .map(|s| s != "java/lang/Object" && s != "java/lang/Enum")
976                .unwrap_or(false);
977            if !const_subclass {
978                passes::strip_enum_ctor_super(&mut body);
979            }
980        } else {
981            passes::fix_ctor_delegation_arg_defs(&mut body);
982            passes::fix_ctor_conditional_super(&mut body);
983            passes::fix_ctor_super_first(&mut body, &vt);
984            passes::dedupe_ctor_delegations(&mut body);
985            passes::strip_secondary_delegations(&mut body);
986            passes::hoist_branch_delegations(&mut body, &vt);
987            passes::extract_branched_delegation_helper(&mut body, &vt, pool, class, &desc.to_string());
988        }
989        // The delegation merges/hoists can leave prelude decls dead
990        // (their defs were inlined into the merged call) — the dropper
991        // ran BEFORE the ctor passes, so re-run it on their output.
992        passes::drop_dead_locals(&mut body);
993    }
994    if &*m.name == "<clinit>" {
995        passes::strip_clinit_returns(&mut body);
996    }
997    passes::strip_trailing_void_return(&mut body);
998    passes::cleanup(&mut body);
999    // Short-circuit folding last: the diamond shapes are final only
1000    // after cleanup merges singleton blocks.
1001    passes::invert_empty_thens(&mut body);
1002    passes::fold_short_circuits(&mut body);
1003    passes::resolve_dangling_gotos(&mut body);
1004    passes::dedupe_multicatch(&mut body, pool);
1005    passes::strip_phantom_field_writes(&mut body, pool);
1006    passes::init_bare_decls(&mut body, &vt);
1007
1008    if !errors.is_empty() {
1009        passes::prepend_comment(
1010            &mut body,
1011            format!("$DDC: {} block(s) failed to decompile", errors.len()),
1012        );
1013    }
1014
1015    phase_hit_n(2, n, t_fix);
1016    record_bucket(n, t0);
1017    Ok(Some(MethodBody { body, vt, desc }))
1018}
1019
1020static PHASE_MICROS: [std::sync::atomic::AtomicU64; 5] = [
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];
1027/// Phase × bucket attribution (5 phases × 5 buckets, row-major).
1028static PHASE_BUCKET_MICROS: [std::sync::atomic::AtomicU64; 25] = [
1029    std::sync::atomic::AtomicU64::new(0),
1030    std::sync::atomic::AtomicU64::new(0),
1031    std::sync::atomic::AtomicU64::new(0),
1032    std::sync::atomic::AtomicU64::new(0),
1033    std::sync::atomic::AtomicU64::new(0),
1034    std::sync::atomic::AtomicU64::new(0),
1035    std::sync::atomic::AtomicU64::new(0),
1036    std::sync::atomic::AtomicU64::new(0),
1037    std::sync::atomic::AtomicU64::new(0),
1038    std::sync::atomic::AtomicU64::new(0),
1039    std::sync::atomic::AtomicU64::new(0),
1040    std::sync::atomic::AtomicU64::new(0),
1041    std::sync::atomic::AtomicU64::new(0),
1042    std::sync::atomic::AtomicU64::new(0),
1043    std::sync::atomic::AtomicU64::new(0),
1044    std::sync::atomic::AtomicU64::new(0),
1045    std::sync::atomic::AtomicU64::new(0),
1046    std::sync::atomic::AtomicU64::new(0),
1047    std::sync::atomic::AtomicU64::new(0),
1048    std::sync::atomic::AtomicU64::new(0),
1049    std::sync::atomic::AtomicU64::new(0),
1050    std::sync::atomic::AtomicU64::new(0),
1051    std::sync::atomic::AtomicU64::new(0),
1052    std::sync::atomic::AtomicU64::new(0),
1053    std::sync::atomic::AtomicU64::new(0),
1054];
1055static PHASE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1056
1057fn bucket_of(n: usize) -> usize {
1058    if n <= 1 {
1059        0
1060    } else if n <= 5 {
1061        1
1062    } else if n <= 20 {
1063        2
1064    } else if n <= 100 {
1065        3
1066    } else {
1067        4
1068    }
1069}
1070
1071pub(crate) fn phase_hit_n(i: usize, n: usize, t: std::time::Instant) {
1072    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1073        return;
1074    }
1075    let us = t.elapsed().as_micros() as u64;
1076    PHASE_MICROS[i].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1077    PHASE_BUCKET_MICROS[i * 5 + bucket_of(n)].fetch_add(us, std::sync::atomic::Ordering::Relaxed);
1078}
1079
1080pub(crate) fn phase_hit(i: usize, t: std::time::Instant) {
1081    if !PHASE_ON.load(std::sync::atomic::Ordering::Relaxed) {
1082        return;
1083    }
1084    PHASE_MICROS[i].fetch_add(
1085        t.elapsed().as_micros() as u64,
1086        std::sync::atomic::Ordering::Relaxed,
1087    );
1088}
1089
1090/// Enable phase timers (DDC_PHASES=1).
1091pub fn phases_enable() {
1092    PHASE_ON.store(true, std::sync::atomic::Ordering::Relaxed);
1093}
1094
1095/// (fixpoint, structure+convert, passes, print, total) in micros.
1096pub fn phases_dump() -> [u64; 5] {
1097    let mut out = [0u64; 5];
1098    for i in 0..5 {
1099        out[i] = PHASE_MICROS[i].load(std::sync::atomic::Ordering::Relaxed);
1100    }
1101    out
1102}
1103
1104/// Per-bucket phase micros: 5 phases × 5 buckets, row-major.
1105pub fn phases_bucket_dump() -> [[u64; 5]; 5] {
1106    let mut out = [[0u64; 5]; 5];
1107    for i in 0..5 {
1108        for b in 0..5 {
1109            out[i][b] = PHASE_BUCKET_MICROS[i * 5 + b].load(std::sync::atomic::Ordering::Relaxed);
1110        }
1111    }
1112    out
1113}
1114
1115static CAP_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1116static CAP_INSNS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1117
1118static BUILD_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1119static INSN_LIFTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1120
1121static BUCKET_COUNT: [std::sync::atomic::AtomicU64; 5] = [
1122    std::sync::atomic::AtomicU64::new(0),
1123    std::sync::atomic::AtomicU64::new(0),
1124    std::sync::atomic::AtomicU64::new(0),
1125    std::sync::atomic::AtomicU64::new(0),
1126    std::sync::atomic::AtomicU64::new(0),
1127];
1128static BUCKET_MICROS: [std::sync::atomic::AtomicU64; 5] = [
1129    std::sync::atomic::AtomicU64::new(0),
1130    std::sync::atomic::AtomicU64::new(0),
1131    std::sync::atomic::AtomicU64::new(0),
1132    std::sync::atomic::AtomicU64::new(0),
1133    std::sync::atomic::AtomicU64::new(0),
1134];
1135
1136/// Dump build/insn counters.
1137pub fn dump_builds() -> (u64, u64) {
1138    (
1139        BUILD_COUNT.load(std::sync::atomic::Ordering::Relaxed),
1140        INSN_LIFTED.load(std::sync::atomic::Ordering::Relaxed),
1141    )
1142}
1143
1144/// (cap-hit methods, sum of insns*1000+blocks for cap-hit methods).
1145pub fn dump_caps() -> (u64, u64) {
1146    (
1147        CAP_HITS.load(std::sync::atomic::Ordering::Relaxed),
1148        CAP_INSNS.load(std::sync::atomic::Ordering::Relaxed),
1149    )
1150}
1151
1152/// Dump DDC_BUCKETS statistics (global atomics).
1153pub fn dump_buckets() -> [(u64, u64); 5] {
1154    let mut out = [(0u64, 0u64); 5];
1155    for i in 0..5 {
1156        out[i] = (
1157            BUCKET_COUNT[i].load(std::sync::atomic::Ordering::Relaxed),
1158            BUCKET_MICROS[i].load(std::sync::atomic::Ordering::Relaxed),
1159        );
1160    }
1161    out
1162}
1163
1164/// Dominator-recompute counters from jdc-core (perf diagnostics).
1165pub fn dom_counters() -> (u64, u64) {
1166    (
1167        jdc_core::structure::DOM_CALLS.load(std::sync::atomic::Ordering::Relaxed),
1168        jdc_core::structure::DOM_BLOCKS.load(std::sync::atomic::Ordering::Relaxed),
1169    )
1170}
1171
1172/// Enable dominator-recompute counters (diagnostics; jdc-core gate).
1173pub fn dom_counters_enable() {
1174    jdc_core::structure::set_dom_counters(true);
1175}
1176
1177/// A minimal body carrying a diagnostic comment.
1178fn stub_body(msg: String, desc: MethodDescriptor) -> MethodBody {
1179    MethodBody {
1180        body: Stmt::Block(vec![Stmt::Comment(msg)]),
1181        vt: VarTable::default(),
1182        desc,
1183    }
1184}
1185
1186/// True when any phi belongs to merge block `bid`.
1187fn phis_for_merge(bid: usize, phis: &HashMap<(usize, u16), u32>) -> bool {
1188    phis.keys().any(|(b, _)| *b == bid)
1189}
1190
1191/// Phi materialization records for `bid`'s predecessors (pred-tagged).
1192fn record_appends(
1193    cfg: &DexCfg,
1194    bid: usize,
1195    out_states: &[Option<OutState>],
1196    phis: &HashMap<(usize, u16), u32>,
1197    vt: &jdc_core::var::VarTable,
1198    out: &mut Vec<(usize, u32, u32, Expr)>,
1199) {
1200    for p in cfg.blocks[bid].pred.clone() {
1201        let Some(o) = &out_states[p] else { continue };
1202        for (r, st) in o.regs.iter().enumerate() {
1203            if let Some(&phi) = phis.get(&(bid, r as u16)) {
1204                let value = match st {
1205                    Reg::Live(v) if *v == phi => continue,
1206                    Reg::Live(v) => Expr::Local {
1207                        var: *v,
1208                        ty: vt.var(*v).ty.clone(),
1209                    },
1210                    Reg::Pending(e) | Reg::PendingCall(e) => e.clone(),
1211                    Reg::Undef | Reg::WideHi => continue,
1212                };
1213                out.push((p, o.write_pc.get(r).copied().unwrap_or(0), phi, value));
1214            }
1215        }
1216    }
1217}
1218
1219#[allow(unused)]
1220fn record_bucket(n: usize, t0: std::time::Instant) {
1221    // (Perf: env::var is a lock+lookup — per-METHOD cost on 716k-method
1222    // runs; resolve once via OnceLock.)
1223    static BUCKETS_ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1224    if !*BUCKETS_ON.get_or_init(|| std::env::var("DDC_BUCKETS").is_ok()) {
1225        return;
1226    }
1227    let bucket = if n <= 1 {
1228        0
1229    } else if n <= 5 {
1230        1
1231    } else if n <= 20 {
1232        2
1233    } else if n <= 100 {
1234        3
1235    } else {
1236        4
1237    };
1238    BUCKET_COUNT[bucket].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1239    BUCKET_MICROS[bucket].fetch_add(
1240        t0.elapsed().as_micros() as u64,
1241        std::sync::atomic::Ordering::Relaxed,
1242    );
1243}
1244
1245/// True when the expression references any of the phi vars.
1246fn visit_phi_refs(e: &Expr, phis: &std::collections::HashSet<u32>, hit: &mut bool) {
1247    if *hit {
1248        return;
1249    }
1250    if let Expr::Local { var, .. } = e {
1251        if phis.contains(var) {
1252            *hit = true;
1253        }
1254        return;
1255    }
1256    let mut kids: Vec<&Expr> = Vec::new();
1257    match e {
1258        Expr::Un { e, .. } | Expr::Cast { e, .. } | Expr::InstanceOf { e, .. } => kids.push(e),
1259        Expr::Bin { l, r, .. } => {
1260            kids.push(l);
1261            kids.push(r);
1262        }
1263        Expr::Cond { c, t, f } => {
1264            kids.push(c);
1265            kids.push(t);
1266            kids.push(f);
1267        }
1268        Expr::Assign { target, value, .. } => {
1269            kids.push(target);
1270            kids.push(value);
1271        }
1272        Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => kids.push(e),
1273        Expr::Field { owner: Some(o), .. } => kids.push(o),
1274        Expr::Method {
1275            owner: Some(o),
1276            args,
1277            ..
1278        } => {
1279            kids.push(o);
1280            kids.extend(args.iter());
1281        }
1282        Expr::ArrayIndex { array, index } => {
1283            kids.push(array);
1284            kids.push(index);
1285        }
1286        Expr::New { args, .. } => kids.extend(args.iter()),
1287        Expr::NewArray { dims, init, .. } => {
1288            kids.extend(dims.iter());
1289            if let Some(v) = init {
1290                kids.extend(v.iter());
1291            }
1292        }
1293        Expr::NewMultiArray { dims, .. } => kids.extend(dims.iter()),
1294        _ => {}
1295    }
1296    for k in kids {
1297        visit_phi_refs(k, phis, hit);
1298        if *hit {
1299            return;
1300        }
1301    }
1302}
1303
1304/// Merge several predecessor register states: pass identical values
1305/// through, otherwise materialize into a phi var for `(block, register)`.
1306/// Debug-info name covering `(pc, slot)`, sanitized (shared by the
1307/// lifter and the merge path).
1308fn debug_name_at(
1309    locals: &[ddc_dex::DebugLocal],
1310    slot: u16,
1311    pc: u32,
1312    ty: &jdc_core::types::JavaType,
1313) -> Option<String> {
1314    if locals.is_empty() {
1315        return None;
1316    }
1317    let hit = locals.iter().find(|l| {
1318        l.reg == slot
1319            && pc >= l.start
1320            && pc < l.end
1321            && l.ty.as_deref().map(|d| &crate::desc_type(d) == ty).unwrap_or(true)
1322    })?;
1323    let n = crate::classdec::java_ident(&hit.name);
1324    if n.is_empty() {
1325        None
1326    } else {
1327        Some(n.into_owned())
1328    }
1329}
1330
1331fn merge_states(
1332    vt: &mut VarTable,
1333    phis: &mut HashMap<(usize, u16), u32>,
1334    bid: usize,
1335    sides: &[&[Reg]],
1336    debug_locals: &[ddc_dex::DebugLocal],
1337    merge_pc: u32,
1338) -> Vec<Reg> {
1339    let len = sides.iter().map(|s| s.len()).max().unwrap_or(0);
1340    let mut out = vec![Reg::Undef; len];
1341    for (r, slot) in out.iter_mut().enumerate() {
1342        let mut all_eq = true;
1343        let mut first: Option<&Reg> = None;
1344        for s in sides {
1345            let v = s.get(r);
1346            match (first, v) {
1347                (None, v) => first = v,
1348                (Some(f), Some(v)) if f == v => {}
1349                _ => all_eq = false,
1350            }
1351        }
1352        if all_eq {
1353            *slot = first.cloned().unwrap_or(Reg::Undef);
1354            continue;
1355        }
1356        // Diverged: phi var.
1357        let key = (bid, r as u16);
1358        let phi = match phis.get(&key) {
1359            Some(&v) => v,
1360            None => {
1361                let ty = join_side_types(vt, sides, r);
1362                // Loop-carried values are usually THE source local (the
1363                // `char[] out` / `int i` of a loop): name the phi from the
1364                // debug range covering the merge block's head. When a var
1365                // of that name+type already exists, REUSE it — per-block
1366                // copies of one source local degrade to out/out2/out3
1367                // suffix soup, and one register+type = one Java local is
1368                // exactly Dalvik semantics.
1369                if let Some(n) = debug_name_at(debug_locals, r as u16, merge_pc, &ty.erased()) {
1370                    let unified = vt
1371                        .vars
1372                        .iter()
1373                        .find(|v| {
1374                            v.slot == r as u16
1375                                && !v.synthetic_name
1376                                && v.name == n
1377                                && v.ty.erased() == ty.erased()
1378                        })
1379                        .map(|v| v.id);
1380                    let id = match unified {
1381                        Some(id) => id,
1382                        None => {
1383                            let id = vt.vars.len() as u32;
1384                            vt.vars.push(jdc_core::var::VarInfo {
1385                                id,
1386                                slot: r as u16,
1387                                name: n,
1388                                ty,
1389                                is_param: false,
1390                                range_start: 0,
1391                                range_end: u16::MAX,
1392                                synthetic_name: false,
1393                            });
1394                            while vt.by_slot.len() <= r {
1395                                vt.by_slot.push(Vec::new());
1396                            }
1397                            vt.by_slot[r].push((0, u16::MAX, id));
1398                            id
1399                        }
1400                    };
1401                    phis.insert(key, id);
1402                    id
1403                } else {
1404                    let id = vt.vars.len() as u32;
1405                    vt.vars.push(jdc_core::var::VarInfo {
1406                        id,
1407                        slot: r as u16,
1408                        name: format!("v{}", id),
1409                        ty,
1410                        is_param: false,
1411                        range_start: 0,
1412                        range_end: u16::MAX,
1413                        synthetic_name: true,
1414                    });
1415                    while vt.by_slot.len() <= r {
1416                        vt.by_slot.push(Vec::new());
1417                    }
1418                    vt.by_slot[r].push((0, u16::MAX, id));
1419                    phis.insert(key, id);
1420                    id
1421                }
1422            }
1423        };
1424        *slot = Reg::Live(phi);
1425    }
1426    out
1427}
1428
1429/// Type of a phi var: join of the non-null side values' erased types.
1430fn join_side_types(vt: &VarTable, sides: &[&[Reg]], r: usize) -> TypeRef {
1431    let mut ty: Option<JavaType> = None;
1432    for s in sides {
1433        let st = s.get(r).cloned().unwrap_or(Reg::Undef);
1434        let e = match st {
1435            Reg::Pending(e) | Reg::PendingCall(e) => e,
1436            Reg::Live(v) => Expr::Local {
1437                var: v,
1438                ty: vt.var(v).ty.clone(),
1439            },
1440            _ => continue,
1441        };
1442        let t = e.type_ref().erased();
1443        ty = Some(match ty {
1444            None => t,
1445            Some(prev) => join_types(&prev, &t),
1446        });
1447    }
1448    TypeRef::J(ty.unwrap_or(JavaType::Int))
1449}
1450
1451fn join_types(a: &JavaType, b: &JavaType) -> JavaType {
1452    if a == b {
1453        return a.clone();
1454    }
1455    let num = |t: &JavaType| {
1456        matches!(
1457            t,
1458            JavaType::Boolean
1459                | JavaType::Byte
1460                | JavaType::Char
1461                | JavaType::Short
1462                | JavaType::Int
1463                | JavaType::Long
1464                | JavaType::Float
1465                | JavaType::Double
1466        )
1467    };
1468    if num(a) && num(b) {
1469        // Numeric promotion.
1470        return match (a, b) {
1471            (JavaType::Double, _) | (_, JavaType::Double) => JavaType::Double,
1472            (JavaType::Float, _) | (_, JavaType::Float) => JavaType::Float,
1473            (JavaType::Long, _) | (_, JavaType::Long) => JavaType::Long,
1474            _ => JavaType::Int,
1475        };
1476    }
1477    if let (JavaType::Object(x), JavaType::Object(y)) = (a, b) {
1478        if x == y {
1479            return a.clone();
1480        }
1481        // Char/int ternaries join to int; otherwise objects join to Object.
1482        return JavaType::Object("java/lang/Object".into());
1483    }
1484    JavaType::Object("java/lang/Object".into())
1485}
1486
1487/// True when the block's terminator exits (used by callers to skip appends).
1488#[allow(dead_code)]
1489fn is_exit_term(term: &jdc_core::ir::build::Term) -> bool {
1490    matches!(
1491        term,
1492        jdc_core::ir::build::Term::Return(_) | jdc_core::ir::build::Term::Throw(_)
1493    )
1494}
1495
1496#[allow(dead_code)]
1497fn unused(_: &InsnKind) {}