Skip to main content

jdc_core/
sese.rs

1//! From-scratch SESE / dominator-tree control-flow structurer.
2//!
3//! Replaces the heuristic `walk` with a monotone region decomposition:
4//! * follows are TRUE immediate post-dominators (computed once per method via a
5//!   sentinel-virtual-exit reverse CHK), fixing the compound-condition
6//!   `if (A || B) then; tail` mis-follow at the root;
7//! * every block is structured EXACTLY ONCE — guarded by a `consumed` set and a
8//!   "reached-from-this-region's-entry" check. A branch that runs into an
9//!   already-consumed block, or into a block it does not reach (a shared merge
10//!   owned by a sibling/follow), emits `Goto{block}` instead of re-walking it.
11//!   There is NO fresh-claimed shared-tail copy, so the decomposition cannot
12//!   diverge (the failure mode of every incremental patch on `walk`).
13//!
14//! Gated behind `JCDC_SESE`; `structure_method` falls back to `walk` when unset.
15//! Milestone 1: straight-line, Cond (if/else + value-diamond/ternary), natural
16//! loops. Switch/Try reuse the existing (pub(crate)) region builders next.
17
18use std::collections::{HashMap, HashSet};
19
20use crate::ir::build::Term;
21use crate::ir::expr::Expr;
22use crate::ir::stmt::Stmt;
23
24use crate::structure::{
25    compute_dominators, compute_postdominators, reachable_within, DomInfo, Region, Structurer,
26};
27
28// Per-method precomputation for the SESE decomposition.
29thread_local! {
30    /// Set when a matexit splice committed in the current method; read by
31    /// decompile_method's post-pipeline pathology retry.
32    pub static MATEXIT_FIRED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
33    /// Method-local kill switch for the retry pass.
34    pub static MATEXIT_DISABLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
35}
36
37struct SeseCtx {
38    universe: HashSet<usize>,
39    idom: DomInfo,
40    /// block -> immediate post-dominator (== vx when only the virtual exit).
41    ipdom: HashMap<usize, usize>,
42    /// sentinel virtual-exit id.
43    vx: usize,
44    /// loop headers (back-edge targets that dominate the source).
45    loop_headers: HashSet<usize>,
46    /// loop headers whose back edge is EXCEPTION-mediated (the retry jump
47    /// originates in handler flow, invisible to normal dominance at the
48    /// group-yield check).
49    exc_retry_headers: HashSet<usize>,
50    /// header -> natural-loop member set.
51    loop_members: HashMap<usize, HashSet<usize>>,
52    /// blocks consumed (structured exactly once) across the whole method.
53    consumed: HashSet<usize>,
54    /// loop headers currently being structured (a back-edge to one is a
55    /// `continue`, never a copy_walk target).
56    loop_stack: Vec<usize>,
57    /// Outermost try groups (mirrors walk's `top_groups`): the `active`
58    /// candidate list threaded into walk-based sub-builders so a try group
59    /// that STARTS inside a switch case or a copied tail still fires there
60    /// (URL$DefaultFactory.createURLStreamHandler: the reflection try lives
61    /// entirely inside the stage-2 switch default case; with active=[] the
62    /// case walk structured it bare and the catch was orphaned -> unreported
63    /// checked exceptions, a jdk11/17 corpus blocker).
64    top_groups: Vec<usize>,
65    /// recursion depth (safety bound).
66    depth: usize,
67}
68
69impl<'a> Structurer<'a> {
70    /// Structure the whole method via SESE decomposition.
71    /// Catch-and-retry header detection shared by both structurizers.
72    /// A catch-and-retry handler has NO normal-flow preds, so the
73    /// dominator tree roots it and its `goto header` back edge is
74    /// invisible to natural-loop detection. Returns the per-header
75    /// handler-flow back-edge sources and (as a side effect) marks the
76    /// headers in `loop_headers` and `self.sese_exc_retry_headers`.
77    /// The WALK structurer consumes sese_exc_retry_headers (its
78    /// loop-structuring branch + single_enclosing_succ) — in walk-only
79    /// mode it was never computed, so exc-mediated retry loops unrolled
80    /// into nested try copies (jdk11/17 ObjectInputStream.auditSubclass
81    /// lost the retry loop and its tail return — 缺少返回语句 x2 trees;
82    /// SESE rendered it correctly).
83    pub(crate) fn precompute_exc_retry(
84        &mut self,
85        universe: &HashSet<usize>,
86        idom: &crate::structure::DomInfo,
87        loop_headers: &mut HashSet<usize>,
88    ) -> HashMap<usize, Vec<usize>> {
89        let mut exc_back_sources: HashMap<usize, Vec<usize>> = HashMap::new();
90        let mut exc_retry_only: HashSet<usize> = HashSet::new();
91        for e in &self.cfg.exc_edges {
92            if !(universe.contains(&e.from) && universe.contains(&e.to)) {
93                continue;
94            }
95            let c = e.to;
96            if !self.cfg.blocks[c].pred.is_empty() {
97                continue; // normally reachable: real dominators apply
98            }
99            // Handler-flow closure: blocks whose normal preds all stay
100            // within the handler flow. The retry back edge may originate
101            // deeper than the handler entry (`catch { if (rem > 0)
102            // sleep(..); rem = ..; if (rem > 0) goto head; }` — jdk11
103            // Process.waitFor: the back edge sits at the while-test two
104            // hops down; the direct-succ scan missed it, the retry loop
105            // never structured, and the back-edge arrival copy_walked the
106            // try head into 5 nested duplicate tries with the final
107            // `return false` lost — 缺少返回语句). Blocks with a normal pred
108            // from OUTSIDE the handler flow (shared merges) stop the
109            // closure; they belong to the enclosing flow.
110            let mut hf: HashSet<usize> = HashSet::new();
111            hf.insert(c);
112            {
113                let mut q: std::collections::VecDeque<usize> = std::collections::VecDeque::new();
114                q.push_back(c);
115                while let Some(b) = q.pop_front() {
116                    for &s in &self.cfg.blocks[b].succ {
117                        if hf.contains(&s)
118                            || !universe.contains(&s)
119                            || self.handler_group.contains_key(&s)
120                        {
121                            continue;
122                        }
123                        if self.cfg.blocks[s]
124                            .pred
125                            .iter()
126                            .all(|p| hf.contains(p) || self.handler_group.contains_key(p))
127                        {
128                            hf.insert(s);
129                            q.push_back(s);
130                        }
131                    }
132                }
133            }
134            for &b in hf.iter() {
135                for &h in &self.cfg.blocks[b].succ {
136                    if hf.contains(&h) {
137                        continue;
138                    }
139                    if universe.contains(&h) && idom.dominates(h, e.from) {
140                        loop_headers.insert(h);
141                        exc_retry_only.insert(h);
142                        let srcs = exc_back_sources.entry(h).or_default();
143                        for &m in hf.iter() {
144                            if !srcs.contains(&m) {
145                                srcs.push(m);
146                            }
147                        }
148                    }
149                }
150            }
151        }
152        if crate::dbg_flag!("JCDC_DBG_IF") && !exc_retry_only.is_empty() {
153            let mut v: Vec<usize> = exc_retry_only.iter().copied().collect();
154            v.sort_unstable();
155            eprintln!("EXCRETRY headers={:?}", v);
156        }
157        self.sese_exc_retry_headers = exc_retry_only;
158        exc_back_sources
159    }
160
161    pub fn structure_method_sese(&mut self) -> Region {
162        let universe: HashSet<usize> = self
163            .cfg
164            .blocks
165            .iter()
166            .filter(|b| b.ins_len != 0)
167            .map(|b| b.id)
168            .collect();
169        let idom = compute_dominators(self.cfg, &universe, self.cfg.entry);
170        let (vx, ipdom) = compute_postdominators(self.cfg, &universe);
171
172        // Natural loops from back edges (h dominates u => u->h is a back edge).
173        let mut loop_headers: HashSet<usize> = HashSet::new();
174        for &u in universe.iter() {
175            for &s in &self.cfg.blocks[u].succ {
176                if universe.contains(&s) && s != u && idom.dominates(s, u) {
177                    loop_headers.insert(s);
178                }
179                if s == u {
180                    loop_headers.insert(u); // self loop
181                }
182            }
183        }
184        let exc_back_sources = self.precompute_exc_retry(&universe, &idom, &mut loop_headers);
185        // Exception-edge predecessors: handler -> protected blocks. A protected
186        // block reaches its handler only on a throw (an exception edge, not a
187        // normal pred), so when the handler loops back to the header, the
188        // protected block is part of the loop too. Without this, a
189        // `while(..){ try{ return }catch{ ..loop.. } }` drops the try out of
190        // the loop (the SecureRandom.getInstanceStrong regression).
191        let mut exc_preds: HashMap<usize, Vec<usize>> = HashMap::new();
192        for e in &self.cfg.exc_edges {
193            if universe.contains(&e.from) && universe.contains(&e.to) {
194                exc_preds.entry(e.to).or_default().push(e.from);
195            }
196        }
197        let mut loop_members: HashMap<usize, HashSet<usize>> = HashMap::new();
198        for &h in loop_headers.iter() {
199            let mut members: HashSet<usize> = HashSet::new();
200            members.insert(h);
201            // Collect every TRUE back-edge source for h (u -> h where h
202            // dominates u; without the dominance check a forward entry edge
203            // like a pre-loop init guard -> header pollutes the member set
204            // and the whole enclosing chain gets swallowed, Integer blk10),
205            // then walk predecessors (normal AND exception) within the
206            // universe until reaching h.
207            let mut stack: Vec<usize> = Vec::new();
208            for &u in universe.iter() {
209                let is_self_loop = u == h && self.cfg.blocks[h].succ.contains(&h);
210                let is_back_edge = u != h && idom.dominates(h, u);
211                if self.cfg.blocks[u].succ.contains(&h) && (is_self_loop || is_back_edge) {
212                    if members.insert(u) {
213                        stack.push(u);
214                    }
215                }
216            }
217            if let Some(srcs) = exc_back_sources.get(&h) {
218                for &c in srcs {
219                    if members.insert(c) {
220                        stack.push(c);
221                    }
222                }
223            }
224            while let Some(b) = stack.pop() {
225                // Do NOT traverse the header's own predecessors: the natural
226                // loop is {h} u {nodes reaching a back-edge source without
227                // going through h}. Walking h's preds would pull in the
228                // pre-loop code (entry, guards) and duplicate it inside the
229                // body region.
230                if b == h {
231                    continue;
232                }
233                for &p in &self.cfg.blocks[b].pred {
234                    if universe.contains(&p) && members.insert(p) {
235                        stack.push(p);
236                    }
237                }
238                if let Some(xp) = exc_preds.get(&b) {
239                    for &p in xp {
240                        if members.insert(p) {
241                            stack.push(p);
242                        }
243                    }
244                }
245            }
246            loop_members.insert(h, members);
247        }
248
249        let top_groups: Vec<usize> = (0..self.groups.len())
250            .filter(|gi| {
251                let g = &self.groups[*gi];
252                !self.groups.iter().enumerate().any(|(oj, og)| {
253                    oj != *gi
254                        && og.start <= g.start
255                        && og.end >= g.end
256                        && (og.start != g.start || og.end != g.end)
257                })
258            })
259            .collect();
260        self.sese_loop_headers = loop_headers.clone();
261        let mut ctx = SeseCtx {
262            universe,
263            idom,
264            ipdom,
265            vx,
266            exc_retry_headers: exc_back_sources.keys().copied().collect(),
267            loop_headers,
268            loop_members,
269            consumed: HashSet::new(),
270            loop_stack: Vec::new(),
271            top_groups,
272            depth: 0,
273        };
274        let r = self.sese_region(self.cfg.entry, &HashSet::new(), &mut ctx);
275        r
276    }
277
278    /// Immediate post-dominator of `b` (None if only the virtual exit, i.e. all
279    /// paths from b leave the universe / return / throw).
280    fn sese_ipdom(&self, ctx: &SeseCtx, b: usize) -> Option<usize> {
281        match ctx.ipdom.get(&b).copied() {
282            Some(p) if p != ctx.vx && p != b => Some(p),
283            _ => None,
284        }
285    }
286
287    /// Convergent merge of a set of branch/case targets within a region: the
288    /// nearest block (by linear layout) forward-reachable from ALL targets,
289    /// not in `stop`, and not yet consumed. This recovers a shared
290    /// continuation that is NOT a post-dominator because the targets diverge
291    /// to different terminals (a loop `break` -> exit, a `return`/`throw`, or
292    /// a loop tail -> header back-edge that only post-dominates at the virtual
293    /// exit). Examples: the loop tail after `if (a==2 && b==2) break outer;`
294    /// (Legacy6), and the shared `++i` tail after every `case` of a switch
295    /// inside a loop (EnumSwitch — without it the first case swallows the tail
296    /// as `++i; continue` and the remaining cases spin forever).
297    fn convergent_merge(
298        &self,
299        ctx: &SeseCtx,
300        targets: &[usize],
301        stop: &HashSet<usize>,
302    ) -> Option<usize> {
303        if targets.is_empty() {
304            return None;
305        }
306        // Floor = the branch block's own position, NOT max(target starts): a
307        // branch target may sit EARLIER in the layout than the branch (a
308        // backward jump to a fixup, Integer.toString C1 -> FIXUP), and a
309        // max-of-targets floor then hides the true nearest confluence and
310        // lets a far block inside the branch body be chosen as follow.
311        let floor = targets
312            .iter()
313            .filter_map(|&t| {
314                self.cfg.blocks[t]
315                    .pred
316                    .iter()
317                    .map(|&p| self.cfg.blocks[p].start as usize)
318                    .max()
319            })
320            .max()
321            .unwrap_or(0);
322        // Multi-block condition chains (`while (c1 || c2) body;` compiled as
323        // H1: if c1 goto BODY; H2: if c2 goto BODY; else EXIT; BODY: ..; goto
324        // H1): the confluence of H1's branches is the NEXT TEST block, which
325        // is itself one of the targets. Prefer it before the general scan —
326        // the dominance guards below would (correctly in general) reject it,
327        // but here the sibling target IS the chain continuation; picking it
328        // flattens the body to `if (c1) continue; if (c2) continue; else
329        // exit;`, the shape extract_compound_do_while / the CLASSIFY2 fold
330        // consume (jdk8 Random.internalNextInt). Legacy6 is unaffected: its
331        // fall target (the tail) is reachable from the sibling, so the
332        // sibling is not a confluence there.
333        for &t in targets.iter() {
334            if stop.contains(&t) || ctx.consumed.contains(&t) || ctx.loop_stack.contains(&t) {
335                if crate::dbg_flag!("JCDC_DBG_LM") {
336                    eprintln!(
337                        "CM-SKIP t={} stop={} consumed={} lstack={} targets={:?}",
338                        t,
339                        stop.contains(&t),
340                        ctx.consumed.contains(&t),
341                        ctx.loop_stack.contains(&t),
342                        targets
343                    );
344                }
345                continue;
346            }
347            if targets
348                .iter()
349                .all(|&o| o == t || self.reaches_within(ctx, o, t, stop))
350            {
351                if crate::dbg_flag!("JCDC_DBG_LM") {
352                    eprintln!("CM-RET {} targets={:?}", t, targets);
353                }
354                return Some(t);
355            }
356        }
357        let mut best: Option<usize> = None;
358        let mut best_start = usize::MAX;
359        for &x in ctx.universe.iter() {
360            let xs = self.cfg.blocks[x].start as usize;
361            if xs < floor || xs >= best_start {
362                continue;
363            }
364            if stop.contains(&x) || ctx.consumed.contains(&x) {
365                continue;
366            }
367            // A loop header is never a merge candidate WHILE INSIDE its
368            // loop: a branch that jumps to it is a `continue` (the back
369            // edge fires on the NEXT iteration), not a fall-through
370            // confluence. During a body walk the header sits on the
371            // loop_stack, so this guard keeps StringUTF16.codePointCount's
372            // `continue`s. OUTSIDE the loop (switch cases that all
373            // `goto` a loop head laid out after the switch — jdk11
374            // Subject.populateSet) the header IS the switch follow: the
375            // cases break into it and the loop structures ONCE after the
376            // switch instead of being copy-duplicated into every case.
377            if ctx.loop_stack.contains(&x) {
378                continue;
379            }
380            // A candidate that DOMINATES ANY branch target (reflexively: is
381            // a target) is an ancestor
382            // confluence (a fixup block the branches jump back/up to, e.g.
383            // `if (A || B) radix = 10;` where the fixup dominates the cond),
384            // not a follow: choosing it empties a branch and loses the
385            // post-fixup continuation (Integer.toString). Such shapes need
386            // follow=None so the branches are walked naturally and the
387            // re-reached continuation is duplicated by copy_walk (walk
388            // parity). Genuine shared tails (Legacy6/EnumSwitch) are
389            // dominated BY their targets, never dominate them.
390            if targets.iter().any(|&t| t != x && ctx.idom.dominates(x, t)) {
391                continue;
392            }
393            // ... and reject a candidate that IS a branch target while
394            // ANOTHER target sits strictly above it in the dominator tree
395            // (`if (A || B) fixup; main;` — fixup dominates main): choosing
396            // the lower target as follow empties the jump branch and orphans
397            // the fixup (Integer.toString C2 -> empty `if (radix <= 36)`).
398            // A genuine shared tail (Legacy6) is dominated BY its sibling
399            // branch, not the other way around, so it survives both guards.
400            if targets.contains(&x) && targets.iter().any(|&t| t != x && ctx.idom.dominates(t, x)) {
401                continue;
402            }
403            if targets
404                .iter()
405                .all(|&t| self.reaches_within(ctx, t, x, stop))
406            {
407                best = Some(x);
408                best_start = xs;
409            }
410        }
411        best
412    }
413
414    /// Can `from` reach `target` stepping only through blocks not in `stop`
415    /// (target itself may be in `stop` — it is the destination), AND without
416    /// re-entering an enclosing loop? Reaching a loop header on `loop_stack`
417    /// is a back-edge (loop re-entry): anything past it is a *later iteration*,
418    /// not a forward merge. Restricting to forward reach is what lets
419    /// convergent_merge recover a shared loop tail (Legacy6: B2 -> TAIL is a
420    /// forward edge) while refusing to invent a follow across a `continue`
421    /// (ControlFlow.nestedLoops: the `++j;continue` block only reaches `++c`
422    /// via the header back-edge, so `++c` is correctly NOT a merge).
423    /// Nearest block (by start) that every NON-TERMINATING successor
424    /// reaches within `stop` — unlike convergent_merge this MAY return a
425    /// stop member: a switch/if inside a loop body whose branches break
426    /// to the loop increment (a body_stop exit) still has a well-defined
427    /// merge; refusing it strands breaks as RawGotos and drops shared
428    /// tails (ObjectStreamClass.computeFieldOffsets, Long$LongCache
429    /// clinit). Cm's dominance guards still apply: a candidate that
430    /// (properly) dominates a live target is an ancestor confluence
431    /// (Integer.toString fixup), not a follow.
432    fn live_merge(&self, ctx: &SeseCtx, succs: &[usize], stop: &HashSet<usize>) -> Option<usize> {
433        let live: Vec<usize> = succs
434            .iter()
435            .copied()
436            .filter(|&t| !matches!(self.results[t].term, Term::Return(_) | Term::Throw(_)))
437            .collect();
438        // Require 2+ live branches: a single live target trivially
439        // "merges with itself" — for a loop condition that makes the
440        // body entry the follow, emptying the else branch and degrading
441        // ControlFlow.breakInLoop's `return i` to `break`. One-live
442        // shapes must keep follow=None so branches structure naturally.
443        if live.len() < 2 {
444            return None;
445        }
446        // A branch target that every live branch flows to IS the merge
447        // (the sibling completes normally into it and the branch is an
448        // empty fallthrough) — prefer it even when it is a shared
449        // terminator; scanning by nearest-start would otherwise pick a
450        // non-target confluence and strand the tail (Fin/Long$LongCache:
451        // `cache = archivedCache; return` must be the follow, not a
452        // branch-body copy with the top-level tail lost). ONLY with 2+
453        // live targets: a loop condition (one live body entry, one exit
454        // branch) must keep follow=None so both branches structure
455        // naturally — otherwise the body entry becomes the "follow", the
456        // else branch empties, and ControlFlow.breakInLoop's `return i`
457        // degrades to `break`.
458        if live.len() >= 2 {
459            for &t in succs.iter() {
460                if stop.contains(&t) {
461                    if crate::dbg_flag!("JCDC_DBG_LM") {
462                        eprintln!("LM-SKIP t={} stop succs={:?}", t, succs);
463                    }
464                    continue;
465                }
466                if ctx.consumed.contains(&t) {
467                    if crate::dbg_flag!("JCDC_DBG_LM") {
468                        eprintln!("LM-SKIP t={} consumed succs={:?}", t, succs);
469                    }
470                    continue;
471                }
472                if live
473                    .iter()
474                    .all(|&o| o == t || self.reaches_within(ctx, o, t, stop))
475                {
476                    if crate::dbg_flag!("JCDC_DBG_LM") {
477                        eprintln!("LM-RET {} succs={:?} live={:?}", t, succs, live);
478                    }
479                    return Some(t);
480                }
481            }
482        }
483        let mut best: Option<usize> = None;
484        for &cand in ctx.universe.iter() {
485            if ctx.consumed.contains(&cand) || ctx.loop_stack.contains(&cand) {
486                continue;
487            }
488            // (Shared terminators ARE eligible here: a branch merging at
489            // a return block is a normal follow — Long$LongCache's tail.
490            // The escape filter downstream in the follow chain rejects
491            // the cases where a branch jumps OUT instead, jdk17 String.)
492            if live
493                .iter()
494                .any(|&t| t != cand && ctx.idom.dominates(cand, t))
495            {
496                continue;
497            }
498            if live.contains(&cand)
499                && live
500                    .iter()
501                    .any(|&t| t != cand && ctx.idom.dominates(t, cand))
502            {
503                continue;
504            }
505            if live
506                .iter()
507                .all(|&t| t == cand || self.reaches_within(ctx, t, cand, stop))
508            {
509                match best {
510                    None => best = Some(cand),
511                    Some(b) if self.cfg.blocks[cand].start < self.cfg.blocks[b].start => {
512                        best = Some(cand)
513                    }
514                    _ => {}
515                }
516            }
517        }
518        best
519    }
520
521    /// True when `cur` (a stop member) flows through single-successor
522    /// blocks to an already-consumed terminator: the chain is safe to
523    /// copy here because its endpoint was structured elsewhere and the
524    /// copy is this path's sole continuation.
525    fn sese_stop_chain_to_claimed_terminator(
526        &self,
527        cur: usize,
528        stop: &HashSet<usize>,
529        ctx: &SeseCtx,
530    ) -> bool {
531        let mut x = cur;
532        for _ in 0..8 {
533            if matches!(self.results[x].term, Term::Return(_) | Term::Throw(_)) {
534                // Statement-bearing claimed terminators are the post-loop
535                // continuation tail (shared clinit tails get claimed by the
536                // first arrival), NOT absorbed restart-loop scaffolding —
537                // copying them into the exit test duplicates blank-final
538                // assignments inside the loop (SecurityProviderConstants
539                // 可能在 loop 中分配了变量 x18). See the walk-side twin.
540                return ctx.consumed.contains(&x) && self.results[x].stmts.is_empty();
541            }
542            if !matches!(self.results[x].term, Term::Fallthrough | Term::Goto) {
543                return false;
544            }
545            if !self.results[x].stmts.is_empty() && !ctx.consumed.contains(&x) {
546                return false;
547            }
548            let succs = &self.cfg.blocks[x].succ;
549            if succs.len() != 1 {
550                return false;
551            }
552            let n = succs[0];
553            if n == x || ctx.loop_stack.contains(&n) {
554                return false;
555            }
556            let _ = stop;
557            x = n;
558        }
559        false
560    }
561
562    /// Loop-tail switch follow recovery. A switch inside a loop whose cases
563    /// either `break` the SWITCH into a shared epilogue that flows back to
564    /// the header, exit the LOOP (stop), `continue` (header), or terminate:
565    /// ipdom post-dominates only at the virtual exit and the forward-merge
566    /// resolvers refuse header-reaching paths, so follow=None — the epilogue
567    /// is consumed by the first case walk that arrives, sibling cases lose
568    /// their `break`, and the post-loop continuation is stranded (jdk26
569    /// Pattern.sequence/expr: lost `node = closure(node)` epilogue and
570    /// post-loop `if (head == null) return end; root = tail; return head;`
571    /// → 缺少返回语句). E is the nearest block every case target SETTLES at:
572    /// each path from each target reaches E forward (no stop/header steps),
573    /// escapes to a stop (outer break), continues into an enclosing loop
574    /// header, or terminates (return/throw).
575    fn loop_tail_switch_follow(
576        &self,
577        ctx: &SeseCtx,
578        cur: usize,
579        stop: &HashSet<usize>,
580    ) -> Option<usize> {
581        if ctx.loop_stack.is_empty() {
582            return None;
583        }
584        let targets: Vec<usize> = self.cfg.blocks[cur].succ.clone();
585        if targets.is_empty() {
586            return None;
587        }
588        // Candidates: the DESTINATIONS of case-terminal transfers only —
589        // each case region's trailing `goto X` targets and fallthrough
590        // successors whose source block has multiple in-region succ paths
591        // (a full forward closure would offer every case-internal block,
592        // and a private `continue` stub settling on all paths could win
593        // the start-pc contest: Pattern.sequence case 40's `goto 4` block).
594        let mut cands: Vec<usize> = Vec::new();
595        {
596            let mut seen: HashSet<usize> = HashSet::new();
597            let mut stack: Vec<usize> = targets.clone();
598            let mut visited: HashSet<usize> = HashSet::new();
599            while let Some(b) = stack.pop() {
600                if stop.contains(&b) || ctx.loop_stack.contains(&b) || !visited.insert(b) {
601                    continue;
602                }
603                let succs = &self.cfg.blocks[b].succ;
604                match self.results[b].term {
605                    crate::ir::build::Term::Goto => {
606                        // A case-terminal jump: its destination is a
607                        // break/continue/epilogue candidate.
608                        if let Some(&t) = succs.first() {
609                            if !targets.contains(&t)
610                                && !ctx.loop_stack.contains(&t)
611                                && !stop.contains(&t)
612                                && seen.insert(t)
613                            {
614                                cands.push(t);
615                            }
616                        }
617                    }
618                    crate::ir::build::Term::Fallthrough => {
619                        if let Some(&t) = succs.first() {
620                            // Fallthrough into a block with preds from
621                            // ELSEWHERE in the switch (a shared epilogue
622                            // head): candidate. Purely linear flow keeps
623                            // walking (the case's own body).
624                            let shared = self.cfg.blocks[t]
625                                .pred
626                                .iter()
627                                .any(|&p| p != b && (targets.contains(&p) || visited.contains(&p)));
628                            if shared
629                                && !targets.contains(&t)
630                                && !ctx.loop_stack.contains(&t)
631                                && !stop.contains(&t)
632                                && seen.insert(t)
633                            {
634                                cands.push(t);
635                            }
636                            stack.push(t);
637                        }
638                    }
639                    crate::ir::build::Term::Cond { .. } | crate::ir::build::Term::Switch { .. } => {
640                        stack.extend(succs.iter().copied());
641                    }
642                    // A case body can END in straight-line fallthrough into
643                    // the shared epilogue (Pattern.sequence case 92 flows
644                    // into the `node = closure(node)` tail): keep walking
645                    // non-branching blocks so its destination surfaces.
646                    _ if succs.len() == 1
647                        && !matches!(
648                            self.results[b].term,
649                            crate::ir::build::Term::Return(_) | crate::ir::build::Term::Throw(_)
650                        ) =>
651                    {
652                        stack.extend(succs.iter().copied());
653                    }
654                    // Return/Throw: no continuation candidate.
655                    _ => {}
656                }
657            }
658        }
659        let mut best: Option<usize> = None;
660        let mut best_score: Option<(usize, u32)> = None;
661        for &e in &cands {
662            if stop.contains(&e) || ctx.consumed.contains(&e) {
663                continue;
664            }
665            // E must flow back to an enclosing loop header (it IS the loop
666            // tail) — otherwise the switch-break confluence is a plain
667            // post-switch block the forward resolvers would have found.
668            let mut to_header = false;
669            {
670                let mut seen: HashSet<usize> = HashSet::new();
671                let mut stack: Vec<usize> = vec![e];
672                while let Some(b) = stack.pop() {
673                    if !seen.insert(b) {
674                        continue;
675                    }
676                    for &s in &self.cfg.blocks[b].succ {
677                        if ctx.loop_stack.contains(&s) {
678                            to_header = true;
679                            break;
680                        }
681                        if !stop.contains(&s) {
682                            stack.push(s);
683                        }
684                    }
685                    if to_header {
686                        break;
687                    }
688                }
689            }
690            if !to_header {
691                continue;
692            }
693            if targets.iter().all(|&t| self.settles_at(ctx, stop, t, e, 0)) {
694                // Score = how many DISTINCT case targets reach `e` forward:
695                // the switch-break confluence collects every breaking case,
696                // while a case-private merge/continue stub is reached only
697                // by its own case (Pattern.sequence b7 [case 40's
698                // `tail = root; goto EPI`] vs the true epilogue EPI which
699                // all eight breaking cases flow into). Ties: nearest by
700                // start pc (the epilogue's own head block).
701                let score = targets
702                    .iter()
703                    .filter(|&&t| self.reaches_fwd(ctx, stop, t, e, 0))
704                    .count();
705                best = match best_score {
706                    None => {
707                        best_score = Some((score, self.cfg.blocks[e].start));
708                        Some(e)
709                    }
710                    Some((bs, bstart)) => {
711                        let better =
712                            score > bs || (score == bs && self.cfg.blocks[e].start < bstart);
713                        if better {
714                            best_score = Some((score, self.cfg.blocks[e].start));
715                            Some(e)
716                        } else {
717                            best
718                        }
719                    }
720                };
721            }
722        }
723        best
724    }
725
726    /// Some forward path from `t` reaches `e` without stepping on stop
727    /// members or enclosing loop headers.
728    fn reaches_fwd(
729        &self,
730        ctx: &SeseCtx,
731        stop: &HashSet<usize>,
732        t: usize,
733        e: usize,
734        depth: usize,
735    ) -> bool {
736        if depth > 4096 {
737            return false;
738        }
739        if t == e {
740            return true;
741        }
742        if stop.contains(&t) || ctx.loop_stack.contains(&t) {
743            return false;
744        }
745        self.cfg.blocks[t]
746            .succ
747            .iter()
748            .any(|&s| self.reaches_fwd(ctx, stop, s, e, depth + 1))
749    }
750
751    /// Every path from `t` settles at `e`: reaches it forward, escapes to a
752    /// stop (outer break), continues into an enclosing loop header, or
753    /// terminates (return/throw). See `loop_tail_switch_follow`.
754    fn settles_at(
755        &self,
756        ctx: &SeseCtx,
757        stop: &HashSet<usize>,
758        t: usize,
759        e: usize,
760        depth: usize,
761    ) -> bool {
762        if depth > 4096 {
763            return false;
764        }
765        if t == e {
766            return true;
767        }
768        if stop.contains(&t) || ctx.loop_stack.contains(&t) {
769            return true; // outer break / continue: structured elsewhere
770        }
771        let succs = &self.cfg.blocks[t].succ;
772        if succs.is_empty() {
773            return matches!(
774                self.results[t].term,
775                crate::ir::build::Term::Return(_) | crate::ir::build::Term::Throw(_)
776            );
777        }
778        succs
779            .iter()
780            .all(|&s| self.settles_at(ctx, stop, s, e, depth + 1))
781    }
782
783    /// Stronger sibling check for a branch-target follow candidate: EVERY
784    /// bounded route from `from` passes through `target` or leaves abruptly
785    /// (return/throw/stop-jump/loop re-entry). Used ONLY as the trigger
786    /// for the false-merge reconciliation below (never as a standalone
787    /// follow filter — the documented-failed variants 1-7 in memory
788    /// ocsp-sese-follow-diagnosis rejected follows outright and traded
789    /// OCSPResponse against BasicImageReader/keytool/Locale/Throwable/
790    /// ConcurrentHashMap families): a sibling route that completes
791    /// normally PAST the parked target's emission point is the crossing
792    /// that makes the empty-arm contract unsound.
793    fn all_routes_via(
794        &self,
795        ctx: &SeseCtx,
796        from: usize,
797        target: usize,
798        stop: &HashSet<usize>,
799    ) -> bool {
800        if from == target {
801            return true;
802        }
803        let mut post = crate::structure::reachable_within(self.cfg, target, stop);
804        post.remove(&target);
805        let mut seen: HashSet<usize> = HashSet::new();
806        let mut stack: Vec<usize> = vec![from];
807        let mut budget = 4096usize;
808        while let Some(c) = stack.pop() {
809            if c == target || seen.contains(&c) {
810                continue;
811            }
812            if budget == 0 {
813                return false;
814            }
815            budget -= 1;
816            seen.insert(c);
817            if post.contains(&c) {
818                return false; // bypass into the post-target flow
819            }
820            if stop.contains(&c) || ctx.loop_stack.contains(&c) {
821                continue; // abrupt escape: jump/continue, never falls through
822            }
823            if matches!(
824                self.results[c].term,
825                crate::ir::build::Term::Return(_) | crate::ir::build::Term::Throw(_)
826            ) {
827                continue;
828            }
829            let succs: Vec<usize> = self.cfg.blocks[c]
830                .succ
831                .iter()
832                .copied()
833                .filter(|&sx| ctx.universe.contains(&sx))
834                .collect();
835            if succs.is_empty() {
836                continue; // leaves the region: abrupt from this If's view
837            }
838            for sx in succs {
839                if ctx.loop_headers.contains(&sx) && !seen.contains(&sx) {
840                    // Re-entry into a loop header is a back-edge jump
841                    // (continue), not a fallthrough — abrupt.
842                    if self.cfg.blocks[c].succ.iter().any(|&o| o == sx) && sx != target {
843                        if self.cfg.blocks[sx].start <= self.cfg.blocks[c].start {
844                            continue;
845                        }
846                    }
847                }
848                stack.push(sx);
849            }
850        }
851        true
852    }
853
854    fn reaches_within(
855        &self,
856        ctx: &SeseCtx,
857        from: usize,
858        target: usize,
859        stop: &HashSet<usize>,
860    ) -> bool {
861        if from == target {
862            return true;
863        }
864        // A branch that jumps straight to a stop block LEAVES the region
865        // (sibling/follow owns it); it contributes no in-region confluence.
866        // Without this, Integer's C2 (`radix <= 36`) "reaches" the subtree
867        // through the fixup stop in one hop and cm picks the subtree head as
868        // follow, emptying the branch and losing the fixup+copy shape.
869        if stop.contains(&from) {
870            return false;
871        }
872        let mut seen = HashSet::new();
873        let mut stack = vec![from];
874        seen.insert(from);
875        while let Some(c) = stack.pop() {
876            for &s in &self.cfg.blocks[c].succ {
877                if s == target {
878                    return true;
879                }
880                // Not expandable: stop blocks (region boundaries — a sibling
881                // branch owns them; routing through one is not a confluence of
882                // THIS branch set: Integer C2 whose fixup target is the C1
883                // follow must not "reach" the subtree through it) and loop
884                // headers (re-entering a loop body is a later iteration, not a
885                // forward merge: ControlFlow.nestedLoops).
886                if stop.contains(&s) || ctx.loop_stack.contains(&s) || ctx.loop_headers.contains(&s)
887                {
888                    continue;
889                }
890                if seen.insert(s) {
891                    stack.push(s);
892                }
893            }
894        }
895        false
896    }
897
898    /// Structure the region starting at `entry`, stopping at any block in
899    /// `stop` (region exits / follows / enclosing barriers) or at the first
900    /// block not reached-from-`entry`-without-stop (a shared merge owned by a
901    /// sibling or the follow). Each block is consumed exactly once.
902    fn sese_region(&mut self, entry: usize, stop: &HashSet<usize>, ctx: &mut SeseCtx) -> Region {
903        let reach = reachable_within(self.cfg, entry, stop);
904        self.sese_region_with_scope(entry, stop, reach, ctx)
905    }
906
907    /// Region walk with an explicit scope (`reach`). Normally the scope is
908    /// reachable_within(entry, stop); loop bodies pass the same set computed
909    /// once at the loop site so nested walks/copies share one bound.
910    /// Loop-level materialization of statement-bearing exits (jdk17
911    /// AQS.cleanQueue's dropped CAS-unlink phase). Runs AFTER the loop
912    /// body region is fully built, so the body's claims/consumed history
913    /// is untouched — the arm-site copy experiment perturbed sibling
914    /// structuring mid-walk (cancelAcquire regressed, cleanQueue's
915    /// advance path was swallowed) and was reverted; this pass is pure
916    /// region-tree post-processing. Each exit E carrying statement/branch
917    /// CONTENT (exit_has_content; stub-chain exits like Pattern.clazz's
918    /// switch-case goto stubs are exempt and keep their bare breaks) gets
919    /// its cascade structured ONCE on a clean barriered scope (all exits
920    /// + loop members + enclosing headers), then every `Goto{E}` in the
921    /// body becomes `Seq[cascade-copy, Goto{E}]`: the break keeps its
922    /// conversion binding while the cascade runs before it — the golden
923    /// shape (CAS unlink executes, then break restarts the outer loop).
924    /// Cascades whose flow ends at another exit or an enclosing back edge
925    /// render that jump as the matching break/continue (conversion
926    /// resolves against the enclosing loop stack; a cascade reaching an
927    /// UNENCLOSED header falls back to the bare break).
928    pub(crate) fn materialize_content_exits(
929        &mut self,
930        body: &mut Region,
931        header: usize,
932        exits: &[usize],
933        members: &HashSet<usize>,
934        natural: &HashSet<usize>,
935        ctx_universe: &HashSet<usize>,
936        ctx_loop_stack: &[usize],
937        ctx_loop_headers: &HashSet<usize>,
938        ctx_top_groups: &[usize],
939        outer_stop: &HashSet<usize>,
940        reach: &HashSet<usize>,
941        consumed: &HashSet<usize>,
942        natural_follow_empty: bool,
943    ) {
944        if MATEXIT_DISABLED.with(|d| d.get()) {
945            return;
946        }
947        let mut barriers: HashSet<usize> = exits.iter().copied().collect();
948        barriers.extend(members.iter().copied());
949        barriers.extend(ctx_loop_stack.iter().copied());
950        barriers.extend(ctx_loop_headers.iter().copied());
951        // PARENT-CONTINUATION fold: replicate the post-loop follow_pick's
952        // minimal candidate (lowest-start unconsumed in-reach exit) — when
953        // natural_follow is empty the parent continues at THAT exit and
954        // renders its flow once; materializing it double-renders the
955        // territory (ois readSerialData e=45: the cleanup-continuation
956        // copy re-bound catch identities downstream, markException(null)).
957        let mut natural: HashSet<usize> = natural.iter().copied().collect();
958        if natural_follow_empty {
959            // Full follow_pick replication (incl. the continue-stub
960            // filter): the parent's post-loop continuation is exactly
961            // this block, parent-rendered once — never materialize it.
962            let claim_cands: HashSet<usize> = exits
963                .iter()
964                .copied()
965                .filter(|e| {
966                    !consumed.contains(e)
967                        && !outer_stop.contains(e)
968                        && ctx_universe.contains(e)
969                        && reach.contains(e)
970                        && !self.is_handler(*e)
971                        && *e != header
972                })
973                .collect();
974            let mut cands: Vec<usize> = exits
975                .iter()
976                .copied()
977                .filter(|e| {
978                    !consumed.contains(e)
979                        && !outer_stop.contains(e)
980                        && ctx_universe.contains(e)
981                        && reach.contains(e)
982                        && !self.is_handler(*e)
983                        && *e != header
984                        && !ctx_loop_stack.iter().any(|h| {
985                            h != e
986                                && self.is_stmt_free_chain_to_block(*e, *h)
987                                && !self.stub_chain_claims_continuation(*e, *h, &claim_cands)
988                        })
989                })
990                .collect();
991            cands.sort_by_key(|x| self.cfg.blocks[*x].start);
992            if let Some(f) = cands.first() {
993                natural.insert(*f);
994            }
995        }
996        let natural = &natural;
997        if crate::dbg_flag!("JCDC_DBG_SESE") {
998            let mut nv: Vec<usize> = natural.iter().copied().collect();
999            nv.sort_unstable();
1000            eprintln!("MXNAT header={} exits={:?} natural={:?}", header, exits, nv);
1001        }
1002        // Baseline conversion of the un-spliced body: the trial
1003        // pathology scan compares against it (a splice that introduces a
1004        // NEW Stmt::Labeled changed classify_loop's rotation — the
1005        // ObjectInputStream readSerialData corruption route: the L2
1006        // re-rotation moved catch blocks across LVT ranges and varalloc
1007        // rebound the catch identity, markException(ex=null)).
1008        let base_labeled = {
1009            let mut conv = crate::convert::Converter::new(self.cfg, self.results)
1010                .with_copied_tails(self.copied_tails.clone())
1011                .with_final_fields(self.final_fields.clone());
1012            let base_stmt = conv.convert(body.clone());
1013            Self::count_labeled(&base_stmt)
1014        };
1015        let skip_e: Option<usize> = crate::dbg_value!("JCDC_MATEXIT_SKIP", usize);
1016        for &e in exits {
1017            if Some(e) == skip_e {
1018                continue;
1019            }
1020            if members.contains(&e)
1021                || natural.contains(&e)
1022                || ctx_loop_stack.contains(&e)
1023                || ctx_loop_headers.contains(&e)
1024                || self.is_terminator_block(e)
1025                || !self.exit_has_content(e, &barriers)
1026            {
1027                continue;
1028            }
1029            let mut cstop = barriers.clone();
1030            cstop.remove(&e);
1031            cstop.extend(natural.iter().copied());
1032            // The NATURAL CONTINUATION'S forward closure is parent-
1033            // rendered territory: a cascade may not swallow it (ois
1034            // readSerialData e=45's tu dragged in the post-loop blocks
1035            // 50-57 — double-rendered flow re-bound catch identities
1036            // downstream, markException(ex=null)). Barriers for the
1037            // closure: exits, enclosing headers, members — the closure
1038            // must not wrap around the loop.
1039            {
1040                let mut cl_bar: HashSet<usize> = exits.iter().copied().collect();
1041                cl_bar.extend(members.iter().copied());
1042                cl_bar.extend(ctx_loop_stack.iter().copied());
1043                cl_bar.extend(ctx_loop_headers.iter().copied());
1044                let mut cl: HashSet<usize> = HashSet::new();
1045                let mut cq: Vec<usize> = natural.iter().copied().collect();
1046                while let Some(b) = cq.pop() {
1047                    if !cl.insert(b) {
1048                        continue;
1049                    }
1050                    for &n2 in &self.cfg.blocks[b].succ {
1051                        if !cl_bar.contains(&n2) {
1052                            cq.push(n2);
1053                        }
1054                    }
1055                }
1056                cstop.extend(cl.iter().copied());
1057                cstop.remove(&e);
1058            }
1059            // ORPHANED exits only: E must NOT be forward-reachable from
1060            // any natural exit's flow. When it is, the parent renders that
1061            // flow after the Loop (ordinary continuation or finally-copy
1062            // machinery) and the break lands into it — splicing a copy
1063            // duplicated ObjectInputStream.readSerialData's finally-cleanup
1064            // retry (3x catch(ThreadDeath ignored), 已在方法中定义了变量)
1065            // and stranded ConcurrentHashMap.getTable tails (无法访问的语句).
1066            // An orphaned E is rendered NOWHERE else: cleanQueue's CAS
1067            // unlink phase (reachable only via member jumps, its flow
1068            // restarts the outer loop) and TempFileHelper's
1069            // `hasPermissions = true` block (flow joins the post-loop
1070            // continuation only THROUGH the shared break stub).
1071            // Barriered forward reachability: the RAW can_reach wraps
1072            // around the loop through the restart backedge and makes
1073            // every exit "reachable" from every natural (cleanQueue 6→
1074            // 24→0→1→…→11) — barriers are the other exits, members and
1075            // enclosing headers.
1076            let orphaned = !natural.contains(&e) && {
1077                let mut seen_o: HashSet<usize> = HashSet::new();
1078                let mut qo: Vec<usize> = natural.iter().copied().collect();
1079                for x in &qo {
1080                    seen_o.insert(*x);
1081                }
1082                let mut found = false;
1083                while let Some(b) = qo.pop() {
1084                    for &n2 in &self.cfg.blocks[b].succ {
1085                        if n2 == e {
1086                            found = true;
1087                            break;
1088                        }
1089                        if barriers.contains(&n2) || n2 == header {
1090                            continue;
1091                        }
1092                        if seen_o.insert(n2) {
1093                            qo.push(n2);
1094                        }
1095                    }
1096                    if found {
1097                        break;
1098                    }
1099                }
1100                !found
1101            };
1102            if !orphaned {
1103                continue;
1104            }
1105            // SHARED-PRED gate: an exit that shares a normal-flow
1106            // predecessor with a loop member is a SIBLING CONTINUATION
1107            // branch (b24 flows to BOTH the member b25 and the exit 45 —
1108            // ois readSerialData's finally-cleanup fork), not an orphaned
1109            // break target: the outer region renders that territory once,
1110            // and copying it double-renders the flow (catch identities
1111            // rebound downstream: markException(ex=null)). cleanQueue's
1112            // CAS exit (preds all members), Bits' epilogue (pred = its
1113            // own test) and tfh/FJP/CHM restorations have no shared pred.
1114            let shared_pred = self.cfg.blocks[e].pred.iter().any(|&p| {
1115                p != header && !members.contains(&p) && self.cfg.blocks[p].succ.len() >= 2
1116            });
1117            if shared_pred {
1118                continue;
1119            }
1120            // UPDATE-BLOCK gate: an exit whose forward flow (barred by the
1121            // other exits, members, enclosing headers and the natural
1122            // continuation) reaches THIS loop's header is the iteration
1123            // update block — copying it into a jump arm inverts break into
1124            // advance+continue (Pattern split's `break` became `++x2;
1125            // offset += len; continue L3`). A genuine break exit receives
1126            // member edges too (the cond's exit side) but never flows back
1127            // to the header inside the barriers (cleanQueue's CAS exit
1128            // restarts via the OUTER stub, TempFileHelper's joins the
1129            // post-loop continuation).
1130            let is_update = {
1131                let mut bar: HashSet<usize> = barriers.clone();
1132                bar.extend(natural.iter().copied());
1133                bar.remove(&e);
1134                let mut seen2: HashSet<usize> = HashSet::new();
1135                let mut q2: Vec<usize> = vec![e];
1136                seen2.insert(e);
1137                let mut found = false;
1138                while let Some(b) = q2.pop() {
1139                    if self.cfg.blocks[b].succ.iter().any(|&n| n == header) {
1140                        found = true;
1141                        break;
1142                    }
1143                    for &n in &self.cfg.blocks[b].succ {
1144                        if !bar.contains(&n) && seen2.insert(n) {
1145                            q2.push(n);
1146                        }
1147                    }
1148                }
1149                found
1150            };
1151            if is_update {
1152                continue;
1153            }
1154            // GROUP-TERRITORY gate: an exit whose flow lies inside any try
1155            // group's protected span (or is a handler) belongs to the
1156            // finally/catch machinery — copying it competes with the
1157            // dedupe/catch-identity passes (ObjectInputStream
1158            // .readSerialData: the e=4 micro-cascade copy re-bound the
1159            // catch vars — `catch (ClassNotFoundException ignored)` +
1160            // `ex = null` made markException receive NULL instead of the
1161            // exception, and the triple `ignored` collided). cleanQueue
1162            // and TempFileHelper have no groups over their cascades.
1163            let in_group =
1164                self.groups.iter().any(|g| {
1165                    self.cfg.blocks[e].start >= g.start && self.cfg.blocks[e].start < g.end
1166                }) || self.body_group.contains_key(&e)
1167                    || self.handler_group.contains_key(&e);
1168            if in_group {
1169                continue;
1170            }
1171            let tu = crate::structure::reachable_within(self.cfg, e, &cstop);
1172            if !tu.contains(&e) || tu.len() > 48 {
1173                continue;
1174            }
1175            // HANDLER/THROW-TERRITORY gate: a cascade whose blocks
1176            // include an exception-handler head or a throw site is
1177            // finally/pending-rethrow machinery — copying it re-renders
1178            // catch flow and the downstream naming passes rebind the
1179            // catch identity (ois readSerialData e=24: the retry cascade
1180            // copy turned `catch (ClassNotFoundException e1) {
1181            // markException(passHandle, e1) }` into `catch (... ignored)
1182            // { ex = null; markException(passHandle, ex) }` — NULL
1183            // instead of the exception — plus a triple-`ignored`
1184            // redefinition error; conversion-time trial checks cannot
1185            // see it: the corruption happens in the post-convert
1186            // varalloc/naming passes). Such exits keep the bare break.
1187            // The e=4 single-Basic cascade (a genuine dropped
1188            // `hasSpecialReadMethod = true` restoration, golden-verified)
1189            // has neither handler heads nor throws and stays.
1190            if tu.iter().any(|&b| {
1191                self.handler_group.contains_key(&b)
1192                    || matches!(self.results[b].term, Term::Throw(_))
1193            }) {
1194                continue;
1195            }
1196            let mut fresh: HashSet<usize> = HashSet::new();
1197            // The walk's stop carries the OUTER barriers too (not just
1198            // cstop): Goto regions targeting them resolve to
1199            // break/continue at conversion instead of materializing
1200            // foreign territory as RawGoto copies (the ois finally-cleanup
1201            // duplication route).
1202            let mut wstop: HashSet<usize> = cstop.clone();
1203            wstop.extend(barriers.iter().copied());
1204            wstop.extend(natural.iter().copied());
1205            wstop.remove(&e);
1206            // copied_tails isolation: the cascade walk's internal
1207            // copy_walks register shared tails; leaking those into the
1208            // method's set makes the PARENT's own gotos to them elide as
1209            // reaches_copy_tail fallthrough — UnixPath.normalize lost its
1210            // whole `while (i1 < count) ... return new UnixPath(..)`
1211            // continuation (缺少返回语句 x2 trees) after an ACCEPTED splice.
1212            // Restore unconditionally: the cascade's registrations are
1213            // arm-local; the arm-internal trailing gotos still elide via
1214            // goto_is_last inside the copy.
1215            let saved_tails = self.copied_tails.clone();
1216            let r = self.walk(e, &tu, &wstop, &ctx_top_groups, &mut fresh, true);
1217            self.copied_tails = saved_tails;
1218            if matches!(r, Region::Empty) {
1219                continue;
1220            }
1221            // SELF-CONTAINED-FLOW gate: every successor of every cascade
1222            // block must stay inside the cascade universe or land on a
1223            // declared barrier (another exit, an enclosing header, the
1224            // natural continuation). A flow escaping elsewhere (into a
1225            // handler region or foreign territory) gets mangled by the
1226            // copy's conversion context (ObjectInputStream readSerialData:
1227            // the finally-cleanup retry copied as bare blocks re-bound
1228            // catch identities — markException received a null `ex`).
1229            let self_contained = tu.iter().all(|&b| {
1230                self.cfg.blocks[b].succ.iter().all(|&n| {
1231                    tu.contains(&n)
1232                        || cstop.contains(&n)
1233                        || exits.contains(&n)
1234                        || natural.contains(&n)
1235                        || ctx_loop_stack.contains(&n)
1236                        || ctx_loop_headers.contains(&n)
1237                })
1238            });
1239            if !self_contained {
1240                continue;
1241            }
1242            // A cascade containing a Try cannot be spliced as a copy: the
1243            // duplicated catch parameter collides with the original's
1244            // scope (jdk11/17 ObjectInputStream.readSerialData 已在方法中
1245            // 定义了变量 ignored — an inner catch may not redeclare an
1246            // outer catch's variable). Renaming catch vars is a
1247            // Stmt-level concern the region copy cannot express; those
1248            // exits keep the bare break (pre-fix behavior).
1249            if Self::region_contains_try(&r) {
1250                continue;
1251            }
1252            if crate::dbg_flag!("JCDC_DBG_SESE") {
1253                let txt = format!("{:?}", r);
1254                eprintln!(
1255                    "MATEXIT e={} tu={} r={}",
1256                    e,
1257                    tu.len(),
1258                    &txt[..txt.len().min(300)]
1259                );
1260            }
1261            // REDUNDANT BACKEDGE TRIM: a trailing Goto to THIS loop's own
1262            // header is the fall-out-equivalent (the parent renders
1263            // `continue` right after the loop anyway) — kept in the copy
1264            // it makes the arm all-abrupt and strands that continue
1265            // (ForkJoinPool awaitDone 无法访问的语句). Drop it; the arm
1266            // then completes normally into the parent's backedge.
1267            fn trim_backedge(r: &mut Region, header: usize) {
1268                if let Region::Seq(v) = r {
1269                    if matches!(v.last(), Some(Region::Goto { target }) if *target == header) {
1270                        v.pop();
1271                    }
1272                    return;
1273                }
1274                if matches!(r, Region::Goto { target } if *target == header) {
1275                    *r = Region::Empty;
1276                }
1277            }
1278            let mut r = r;
1279            trim_backedge(&mut r, header);
1280            if matches!(r, Region::Empty) {
1281                continue;
1282            }
1283            // CONVERSION-AWARE VALIDATION (the gate the region-level
1284            // predicates could not express — two experiment rounds proved
1285            // the harm classes arise at conversion/Stmt level): trial-
1286            // splice into a CLONE, convert it in a throwaway Converter,
1287            // and scan the Stmt tree for splice pathologies:
1288            // (1) abrupt-stranding — a terminating statement followed by
1289            //     siblings in the same block (the spliced cascade's inner
1290            //     gotos resolved to break/continue at this site where the
1291            //     ORIGINAL Goto{E} elided as fallthrough; jdk26
1292            //     ConcurrentHashMap.getTable 无法访问的语句). prune_
1293            //     unreachable would silently DELETE the stranded siblings.
1294            // (2) duplicate catch exception types — the copy re-rendered
1295            //     handler flow whose catch identity the naming passes
1296            //     then rebind (jdk11 ObjectInputStream.readSerialData
1297            //     markException(ex=null) semantic corruption).
1298            // Clean → commit the splice; pathology → roll back this exit
1299            // (the clone is dropped; nothing outside was mutated).
1300            // Two-tier site policy validated by trial conversion: tier 1
1301            // (loose) splices arm/tail Goto sites even under enclosing
1302            // Seqs with live siblings (CHM putVal's addCount restoration
1303            // lives on such an arm); tier 2 (strict) restricts to the
1304            // true flow-end chain (Bits phase-1's catch-handler Goto{16}
1305            // is followed by the handler's Goto{7} retry — splicing the
1306            // terminating epilogue there strands it). Validate tier 1;
1307            // on pathology fall back to tier 2 and re-validate; reject
1308            // the exit only when both fail.
1309            //
1310            // A cascade whose every flow path already terminates
1311            // (return/throw inlined via term_copy) takes NO trailing
1312            // Goto{e} (the break would render after a return — dead);
1313            // non-terminating cascades keep it so the break binding
1314            // survives. In-loop normalization: when the loop's natural
1315            // continuation is itself a barrier (backedge stub / outer
1316            // header / exit), re-append Goto{e} so the fall-out arm
1317            // re-iterates explicitly like the golden `continue`.
1318            let mut replacement = if self.region_all_paths_terminate(&r) {
1319                r.clone()
1320            } else {
1321                Region::Seq(vec![r.clone(), Region::Goto { target: e }])
1322            };
1323            let natural_is_barrier = natural
1324                .iter()
1325                .all(|&n0| exits.contains(&n0) || ctx_loop_stack.contains(&n0));
1326            if natural_is_barrier
1327                && self.region_all_paths_terminate(&r)
1328                && !matches!(replacement, Region::Seq(_))
1329            {
1330                replacement = Region::Seq(vec![replacement, Region::Goto { target: e }]);
1331            }
1332            let convert_trial = |tb: Region| -> (Stmt, usize) {
1333                let mut conv = crate::convert::Converter::new(self.cfg, self.results)
1334                    .with_copied_tails(self.copied_tails.clone())
1335                    .with_final_fields(self.final_fields.clone());
1336                let st = conv.convert(tb);
1337                let lab = Self::count_labeled(&st);
1338                (st, lab)
1339            };
1340            let trial1 = {
1341                let mut tb = body.clone();
1342                Self::splice_exit_copies_with(&mut tb, e, &replacement, false);
1343                self.replace_empty_arms_for(&mut tb, e, &replacement);
1344                tb
1345            };
1346            let (stmt1, lab1) = convert_trial(trial1);
1347            let strict = if !Self::stmt_splice_pathology(&stmt1) && lab1 == base_labeled {
1348                false
1349            } else {
1350                let trial2 = {
1351                    let mut tb = body.clone();
1352                    Self::splice_exit_copies_with(&mut tb, e, &replacement, true);
1353                    self.replace_empty_arms_for(&mut tb, e, &replacement);
1354                    tb
1355                };
1356                let (stmt2, lab2) = convert_trial(trial2);
1357                if Self::stmt_splice_pathology(&stmt2) || lab2 != base_labeled {
1358                    if crate::dbg_flag!("JCDC_DBG_SESE") {
1359                        eprintln!("MATEXIT-REJECT e={} both tiers pathological", e);
1360                    }
1361                    continue;
1362                }
1363                true
1364            };
1365            if crate::dbg_flag!("JCDC_DBG_SESE") {
1366                let mut tusize: Vec<usize> = tu.iter().copied().collect();
1367                tusize.sort_unstable();
1368                eprintln!("MATEXIT-ACCEPT e={} strict={} tu={:?}", e, strict, tusize);
1369                for (gi, g) in self.groups.iter().enumerate() {
1370                    let overlap: Vec<usize> = tusize
1371                        .iter()
1372                        .copied()
1373                        .filter(|&b| {
1374                            self.cfg.blocks[b].start >= g.start && self.cfg.blocks[b].start < g.end
1375                        })
1376                        .collect();
1377                    if !overlap.is_empty() {
1378                        eprintln!(
1379                            "MXGROUP gi={} span=({},{}) overlap={:?}",
1380                            gi, g.start, g.end, overlap
1381                        );
1382                    }
1383                }
1384                let bg: Vec<usize> = tusize
1385                    .iter()
1386                    .copied()
1387                    .filter(|b| self.body_group.contains_key(b))
1388                    .collect();
1389                let hg: Vec<usize> = tusize
1390                    .iter()
1391                    .copied()
1392                    .filter(|b| self.handler_group.contains_key(b))
1393                    .collect();
1394                eprintln!("MXGH body_group={:?} handler_group={:?}", bg, hg);
1395            }
1396            let h1 = Self::splice_exit_copies_with(body, e, &replacement, strict);
1397            let h2 = self.replace_empty_arms_for(body, e, &replacement);
1398            if h1 || h2 {
1399                MATEXIT_FIRED.with(|f| f.set(true));
1400            }
1401        }
1402    }
1403
1404    /// True when every flow path through the region ends at a
1405    /// return/throw (Basic/CopyStmts of a terminator block, or a Goto
1406    /// whose target term-copies inline). Empty arms fall through, so an
1407    /// If only terminates when BOTH arms do; a Seq when its last element
1408    /// does.
1409    fn region_all_paths_terminate(&self, r: &Region) -> bool {
1410        match r {
1411            Region::Basic { block } | Region::CopyStmts { block } => {
1412                self.is_terminator_block(*block)
1413            }
1414            Region::Goto { target } => self.is_terminator_block(*target),
1415            Region::Seq(v) => v
1416                .last()
1417                .map(|x| self.region_all_paths_terminate(x))
1418                .unwrap_or(false),
1419            Region::If { then_r, else_r, .. } => {
1420                self.region_all_paths_terminate(then_r) && self.region_all_paths_terminate(else_r)
1421            }
1422            Region::Try { body, catches, .. } => {
1423                self.region_all_paths_terminate(body)
1424                    && catches
1425                        .iter()
1426                        .all(|(_, _, h)| self.region_all_paths_terminate(h))
1427            }
1428            _ => false,
1429        }
1430    }
1431
1432    /// Count Stmt::Labeled nodes in a converted tree (rotation-shape
1433    /// fingerprint for the trial comparison).
1434    fn count_labeled(s: &Stmt) -> usize {
1435        let mut n = match s {
1436            Stmt::Labeled { .. } => 1,
1437            _ => 0,
1438        };
1439        match s {
1440            Stmt::Block(v) => {
1441                for x in v {
1442                    n += Self::count_labeled(x);
1443                }
1444            }
1445            Stmt::If {
1446                then_stmt,
1447                else_stmt,
1448                ..
1449            } => {
1450                n += Self::count_labeled(then_stmt);
1451                if let Some(e) = else_stmt {
1452                    n += Self::count_labeled(e);
1453                }
1454            }
1455            Stmt::While { body, .. }
1456            | Stmt::DoWhile { body, .. }
1457            | Stmt::ForEach { body, .. }
1458            | Stmt::Labeled { body, .. }
1459            | Stmt::Synchronized { body, .. } => n += Self::count_labeled(body),
1460            Stmt::For { init, body, .. } => {
1461                for x in init {
1462                    n += Self::count_labeled(x);
1463                }
1464                n += Self::count_labeled(body);
1465            }
1466            Stmt::Try {
1467                body,
1468                catches,
1469                finally,
1470                ..
1471            } => {
1472                n += Self::count_labeled(body);
1473                for c in catches {
1474                    n += Self::count_labeled(&c.body);
1475                }
1476                if let Some(f) = finally {
1477                    n += Self::count_labeled(f);
1478                }
1479            }
1480            Stmt::Switch { cases, default, .. } => {
1481                for c in cases {
1482                    for x in &c.body {
1483                        n += Self::count_labeled(x);
1484                    }
1485                }
1486                if let Some(d) = default {
1487                    n += Self::count_labeled(d);
1488                }
1489            }
1490            _ => {}
1491        }
1492        n
1493    }
1494
1495    /// Scan a converted Stmt tree for splice pathologies (see
1496    /// materialize_content_exits). Conservative: any hit rolls the exit
1497    /// back to the bare-break shape.
1498    pub fn stmt_splice_pathology(s: &Stmt) -> bool {
1499        Self::pathology_in(s, None)
1500    }
1501
1502    /// Label-aware JLS-14.21 termination for the pathology scanner:
1503    /// `break L1` targeting an OUTER labeled loop escapes an inner
1504    /// `while (true)` WITHOUT letting it complete normally — only
1505    /// Break(None) or a break carrying THIS loop's own label does.
1506    /// stmt_terminates's any-labeled-break conservatism (correct for
1507    /// prune_unreachable's deletion side) false-negatived the
1508    /// ForwardingNode.find strand (无法访问的语句 x3 trees: the spliced
1509    /// cascade made the inner while(true) body all-abrupt, the outer
1510    /// break-through left the loop non-completing, and the parent's next
1511    /// sibling was unreachable).
1512    fn terminates_scoped(s: &Stmt, own: Option<&str>) -> bool {
1513        fn is_true_expr(c: &crate::ir::expr::Expr) -> bool {
1514            matches!(
1515                c,
1516                crate::ir::expr::Expr::Const(crate::ir::expr::ConstVal::Int(1))
1517            )
1518        }
1519        fn deep_own_break(s: &Stmt, own: Option<&str>) -> bool {
1520            match s {
1521                Stmt::Break(None) => true,
1522                Stmt::Break(Some(l)) => Some(l.as_str()) == own,
1523                Stmt::Block(v) => v.iter().any(|x| deep_own_break(x, own)),
1524                Stmt::If {
1525                    then_stmt,
1526                    else_stmt,
1527                    ..
1528                } => {
1529                    deep_own_break(then_stmt, own)
1530                        || else_stmt
1531                            .as_ref()
1532                            .map(|e| deep_own_break(e, own))
1533                            .unwrap_or(false)
1534                }
1535                Stmt::While { body, .. }
1536                | Stmt::DoWhile { body, .. }
1537                | Stmt::ForEach { body, .. }
1538                | Stmt::For { body, .. }
1539                | Stmt::Synchronized { body, .. }
1540                | Stmt::Labeled { body, .. } => deep_own_break(body, own),
1541                Stmt::Switch { cases, default, .. } => {
1542                    cases
1543                        .iter()
1544                        .any(|c| c.body.iter().any(|x| deep_own_break(x, own)))
1545                        || default
1546                            .as_ref()
1547                            .map(|d| deep_own_break(d, own))
1548                            .unwrap_or(false)
1549                }
1550                Stmt::Try {
1551                    body,
1552                    catches,
1553                    finally,
1554                    ..
1555                } => {
1556                    deep_own_break(body, own)
1557                        || catches.iter().any(|c| deep_own_break(&c.body, own))
1558                        || finally
1559                            .as_ref()
1560                            .map(|f| deep_own_break(f, own))
1561                            .unwrap_or(false)
1562                }
1563                Stmt::TryWithResources {
1564                    resources,
1565                    body,
1566                    catches,
1567                    finally,
1568                    ..
1569                } => {
1570                    resources.iter().any(|r| deep_own_break(r, own))
1571                        || deep_own_break(body, own)
1572                        || catches.iter().any(|c| deep_own_break(&c.body, own))
1573                        || finally
1574                            .as_ref()
1575                            .map(|f| deep_own_break(f, own))
1576                            .unwrap_or(false)
1577                }
1578                _ => false,
1579            }
1580        }
1581        match s {
1582            Stmt::Return(_) | Stmt::Throw(_) | Stmt::Break(_) | Stmt::Continue(_) => true,
1583            Stmt::Block(v) => v
1584                .last()
1585                .map(|x| Structurer::terminates_scoped(x, own))
1586                .unwrap_or(false),
1587            Stmt::If {
1588                then_stmt,
1589                else_stmt: Some(e),
1590                ..
1591            } => {
1592                Structurer::terminates_scoped(then_stmt, own)
1593                    && Structurer::terminates_scoped(e, own)
1594            }
1595            Stmt::Synchronized { body, .. } => Structurer::terminates_scoped(body, own),
1596            Stmt::Labeled { label, body } => Structurer::terminates_scoped(body, Some(label)),
1597            Stmt::While { cond, body } | Stmt::DoWhile { body, cond }
1598                if is_true_expr(cond) && !deep_own_break(body, own) =>
1599            {
1600                true
1601            }
1602            Stmt::For { cond, body, .. }
1603                if match cond {
1604                    None => true,
1605                    Some(c) => is_true_expr(c),
1606                } && !deep_own_break(body, own) =>
1607            {
1608                true
1609            }
1610            Stmt::Try { body, catches, .. } => {
1611                Structurer::terminates_scoped(body, own)
1612                    && catches
1613                        .iter()
1614                        .all(|c| Structurer::terminates_scoped(&c.body, own))
1615            }
1616            _ => false,
1617        }
1618    }
1619
1620    fn pathology_in(s: &Stmt, own: Option<&str>) -> bool {
1621        fn stmt_is_empty(x: &Stmt) -> bool {
1622            match x {
1623                Stmt::Block(v) => v.iter().all(stmt_is_empty),
1624                Stmt::Comment(_) => true,
1625                _ => false,
1626            }
1627        }
1628        fn dup_catch(catches: &[crate::ir::stmt::Catch]) -> bool {
1629            for i in 0..catches.len() {
1630                for j in i + 1..catches.len() {
1631                    if !catches[i].exc.is_empty() && catches[i].exc == catches[j].exc {
1632                        return true;
1633                    }
1634                }
1635            }
1636            false
1637        }
1638        match s {
1639            Stmt::Block(v) => {
1640                if v.len() > 1 {
1641                    if let Some(pos) = v.iter().position(|x| Structurer::terminates_scoped(x, own))
1642                    {
1643                        // EMPTY trailing blocks are conversion placeholders
1644                        // (elided gotos) that cleanup() removes before
1645                        // render — javac never sees them. Only NON-EMPTY
1646                        // stranded siblings are pathologies (the trial
1647                        // scans raw converter output; Bits phase-1's
1648                        // [terminating Try, Block([])] false positive
1649                        // vetoed the splice).
1650                        //
1651                        // EXCEPT when the terminator is an emit-level
1652                        // dead-end while(true): Printer::into_string runs
1653                        // truncate_dead_ends over the FINAL tree and
1654                        // strips everything after it, so javac never sees
1655                        // those siblings either — flagging them vetoed the
1656                        // matexit shape whose break-cascade arms carry the
1657                        // loop's real exits (jdk26 ConcurrentLinkedQueue
1658                        // .poll: the restart Continue(None) after the
1659                        // dead-end inner traversal forced the retry, whose
1660                        // matexit-OFF shape drops the cas-success p==h
1661                        // `return item` exit — the polled item was
1662                        // dequeued but never returned).
1663                        let scan_len = if crate::analysis::dead_end_infinite_while(&v[pos]) {
1664                            pos + 1
1665                        } else {
1666                            v.len()
1667                        };
1668                        if v[pos + 1..scan_len].iter().any(|x| !stmt_is_empty(x)) {
1669                            return true;
1670                        }
1671                        // Truncated siblings are invisible to javac — their
1672                        // interiors cannot be pathologies either.
1673                        return v[..scan_len]
1674                            .iter()
1675                            .any(|x| Structurer::pathology_in(x, own));
1676                    }
1677                }
1678                v.iter().any(|x| Structurer::pathology_in(x, own))
1679            }
1680            Stmt::If {
1681                then_stmt,
1682                else_stmt,
1683                ..
1684            } => {
1685                Structurer::pathology_in(then_stmt, own)
1686                    || else_stmt
1687                        .as_ref()
1688                        .map(|e| Structurer::pathology_in(e, own))
1689                        .unwrap_or(false)
1690            }
1691            // Loop bodies bind unlabeled breaks to themselves: the
1692            // enclosing label does NOT propagate in (an inner while(true)
1693            // under `L1:` is still non-completing when its body breaks
1694            // to L1 — the break escapes THROUGH it). Synchronized is
1695            // transparent.
1696            Stmt::While { body, .. } | Stmt::DoWhile { body, .. } | Stmt::ForEach { body, .. } => {
1697                Structurer::pathology_in(body, None)
1698            }
1699            Stmt::Synchronized { body, .. } => Structurer::pathology_in(body, own),
1700            Stmt::For { init, body, .. } => {
1701                init.iter().any(|x| Structurer::pathology_in(x, own))
1702                    || Structurer::pathology_in(body, None)
1703            }
1704            Stmt::Labeled { label, body } => Structurer::pathology_in(body, Some(label)),
1705            Stmt::Try {
1706                body,
1707                catches,
1708                finally,
1709                ..
1710            } => {
1711                dup_catch(catches)
1712                    || Structurer::pathology_in(body, own)
1713                    || catches
1714                        .iter()
1715                        .any(|c| Structurer::pathology_in(&c.body, own))
1716                    || finally
1717                        .as_ref()
1718                        .map(|f| Structurer::pathology_in(f, own))
1719                        .unwrap_or(false)
1720            }
1721            Stmt::TryWithResources {
1722                body,
1723                catches,
1724                finally,
1725                ..
1726            } => {
1727                dup_catch(catches)
1728                    || Structurer::pathology_in(body, own)
1729                    || catches
1730                        .iter()
1731                        .any(|c| Structurer::pathology_in(&c.body, own))
1732                    || finally
1733                        .as_ref()
1734                        .map(|f| Structurer::pathology_in(f, own))
1735                        .unwrap_or(false)
1736            }
1737            Stmt::Switch { cases, default, .. } => {
1738                cases
1739                    .iter()
1740                    .any(|c| c.body.iter().any(|x| Structurer::pathology_in(x, own)))
1741                    || default
1742                        .as_ref()
1743                        .map(|d| Structurer::pathology_in(d, own))
1744                        .unwrap_or(false)
1745            }
1746            _ => false,
1747        }
1748    }
1749
1750    /// True when the region tree contains any Try.
1751    fn region_contains_try(r: &Region) -> bool {
1752        match r {
1753            Region::Try { .. } => true,
1754            Region::Seq(v) => v.iter().any(Self::region_contains_try),
1755            Region::If { then_r, else_r, .. } => {
1756                Self::region_contains_try(then_r) || Self::region_contains_try(else_r)
1757            }
1758            Region::Loop { body, .. } => Self::region_contains_try(body),
1759            Region::Switch { cases, default, .. } => {
1760                cases.iter().any(|(_, cr)| Self::region_contains_try(cr))
1761                    || default
1762                        .as_ref()
1763                        .map(|d| Self::region_contains_try(d))
1764                        .unwrap_or(false)
1765            }
1766            _ => false,
1767        }
1768    }
1769
1770    /// Replace EMPTY If arms whose branch target is `e` with the
1771    /// replacement region: the Bits phase-1 shape has NO Goto{e} site at
1772    /// all — the COND's fall==follow==exit renders the success arm as
1773    /// Region::Empty and the body falls out to the backedge (re-loop).
1774    /// The empty arm IS the jump to e; materializing it restores the
1775    /// golden `if (!call) continue; else { epilogue; }`.
1776    fn replace_empty_arms_for(&self, r: &mut Region, e: usize, replacement: &Region) -> bool {
1777        match r {
1778            Region::If {
1779                block,
1780                then_r,
1781                else_r,
1782                ..
1783            } => {
1784                let succs = &self.cfg.blocks[*block].succ;
1785                let mut hit = false;
1786                if matches!(**then_r, Region::Empty) && succs.get(1) == Some(&e) {
1787                    *then_r = Box::new(replacement.clone());
1788                    hit = true;
1789                }
1790                if matches!(**else_r, Region::Empty) && succs.first() == Some(&e) {
1791                    *else_r = Box::new(replacement.clone());
1792                    hit = true;
1793                }
1794                hit |= self.replace_empty_arms_for(then_r, e, replacement);
1795                hit |= self.replace_empty_arms_for(else_r, e, replacement);
1796                hit
1797            }
1798            Region::Seq(v) => v.iter_mut().fold(false, |h, x| {
1799                h | self.replace_empty_arms_for(x, e, replacement)
1800            }),
1801            Region::Try { body, catches, .. } => {
1802                let mut hit = self.replace_empty_arms_for(body, e, replacement);
1803                for (_, _, h) in catches.iter_mut() {
1804                    hit |= self.replace_empty_arms_for(h, e, replacement);
1805                }
1806                hit
1807            }
1808            Region::Loop { body, .. } => self.replace_empty_arms_for(body, e, replacement),
1809            Region::Switch { cases, default, .. } => {
1810                let mut hit = false;
1811                for (_, cr) in cases.iter_mut() {
1812                    hit |= self.replace_empty_arms_for(cr, e, replacement);
1813                }
1814                if let Some(d) = default {
1815                    hit |= self.replace_empty_arms_for(d, e, replacement);
1816                }
1817                hit
1818            }
1819            _ => false,
1820        }
1821    }
1822
1823    /// Replace `Goto{e}` sites in the region tree with `replacement`
1824    /// (per-arrival copies; Region: Clone). `strict`: only sites on the
1825    /// true flow-end chain (every enclosing Seq position is last) are
1826    /// replaced; loose mode additionally replaces arm-internal sites
1827    /// whose enclosing Seq has live siblings. A MID-Seq Goto leaf is
1828    /// never replaced in either mode (live siblings follow it directly).
1829    fn splice_exit_copies_with(
1830        r: &mut Region,
1831        e: usize,
1832        replacement: &Region,
1833        strict: bool,
1834    ) -> bool {
1835        match r {
1836            Region::Goto { target } if *target == e => {
1837                *r = replacement.clone();
1838                true
1839            }
1840            Region::Seq(v) => {
1841                let mut hit = false;
1842                let n = v.len();
1843                for (i, x) in v.iter_mut().enumerate() {
1844                    let last = i + 1 == n;
1845                    if matches!(x, Region::Goto { target } if *target == e) {
1846                        if last {
1847                            *x = replacement.clone();
1848                            hit = true;
1849                        }
1850                    } else {
1851                        hit |= Self::splice_exit_copies_with(x, e, replacement, strict || !last);
1852                    }
1853                }
1854                hit
1855            }
1856            Region::If { then_r, else_r, .. } => {
1857                let a = Self::splice_exit_copies_with(then_r, e, replacement, strict);
1858                let b = Self::splice_exit_copies_with(else_r, e, replacement, strict);
1859                a | b
1860            }
1861            Region::Try { body, catches, .. } => {
1862                let mut hit = Self::splice_exit_copies_with(body, e, replacement, strict);
1863                for (_, _, h) in catches.iter_mut() {
1864                    hit |= Self::splice_exit_copies_with(h, e, replacement, strict);
1865                }
1866                hit
1867            }
1868            Region::Loop { body, .. } => {
1869                Self::splice_exit_copies_with(body, e, replacement, strict)
1870            }
1871            Region::Switch { cases, default, .. } => {
1872                let mut hit = false;
1873                for (_, cr) in cases.iter_mut() {
1874                    hit |= Self::splice_exit_copies_with(cr, e, replacement, strict);
1875                }
1876                if let Some(d) = default {
1877                    hit |= Self::splice_exit_copies_with(d, e, replacement, strict);
1878                }
1879                hit
1880            }
1881            _ => false,
1882        }
1883    }
1884
1885    fn sese_region_with_scope(
1886        &mut self,
1887        entry: usize,
1888        stop: &HashSet<usize>,
1889        reach: HashSet<usize>,
1890        ctx: &mut SeseCtx,
1891    ) -> Region {
1892        ctx.depth += 1;
1893        let deep = ctx.depth > 400;
1894        let mut parts: Vec<Region> = Vec::new();
1895        let mut cur = entry;
1896        let mut guard = 0usize;
1897        // True when the walk advanced into `cur` through an explicit Goto
1898        // terminator (vs. natural fall-through): a jump into a stop must be
1899        // materialized as a Goto region (the converter resolves it to
1900        // break/continue, elides it as if-follow fallthrough, or inlines a
1901        // shared return/throw via term_copy) — silently ending the region
1902        // DROPS the jump (jdk17 String LATIN1 fast-path `goto 839` lost its
1903        // `return;` against the stop=shared-exit, double-assigning finals).
1904        let mut last_via_goto = false;
1905        loop {
1906            guard += 1;
1907            if crate::dbg_flag!("JCDC_DBG_GOTO") {
1908                eprintln!("SESETOP entry={} cur={} parts={} reach={} stop={} consumed={} last_via_goto={}",
1909                    entry, cur, parts.len(), reach.contains(&cur), stop.contains(&cur),
1910                    ctx.consumed.contains(&cur), last_via_goto);
1911            }
1912            if deep || guard > ctx.universe.len() * 4 + 64 {
1913                break;
1914            }
1915            // A try body reaches its tail through inlined/duplicated finally
1916            // copies, so reachable_within (normal succ only) can miss the
1917            // post-finally continuation even though it is a legitimate forward
1918            // tail (unconsumed, in-universe, not a stop). Structure it anyway;
1919            // monotonicity is preserved by the consumed check below (a block
1920            // owned by a sibling is consumed -> Goto, never re-structured).
1921            let forward_tail = !reach.contains(&cur)
1922                && ctx.universe.contains(&cur)
1923                && !ctx.consumed.contains(&cur)
1924                && !stop.contains(&cur);
1925            if !forward_tail
1926                && (stop.contains(&cur) || !ctx.universe.contains(&cur) || !reach.contains(&cur))
1927            {
1928                // A region whose ENTRY is itself a stop block was branched-to
1929                // deliberately (a cond branch / `break` to a loop exit, or a
1930                // jump to an enclosing follow). Emit Goto{entry} so the
1931                // converter resolves it to break/continue — or elides it as a
1932                // natural fallthrough when entry is the enclosing if-follow.
1933                // Without this, a `break outer` branch to a stop block renders
1934                // as an EMPTY branch and the loop exit is silently lost
1935                // (Legacy6 `if (a==2 && b==2) break outer;` -> infinite loop).
1936                if cur == entry && stop.contains(&entry) && parts.is_empty() {
1937                    parts.push(Region::Goto { target: entry });
1938                } else if last_via_goto && stop.contains(&cur) && !parts.is_empty() {
1939                    parts.push(Region::Goto { target: cur });
1940                }
1941                break;
1942            }
1943            if ctx.consumed.contains(&cur) {
1944                // Already structured (a shared merge owned by an earlier
1945                // sibling/region). A shared TERMINATOR (return/throw) is
1946                // safely duplicated inline at each arrival site (it has no
1947                // outgoing flow) — this is how `if (t || explode()) return 1;
1948                // return 2;` keeps the `return 1` on both the t-true and
1949                // explode-true paths. Anything else becomes a Goto (resolved
1950                // to break/continue/label at conversion), never a re-walk.
1951                if matches!(self.results[cur].term, Term::Return(_) | Term::Throw(_)) {
1952                    // Shared terminator: duplicate inline (no outgoing
1953                    // flow). Duplicating a final-field write is REQUIRED
1954                    // here: the paths are disjoint (each copy ends in the
1955                    // return), and eliding it would drop the assignment
1956                    // from this path entirely ("variable f might not have
1957                    // been assigned" — Fin/Long$LongCache fresh path).
1958                    parts.push(Region::CopyStmts { block: cur });
1959                } else if ctx.loop_stack.contains(&cur) {
1960                    // Back-edge to an enclosing loop header: a `continue`
1961                    // (resolved at conversion). NEVER copy_walk it — that would
1962                    // re-walk the whole loop as a nested duplicate. The Goto is
1963                    // emitted even when parts is empty: a branch region that
1964                    // IS the jump to the header (`if (c) continue;`) must not
1965                    // collapse to Empty — that silently dropped BOTH continues
1966                    // of StringUTF16.codePointCount, running the loop tail
1967                    // unconditionally.
1968                    parts.push(Region::Goto { target: cur });
1969                } else if let Some(&h) = ctx
1970                    .loop_stack
1971                    .iter()
1972                    .rev()
1973                    .find(|&&h| crate::structure::can_reach_cfg(self.cfg, cur, h, 4096))
1974                {
1975                    // The consumed block flows back into an enclosing loop
1976                    // (a catch's retry back-edge into the loop-top try,
1977                    // jdk11 ObjectStreamClass.getInheritableMethod): a
1978                    // copy_walk here unrolls the loop into nested duplicate
1979                    // tries (COPY_DEPTH-bounded, then wrong). Resolve as
1980                    // `continue` of the nearest such loop instead — walk's
1981                    // loops_stack guard equivalent (walk tracks its own
1982                    // stack; SESE keeps it in ctx).
1983                    parts.push(Region::Goto { target: h });
1984                } else if !stop.contains(&cur) {
1985                    // Shared non-terminator reached from a divergent sibling
1986                    // (e.g. the continuation after `if (A && B) return X;`):
1987                    // copy_walk re-structures it inline, COPY_DEPTH-bounded so
1988                    // nested shared chains stay monotone (no divergence). The
1989                    // copy is additionally barred from leaving THIS region's
1990                    // scope: reachable_within(copy) must not pick up blocks the
1991                    // enclosing walk could never consume (that is how the
1992                    // post-loop tail vanished from a copied loop branch).
1993                    // Falls back to a Goto when the cap is hit or it loops back.
1994                    let mut cstop: HashSet<usize> = stop.iter().copied().collect();
1995                    for &u in ctx.universe.iter() {
1996                        if !reach.contains(&u) {
1997                            cstop.insert(u);
1998                        }
1999                    }
2000                    let prev_allow =
2001                        crate::structure::COPY_ALLOW_CONFLUENCE.with(|c| c.replace(true));
2002                    let copied = self.copy_walk(cur, &cstop, &ctx.top_groups, usize::MAX);
2003                    crate::structure::COPY_ALLOW_CONFLUENCE.with(|c| c.set(prev_allow));
2004                    match copied {
2005                        Some(r) => parts.push(r),
2006                        None => {
2007                            if !parts.is_empty() {
2008                                parts.push(Region::Goto { target: cur });
2009                            }
2010                        }
2011                    }
2012                } else if !stop.contains(&cur)
2013                    || !self.sese_stop_chain_to_claimed_terminator(cur, stop, ctx)
2014                {
2015                    if !parts.is_empty() {
2016                        parts.push(Region::Goto { target: cur });
2017                    }
2018                } else {
2019                    // A stop member whose forward flow is a single-succ chain
2020                    // into an ALREADY-CONSUMED terminator: copy the chain
2021                    // inline. The restart-loop switch (jdk26 DecimalFormat
2022                    // guarded typeSwitch): the guard-pass body is a loop exit
2023                    // that flows ONLY to the shared areturn every case region
2024                    // absorbed — `break L1` would land after the loop where
2025                    // nothing remains and the body is lost. Normal loop exits
2026                    // chain to UNCLAIMED continuations and keep the Goto
2027                    // (inlining those rewrote breaks into returns and
2028                    // degraded while-cond loops, ThreadPoolExecutor).
2029                    let mut cstop: HashSet<usize> = stop.iter().copied().collect();
2030                    for &u in ctx.universe.iter() {
2031                        if !reach.contains(&u) {
2032                            cstop.insert(u);
2033                        }
2034                    }
2035                    match self.copy_walk(cur, &cstop, &ctx.top_groups, usize::MAX) {
2036                        Some(r) => parts.push(r),
2037                        None => {
2038                            if !parts.is_empty() {
2039                                parts.push(Region::Goto { target: cur });
2040                            }
2041                        }
2042                    }
2043                }
2044                break;
2045            }
2046            // Value-diamond fold: when `cur` roots a pre-folded pure-value
2047            // diamond (computed by the builder), collapse it — consume the
2048            // absorbed branch blocks and continue at the merge, whose input
2049            // stack already holds the folded ternary. This is what turns
2050            // boolean short-circuits (`a && b`, `a || b`) and `c ? a : b`
2051            // into expressions instead of structuring them as control-flow
2052            // ifs with empty branches (the milestone-3 parity with walk).
2053            // A block that is ALSO the exact start of a try group must be
2054            // structured as the try first — walk checks groups before folds.
2055            // Collapsing it as a value diamond skips the try entirely and
2056            // orphans the handler (URL.createURLStreamHandler: stage-1 string
2057            // switch dispatch folded, try [5,86) never fired, bare reflective
2058            // call without its catch -> unreported checked exceptions; a jdk11/17
2059            // corpus blocker). The diamond is re-folded inside the try body walk.
2060            let fold_blocked_by_group = (0..self.groups.len()).any(|gi| {
2061                self.groups[gi].start == self.cfg.blocks[cur].start
2062                    && self.groups[gi].end >= self.cfg.blocks[cur].end
2063                    && !self.handler_group.contains_key(&cur)
2064            });
2065            if let Some(&merge) = self.fold_root_to_merge.get(&cur) {
2066                if !fold_blocked_by_group {
2067                    if let Some((_root, vis)) = self.fold_regions.get(&merge) {
2068                        if !self.results[cur].stmts.is_empty() {
2069                            parts.push(Region::Basic { block: cur });
2070                        }
2071                        for &v in vis.iter() {
2072                            ctx.consumed.insert(v);
2073                        }
2074                        ctx.consumed.insert(cur);
2075                        cur = merge;
2076                        last_via_goto = false;
2077                        continue;
2078                    }
2079                }
2080            }
2081            let b = &self.cfg.blocks[cur];
2082            if b.ins_len == 0 {
2083                ctx.consumed.insert(cur);
2084                match b.succ.first().copied() {
2085                    Some(n) => {
2086                        cur = n;
2087                        last_via_goto = false;
2088                        continue;
2089                    }
2090                    None => break,
2091                }
2092            }
2093
2094            // Loop header? Structure the natural loop, then continue at its
2095            // follow (the exit the loop post-dominates toward).
2096            // Try group starting exactly here? Reuse the tuned try builder
2097            // (body/handlers structured by walk over their sub-scopes; the
2098            // handler regions and finally duplication are intricate). Pick the
2099            // OUTERMOST group starting at cur (largest span); structure_try
2100            // handles nested groups internally.
2101            {
2102                let bs = self.cfg.blocks[cur].start;
2103                let be = self.cfg.blocks[cur].end;
2104                let group_here = (0..self.groups.len())
2105                    .filter(|&gi| {
2106                        self.groups[gi].start == bs
2107                            && self.groups[gi].end >= be
2108                            && !self.handler_group.contains_key(&cur)
2109                    })
2110                    .max_by_key(|&gi| self.groups[gi].end);
2111                // The group starts at a LOOP HEADER whose back edge lies
2112                // OUTSIDE the protected span (`for (;;) { try { ... }
2113                // catch { ... } ...retry... }` — jdk26
2114                // ClassValue.getFromHashMap): the loop is the enclosing
2115                // construct. Structuring the try first consumes the
2116                // header and the back edge gets duplicated (3× unrolled
2117                // copies, lost retry loop, missing return). Let the
2118                // loop-header branch below win; the body walk re-finds
2119                // this group at its start. try{while} keeps group-first:
2120                // its back edge is INSIDE the protected span.
2121                //
2122                // FINALLY-WRAP exception: `try { while (true) { ... }
2123                // finally { ... } }` (jdk26 KQueuePort
2124                // EventHandlerTask.run) — javac splits the protection
2125                // around the inlined finally copies, so the FIRST range
2126                // ends mid-loop and the back edges sit outside it: the
2127                // ClassValue span shape. What separates the two is the
2128                // handler's TAIL: ClassValue's catch continues the
2129                // retry (the loop must own the header), while a finally
2130                // handler ends in a pending rethrow and never returns
2131                // to the header. Fingerprint: an `any`-range of this
2132                // group's handler set whose end extends INTO the handler
2133                // block — the protection blankets the whole loop up to
2134                // the handler entry (KQueuePort range 171..211 over
2135                // handler 209). Loop-first there nests the try inside
2136                // the loop and walks the loop's break-path finally copy
2137                // (pollTask()==null fall-out) as the post-loop
2138                // continuation — a second threadExit after the
2139                // all-paths-return while(true): 无法访问的语句 x3 trees.
2140                let finally_wrap = |gi: usize| -> bool {
2141                    let g = &self.groups[gi];
2142                    self.cfg.exc_ranges.iter().any(|r| {
2143                        r.catch_type.is_none()
2144                            && g.handlers
2145                                .iter()
2146                                .any(|(h2, t2)| t2.is_none() && *h2 == r.handler)
2147                            && r.start < r.handler
2148                            && self.cfg.block_at(r.handler).is_some_and(|hb| {
2149                                r.end > self.cfg.blocks[hb].start
2150                                    && r.end < self.cfg.blocks[hb].end.saturating_add(8)
2151                            })
2152                    })
2153                };
2154                // The finally-wrap fingerprint overrides BOTH loop-first
2155                // rules (back-edge-outside-span and exc-retry-header):
2156                // KQueuePort's loop is also an exc-retry loop (the
2157                // InterruptedException handler's `goto 16` continue), and
2158                // the wrap still belongs outside it — structure_try's
2159                // body walk re-structures the loop at the header via
2160                // sese_exc_retry_headers (the parseBest mechanism). The
2161                // typed-catch retry shapes (parseBest DateTimeException,
2162                // Process.waitFor) have no `any` handler and never trip
2163                // the fingerprint.
2164                let group_here = group_here.filter(|&gi| {
2165                    !ctx.loop_headers.contains(&cur)
2166                        || finally_wrap(gi)
2167                        || (!ctx.exc_retry_headers.contains(&cur)
2168                            && !self.cfg.blocks[cur].pred.iter().any(|&p| {
2169                                p != cur
2170                                    && ctx.idom.dominates(cur, p)
2171                                    && (self.cfg.blocks[p].end <= self.groups[gi].start
2172                                        || self.cfg.blocks[p].start >= self.groups[gi].end)
2173                            }))
2174                });
2175                if let Some(gi) = group_here {
2176                    let outer_universe = ctx.universe.clone();
2177                    let mut claimed = ctx.consumed.clone();
2178                    let try_region =
2179                        self.structure_try(gi, &ctx.universe, &outer_universe, &mut claimed, stop);
2180                    ctx.consumed = claimed;
2181                    parts.push(try_region);
2182                    let gend = self.groups[gi].end;
2183                    // structure_try absorbs a trailing terminator sitting at
2184                    // exactly g.end into the body (the protected-range areturn
2185                    // javac excludes; ALL its preds are body blocks). It is
2186                    // now claimed and lives INSIDE the try; letting the
2187                    // continuation search below pick it (it passes
2188                    // start >= gend + consumed + is_term) re-emits the body's
2189                    // own return after the try (ObjectStreamClass
2190                    // getDeclaredSUID: trailing `return Long.valueOf(...)`
2191                    // duplicated outside, real `return null` tail lost).
2192                    // A shared terminator at gend that the CATCH also copied
2193                    // (nestedTry) has a handler pred, is not absorbed, and
2194                    // must still be re-copied here — hence the all-preds-
2195                    // in-body mirror of the absorption rule.
2196                    let absorbed_tail = self.cfg.block_at(gend).filter(|&b| {
2197                        matches!(self.results[b].term, Term::Return(_) | Term::Throw(_))
2198                            && self.results[b].stmts.is_empty()
2199                            && !self.handler_group.contains_key(&b)
2200                            && !self.cfg.blocks[b].pred.is_empty()
2201                            && self.cfg.blocks[b]
2202                                .pred
2203                                .iter()
2204                                .all(|p| self.body_group.get(p) == Some(&gi))
2205                    });
2206                    // Handler-flow-only blocks (the handler's private tail,
2207                    // e.g. the synchronized monitorexit-rethrow `aload t;
2208                    // athrow`) are NOT shared method tails: the is_term
2209                    // exception below exists for tails the NORMAL path also
2210                    // reaches (nestedTry's lost return). Copying a
2211                    // handler-only pending-rethrow after the try leaks
2212                    // `throw <pending>;` into the normal flow (jdk26
2213                    // LambdaFormEditor.putInCache: 未报告的异常错误Throwable).
2214                    let hf_after = self.handler_flow_only(gi);
2215                    // Blocks are in ascending-start order. The scan STOPS at
2216                    // the first stop (barrier) block: when the block right
2217                    // after the span is the enclosing loop's exit, the flow
2218                    // LEAVES this scope there (the try body's Goto resolved
2219                    // to break) — continuing at some later non-stop block
2220                    // pulls post-exit code into the loop body, whose
2221                    // duplicated return then trips body_done and strands the
2222                    // exit's own tail (jdk26 Future.resultNow: the normal
2223                    // finally-if + `return result` after the retry loop went
2224                    // missing — 缺少返回语句).
2225                    let mut next: Option<usize> = None;
2226                    let dbg_next = crate::dbg_flag!("JCDC_DBG_SWF");
2227                    for nb in self.cfg.blocks.iter() {
2228                        if nb.start < gend {
2229                            continue;
2230                        }
2231                        if dbg_next {
2232                            eprintln!("NEXTSCAN gend={} nb={} start={} absorbed={} hf={} univ={} stop={} handler={} consumed={} term={}",
2233                                gend, nb.id, nb.start, Some(nb.id) == absorbed_tail,
2234                                hf_after.contains(&nb.id), ctx.universe.contains(&nb.id),
2235                                stop.contains(&nb.id), self.handler_group.contains_key(&nb.id),
2236                                ctx.consumed.contains(&nb.id),
2237                                matches!(self.results[nb.id].term, crate::ir::build::Term::Return(_) | crate::ir::build::Term::Throw(_)));
2238                        }
2239                        if Some(nb.id) == absorbed_tail || hf_after.contains(&nb.id) {
2240                            continue;
2241                        }
2242                        if !ctx.universe.contains(&nb.id) {
2243                            continue;
2244                        }
2245                        if stop.contains(&nb.id) {
2246                            break;
2247                        }
2248                        let is_term =
2249                            matches!(self.results[nb.id].term, Term::Return(_) | Term::Throw(_));
2250                        // A handler block is normally skipped (it belongs to
2251                        // the try's catch/finally), but a handler that is a
2252                        // shared return/throw is the method tail the finally
2253                        // copy jumps to — the normal (try-completes) path
2254                        // must still return it (nestedTry's lost return).
2255                        // THIS group's own handler is never that shared
2256                        // tail: its catch region already absorbed it, and
2257                        // re-walking it duplicated the handler as top-level
2258                        // statements after the try (jdk11
2259                        // ThreadedSeedGenerator.run: `Exception e = null;
2260                        // throw new InternalError(.., e);` after the
2261                        // catch-that-throws — 无法访问的语句).
2262                        if self.handler_group.contains_key(&nb.id)
2263                            && (!is_term || self.handler_group.get(&nb.id) == Some(&gi))
2264                        {
2265                            continue;
2266                        }
2267                        if ctx.consumed.contains(&nb.id) && !is_term {
2268                            continue;
2269                        }
2270                        next = Some(nb.id);
2271                        break;
2272                    }
2273                    match next {
2274                        // A consumed shared terminator right after the try is
2275                        // the method/region tail return that the catch also
2276                        // used; copy it inline so the normal (try-completes)
2277                        // path still returns (fixes nestedTry's lost return).
2278                        Some(nb) if ctx.consumed.contains(&nb) => {
2279                            parts.push(Region::CopyStmts { block: nb });
2280                            break;
2281                        }
2282                        Some(nb) => {
2283                            // Continue at the try's forward continuation even
2284                            // when it is not in this region's `reach` set: a
2285                            // try body reaches its tail through inlined/duplicated
2286                            // finally copies, so reachable_within (normal succ
2287                            // only) can miss the post-finally return block. The
2288                            // block is unconsumed and forward (start >= gend), so
2289                            // structuring it is monotone and recovers the tail
2290                            // return (nestedTry's `return sb.toString()`).
2291                            cur = nb;
2292                            last_via_goto = false;
2293                            continue;
2294                        }
2295                        None => break,
2296                    }
2297                }
2298            }
2299            let is_header =
2300                ctx.loop_headers.contains(&cur) && !self.handler_group.contains_key(&cur);
2301            if is_header {
2302                let members = ctx.loop_members.get(&cur).cloned().unwrap_or_default();
2303                // exits = EVERY member's out-edges leaving the loop: the
2304                // break-resolution set (a `break outer` from deep in the body
2305                // targets one of these; resolve_goto maps a Goto to the
2306                // OUTERMOST loop whose exits contain it -> labeled break).
2307                // A SWITCH-dispatch header never has a condition fall-out:
2308                // its out-of-loop target edges are per-case break stubs, so
2309                // extending exits cannot degrade a while-cond
2310                // classification (top-tested `while (i < n)` headers keep
2311                // their raw exits — String.contentEquals).
2312                let natural_follow_empty = matches!(
2313                    self.results[cur].term,
2314                    crate::ir::build::Term::Switch { .. }
2315                );
2316                let mut exits: Vec<usize> = Vec::new();
2317                for &m in members.iter() {
2318                    for &s in &self.cfg.blocks[m].succ {
2319                        if !members.contains(&s) && ctx.universe.contains(&s) && !exits.contains(&s)
2320                        {
2321                            exits.push(s);
2322                        }
2323                    }
2324                }
2325                // Bottom-tested loops ONLY (for(;;) / restart shapes): a
2326                // `break L` out of a deep switch compiles to a per-case
2327                // empty `goto TAIL` stub, so the member-boundary exits are
2328                // the stubs and the REAL continuation sits one hop behind
2329                // them — invisible to body_stop (the case region walks
2330                // through the stub and consumes the tail) and to the
2331                // post-loop continuation (stubs are consumed with
2332                // preds==header and filtered). See through pure-jump stubs
2333                // so exits name the semantic destination (jdk26
2334                // Pattern.sequence: `goto 609` stubs → the `if (head ==
2335                // null) return end; .. return head;` tail —
2336                // 缺少返回语句). Top-tested loops (String.contentEquals
2337                // `while (i < n)`) keep the raw exits: their header
2338                // fall-out exit drives the while-cond classification and
2339                // extending it degraded the loop to `while (true)` and
2340                // lost the post-loop return.
2341                if natural_follow_empty {
2342                    let mut extended: Vec<usize> = Vec::new();
2343                    for &x in exits.iter() {
2344                        let mut cur_x = x;
2345                        let mut guard = 0;
2346                        while matches!(self.results[cur_x].term, crate::ir::build::Term::Goto)
2347                            && self.results[cur_x].stmts.is_empty()
2348                            && self.cfg.blocks[cur_x].succ.len() == 1
2349                            && guard < 8
2350                        {
2351                            let n = self.cfg.blocks[cur_x].succ[0];
2352                            if members.contains(&n)
2353                                || !ctx.universe.contains(&n)
2354                                || ctx.loop_stack.contains(&n)
2355                                || ctx.loop_headers.contains(&n)
2356                            {
2357                                break;
2358                            }
2359                            cur_x = n;
2360                            guard += 1;
2361                        }
2362                        if !extended.contains(&cur_x) {
2363                            extended.push(cur_x);
2364                        }
2365                    }
2366                    exits = extended;
2367                }
2368                exits.sort_by_key(|e| self.cfg.blocks[*e].start);
2369                // natural_follow = the HEADER's own exits (the condition's
2370                // fall-out): where straight-line flow continues after the
2371                // loop. Other members' exits are body breaks and must NOT be
2372                // the continuation -- exits.first() over all members could be
2373                // a far-away early-return the body region never reaches,
2374                // silently dropping the post-loop tail (Integer.toString).
2375                let mut natural_follow: Vec<usize> = Vec::new();
2376                for &s in &self.cfg.blocks[cur].succ {
2377                    if !members.contains(&s) && ctx.universe.contains(&s) {
2378                        natural_follow.push(s);
2379                    }
2380                }
2381                // A top-tested Cond header's own fall-out is a LIVE normal
2382                // completion no matter what the body does: body_done (every
2383                // body path returns/continues) must not suppress it
2384                // (jdk11/17/26 AbstractPoller$Request.awaitResult: the
2385                // wait-retry body is all-continue, so the body_done veto
2386                // dropped the `!interrupted ? result : interrupt+result`
2387                // epilogue the condition falls into — 缺少返回语句 ×3
2388                // trees, latent behind OCSPResponse's FLOW mask). The
2389                // bottom-tested fallback below keeps the veto: for(;;)/
2390                // do-while exits are break landings the veto legitimately
2391                // owns (TempFileHelper.create's in-try areturn re-emission).
2392                let cond_exit_live = !natural_follow.is_empty()
2393                    && matches!(self.results[cur].term, Term::Cond { .. });
2394                if natural_follow.is_empty() {
2395                    // Bottom-tested loop (do-while): the header is the body
2396                    // entry whose only successor is inside the loop; the
2397                    // natural exit hangs off the condition member instead.
2398                    natural_follow = exits.clone();
2399                }
2400                natural_follow.sort_by_key(|e| self.cfg.blocks[*e].start);
2401                // Body: structure from the header; the loop's exits and the
2402                // enclosing stop bound it. The header is the body entry and is
2403                // NOT in the body stop (the back edge re-targets it -> Goto ->
2404                // `continue` at conversion).
2405                let mut body_stop: HashSet<usize> = stop.iter().copied().collect();
2406                body_stop.extend(exits.iter().copied());
2407                let header = cur;
2408                // Structure the body from the header, but drop the header from
2409                // loop_headers for the duration so the body region does not
2410                // re-detect it as a loop (infinite recursion). The back edge
2411                // (a body block whose succ is the header) hits the consumed
2412                // check -> Goto{header} -> `continue` at conversion.
2413                ctx.loop_headers.remove(&header);
2414                ctx.loop_stack.push(header);
2415                // Sync the walk-facing loops_stack so any walk-based sub-builder
2416                // reused inside the body (structure_try / structure_switch)
2417                // resolves a back-edge to this SESE loop header as a
2418                // `continue` (Goto{header}) instead of re-walking it as a new
2419                // nested loop (the catch-handler `while(true)` duplication).
2420                self.loops_stack.push(header);
2421                // The loop tail (back-edge source -> header) is reachable
2422                // from the header WITHOUT stepping on an exit only through
2423                // the body, so reachable_within(header, body_stop) always
2424                // contains every member; blocks of divergent shapes (a
2425                // pre-loop init guard whose branches rejoin after the loop,
2426                // Integer.toString blk9/10) are correctly NOT members. Pass
2427                // this exact set as the body sub-scope so nested copy_walks
2428                // (which bound their region by reachable_within) cannot lose
2429                // the post-loop tail.
2430                let body_scope = reachable_within(self.cfg, header, &body_stop);
2431                let body = self.sese_region_with_scope(header, &body_stop, body_scope, ctx);
2432                self.loops_stack.pop();
2433                ctx.loop_stack.pop();
2434                // A body that cannot complete normally (both arms of its
2435                // tail check inline the loop's terminator exits — the
2436                // finally-retry dual-throw shape, jdk11 ObjectInputStream
2437                // .readSerialData) makes the post-loop continuation
2438                // unreachable (无法访问的语句): emit the loop and stop.
2439                let handler_exits: Vec<usize> = exits
2440                    .iter()
2441                    .copied()
2442                    .filter(|e| self.is_handler(*e))
2443                    .collect();
2444                // Mirrors conv's break resolutions: a Goto to a loop exit
2445                // or to any block that cannot reach back to the header
2446                // converts to `break` — the loop is escapable.
2447                fn region_has_break_goto(
2448                    r: &Region,
2449                    s: &Structurer,
2450                    header: usize,
2451                    exits: &[usize],
2452                    members: &HashSet<usize>,
2453                ) -> bool {
2454                    let esc = |t: usize| {
2455                        if t == header || exits.contains(&t) {
2456                            return t != header;
2457                        }
2458                        // A jump onto another MEMBER is an internal
2459                        // landing (an inner construct's break/merge whose
2460                        // statements render mid-body — TempFileHelper
2461                        // .create's inner generatePath loop exit
2462                        // `goto 28`); it never leaves THIS loop, so it
2463                        // cannot make the loop completable.
2464                        if members.contains(&t) {
2465                            return false;
2466                        }
2467                        // A forward escape onto a shared return/throw
2468                        // terminator is NOT a break: conversion inlines
2469                        // the terminator at the arrival (if-follow inline
2470                        // or RawGoto term-copy), so the path completes
2471                        // abruptly right here (TempFileHelper.create's SE
2472                        // catch `if (dir != tmpdir) <goto throw-e>` — the
2473                        // old esc made body_done miss the non-completing
2474                        // for(;;) and the chain re-emitted an in-try
2475                        // areturn after the loop — 无法访问的语句 x2).
2476                        !matches!(
2477                            s.results[t].term,
2478                            crate::ir::build::Term::Return(_) | crate::ir::build::Term::Throw(_)
2479                        ) && !crate::structure::can_reach_cfg(s.cfg, t, header, 4096)
2480                    };
2481                    match r {
2482                        Region::Goto { target } => esc(*target),
2483                        Region::Seq(v) => v
2484                            .iter()
2485                            .any(|x| region_has_break_goto(x, s, header, exits, members)),
2486                        Region::If { then_r, else_r, .. } => {
2487                            region_has_break_goto(then_r, s, header, exits, members)
2488                                || region_has_break_goto(else_r, s, header, exits, members)
2489                        }
2490                        Region::Loop { body, .. } => {
2491                            region_has_break_goto(body, s, header, exits, members)
2492                        }
2493                        Region::Try { body, catches, .. } => {
2494                            region_has_break_goto(body, s, header, exits, members)
2495                                || catches.iter().any(|(_, _, cr)| {
2496                                    region_has_break_goto(cr, s, header, exits, members)
2497                                })
2498                        }
2499                        Region::Switch { cases, default, .. } => {
2500                            cases
2501                                .iter()
2502                                .any(|(_, cr)| region_has_break_goto(cr, s, header, exits, members))
2503                                || default
2504                                    .as_ref()
2505                                    .map(|d| region_has_break_goto(d, s, header, exits, members))
2506                                    .unwrap_or(false)
2507                        }
2508                        _ => false,
2509                    }
2510                }
2511                // A `break` inside the body means the loop CAN complete
2512                // normally: the post-loop follow is reachable through it
2513                // and must still be structured. region_terminates_ex is
2514                // Goto-blind (conservatively false for Goto parts), but a
2515                // body that absorbed an exit-landing return tail
2516                // (awaitTermination's `var7 = false; unlock; return var7;`
2517                // return-false path became the in-body continuation of the
2518                // header try) looks terminating while the state-test break
2519                // escapes — suppressing natural_follow there stranded the
2520                // return-true tail after the loop (缺少返回语句, jdk11/17
2521                // ThreadPoolExecutor.awaitTermination).
2522                // Loop-aware completion: a Goto back to the header is a
2523                // `continue` — abrupt, and it never lands past the loop —
2524                // so it counts as terminating HERE (the FAE retry catch of
2525                // TempFileHelper.create's for(;;); region_terminates_ex
2526                // cannot know the header).
2527                fn region_done_or_continues(
2528                    r: &Region,
2529                    s: &Structurer,
2530                    handler_exits: &[usize],
2531                    header: usize,
2532                ) -> bool {
2533                    match r {
2534                        Region::Goto { target } => {
2535                            *target == header
2536                                || crate::structure::region_terminates_ex(
2537                                    r,
2538                                    s.results,
2539                                    handler_exits,
2540                                )
2541                        }
2542                        Region::Seq(v) => v
2543                            .last()
2544                            .map(|x| region_done_or_continues(x, s, handler_exits, header))
2545                            .unwrap_or(false),
2546                        Region::If { then_r, else_r, .. } => {
2547                            region_done_or_continues(then_r, s, handler_exits, header)
2548                                && region_done_or_continues(else_r, s, handler_exits, header)
2549                        }
2550                        Region::Try { body, catches, .. } => {
2551                            region_done_or_continues(body, s, handler_exits, header)
2552                                && catches.iter().all(|(_, _, c)| {
2553                                    region_done_or_continues(c, s, handler_exits, header)
2554                                })
2555                        }
2556                        other => {
2557                            crate::structure::region_terminates_ex(other, s.results, handler_exits)
2558                        }
2559                    }
2560                }
2561                let body_done = region_done_or_continues(&body, self, &handler_exits, header)
2562                    && !region_has_break_goto(&body, self, header, &exits, &members);
2563                if crate::dbg_flag!("JCDC_DBG_SESE") {
2564                    eprintln!(
2565                        "BODYDONE header={} done={} term={} brk={} exits={:?} body={:#?}",
2566                        header,
2567                        body_done,
2568                        region_done_or_continues(&body, self, &handler_exits, header),
2569                        region_has_break_goto(&body, self, header, &exits, &members),
2570                        exits,
2571                        body
2572                    );
2573                }
2574                if is_header {
2575                    ctx.loop_headers.insert(header);
2576                }
2577                for &m in members.iter() {
2578                    ctx.consumed.insert(m);
2579                }
2580                let mut body = body;
2581                if !crate::dbg_flag!("JCDC_NO_MATEXIT") {
2582                    // The header's own out-of-member successors are the
2583                    // NATURAL exits (the while-cond fall-out / bottom-test
2584                    // exit): the parent region renders them ONCE after the
2585                    // Loop. Materializing them inside the body rotated
2586                    // while-cond loops into while(true)+copied-break
2587                    // (TempFileHelper/HttpURLConnection clinit churn).
2588                    let mut natural: HashSet<usize> = self.cfg.blocks[header]
2589                        .succ
2590                        .iter()
2591                        .copied()
2592                        .filter(|x| !members.contains(x) && *x != header)
2593                        .collect();
2594                    // SESE's computed natural_follow is ALSO parent-owned
2595                    // continuation (it may differ from the header's raw
2596                    // succs — bottom-tested/exit-derived follows): splicing
2597                    // it copied UnixPath.normalize's whole join-and-return
2598                    // continuation into a break arm (nf=[36], 缺少返回语句
2599                    // x2 trees).
2600                    natural.extend(natural_follow.iter().copied());
2601                    self.materialize_content_exits(
2602                        &mut body,
2603                        header,
2604                        &exits,
2605                        &members,
2606                        &natural,
2607                        &ctx.universe,
2608                        &ctx.loop_stack,
2609                        &ctx.loop_headers,
2610                        &ctx.top_groups,
2611                        stop,
2612                        &reach,
2613                        &ctx.consumed,
2614                        natural_follow.is_empty(),
2615                    );
2616                }
2617                parts.push(Region::Loop {
2618                    header,
2619                    body: Box::new(body),
2620                    members: members.clone(),
2621                    exits: exits.clone(),
2622                });
2623                // Continue after the loop at the header's natural exit (if it
2624                // is within this region's reach and not an enclosing stop).
2625                // A consumed candidate whose preds are ALL the header can
2626                // only have been emitted INSIDE the body (the header's
2627                // switch/if dispatched it — the restart loop's natural exits
2628                // ARE the case targets); hoisting it re-emits the first
2629                // case's body after the loop (jdk26 DecimalFormat
2630                // `Long l = ...` tail). A consumed candidate with other
2631                // preds is the genuine shared follow (Class.methodToString
2632                // `if (c) return X; else { loop }`) and keeps the loop-top
2633                // consumed policy below.
2634                let header_id = cur;
2635                // Two-level loop exits: `break LOOP` often compiles to a
2636                // dedicated `goto TAIL` stub, so the member-boundary exit
2637                // is the STUB, not the real continuation. When a stub exit
2638                // was consumed by the body walk (the switch case's Goto
2639                // resolved against it) and chains forward — through further
2640                // consumed single-succ stubs — to an unconsumed non-member
2641                // block, THAT block is the true post-loop follow (jdk26
2642                // Pattern.sequence: exits {goto-609 stubs, throw} all
2643                // consumed, the `if (head == null) return end; .. return
2644                // head;` tail stranded → 缺少返回语句).
2645                // Gate: ONLY when every candidate exit was consumed by the
2646                // body walk — the deep-switch break-stub shape (Pattern
2647                // .sequence: all exits are per-case `goto TAIL` stubs the
2648                // case regions absorbed, and the shared TAIL behind them is
2649                // the true continuation). A normal loop leaves its header
2650                // fall-out unconsumed; chain-walking it anyway degraded
2651                // String.contentEquals's `while (i < n)` classification and
2652                // dropped the post-loop `return true`.
2653                let all_consumed = !natural_follow.is_empty()
2654                    && natural_follow.iter().all(|f| ctx.consumed.contains(f));
2655                if crate::dbg_flag!("JCDC_DBG_SESE") && all_consumed {
2656                    eprintln!(
2657                        "CHAINWALK header={} nf={:?} succs={:?} cons49={:?}",
2658                        header_id,
2659                        natural_follow,
2660                        natural_follow
2661                            .iter()
2662                            .map(|f| self.cfg.blocks[*f].succ.clone())
2663                            .collect::<Vec<_>>(),
2664                        natural_follow
2665                            .iter()
2666                            .map(|f| ctx.consumed.contains(f))
2667                            .collect::<Vec<_>>()
2668                    );
2669                }
2670                let natural_follow: Vec<usize> = if all_consumed {
2671                    natural_follow
2672                        .into_iter()
2673                        .map(|x| {
2674                            let mut cur_x = x;
2675                            let mut guard = 0;
2676                            while ctx.consumed.contains(&cur_x)
2677                                && self.cfg.blocks[cur_x].succ.len() == 1
2678                                && guard < 16
2679                            {
2680                                let n = self.cfg.blocks[cur_x].succ[0];
2681                                if ctx.consumed.contains(&n)
2682                                    || stop.contains(&n)
2683                                    || members.contains(&n)
2684                                    || ctx.loop_stack.contains(&n)
2685                                    || ctx.loop_headers.contains(&n)
2686                                {
2687                                    break;
2688                                }
2689                                cur_x = n;
2690                                guard += 1;
2691                            }
2692                            cur_x
2693                        })
2694                        .collect::<Vec<_>>()
2695                } else {
2696                    natural_follow
2697                };
2698                let natural_follow = natural_follow
2699                    .into_iter()
2700                    .filter(|f| {
2701                        // A top-tested Cond header's own fall-out stays the
2702                        // continuation even when the body walk consumed it
2703                        // (AbstractPoller$Request.awaitResult: the epilogue
2704                        // rode into the body as the inner retry loop's
2705                        // follow; dropping it left the condition-fall path
2706                        // falling off the method — 缺少返回语句 ×3). The
2707                        // restart-loop case-target policy only owns
2708                        // unconditional (for(;;)/Goto) headers.
2709                        cond_exit_live
2710                            || !ctx.consumed.contains(f)
2711                            || !self.cfg.blocks[*f].pred.iter().all(|&p| p == header_id)
2712                    })
2713                    .collect::<Vec<_>>();
2714                if crate::dbg_flag!("JCDC_DBG_SESE") {
2715                    eprintln!(
2716                        "LOOPFOLLOW header={} exits={:?} natural_follow={:?} consumed_nf={:?}",
2717                        header_id,
2718                        exits,
2719                        natural_follow,
2720                        natural_follow
2721                            .iter()
2722                            .map(|f| ctx.consumed.contains(f))
2723                            .collect::<Vec<_>>()
2724                    );
2725                }
2726                if body_done && !cond_exit_live {
2727                    ctx.depth -= 1;
2728                    return match parts.len() {
2729                        0 => Region::Empty,
2730                        1 => parts.into_iter().next().unwrap(),
2731                        _ => Region::Seq(parts),
2732                    };
2733                }
2734                let follow_pick = match natural_follow.first().copied() {
2735                    // No `!consumed` gate: a follow already consumed by a
2736                    // sibling branch (the shared single-return block after
2737                    // `if (c) return X; else { loop }`, Class.methodToString)
2738                    // is handled by the loop-top consumed policy — a shared
2739                    // Return/Throw gets CopyStmts (inlined at this arrival),
2740                    // a header becomes `continue`, anything else copy_walk/
2741                    // Goto. Gating on !consumed silently dropped the else
2742                    // path's return (missing-return compile error; walk
2743                    // keeps the tail).
2744                    //
2745                    // body_done vetoes UNLESS the header's own condition
2746                    // fall-out is live (cond_exit_live): a top-tested
2747                    // while's condition exit is a normal completion even
2748                    // when every body path continues/returns
2749                    // (AbstractPoller$Request.awaitResult). The veto stays
2750                    // for the bottom-tested fallback's in-try areturn exits
2751                    // (the shared terminator CopyStmts policy re-emitted
2752                    // `return Files.createDirectory(..)` after the
2753                    // non-completing for(;;) — TempFileHelper.create
2754                    // 无法访问的语句 x2 trees).
2755                    Some(f)
2756                        if (!body_done || cond_exit_live)
2757                            && !stop.contains(&f)
2758                            && reach.contains(&f) =>
2759                    {
2760                        Some(f)
2761                    }
2762                    _ => None,
2763                };
2764                let follow_pick = if body_done && !cond_exit_live {
2765                    None
2766                } else {
2767                    follow_pick.or_else(|| {
2768                        // Stranded break landing: an exit some in-body
2769                        // `break L` targeted but neither the body nor any
2770                        // follow consumed (a guarded-pattern case body sits
2771                        // outside the switch dispatch — jdk26
2772                        // NumberFormat.format's `case BigInteger bi when
2773                        // bi.bitLength() < 64` break-L1 landed on nothing:
2774                        // natural_follow was empty and the bi.longValue()
2775                        // body block was never structured — 缺少返回语句 x2
2776                        // methods).
2777                        // Pre-stub-filter candidate set for the
2778                        // shared-collector test (see the walk-side twin in
2779                        // structure.rs next_after_loop).
2780                        let claim_cands: HashSet<usize> = exits
2781                            .iter()
2782                            .copied()
2783                            .filter(|e| {
2784                                !ctx.consumed.contains(e)
2785                                    && !stop.contains(e)
2786                                    && ctx.universe.contains(e)
2787                                    && reach.contains(e)
2788                                    && !self.is_handler(*e)
2789                                    && *e != header_id
2790                            })
2791                            .collect();
2792                        let mut cands: Vec<usize> = exits
2793                            .iter()
2794                            .copied()
2795                            .filter(|e| {
2796                                !ctx.consumed.contains(e)
2797                                && !stop.contains(e)
2798                                && ctx.universe.contains(e)
2799                                && reach.contains(e)
2800                                && !self.is_handler(*e)
2801                                && *e != header_id
2802                                // Continue-stub exits (statement-free jump
2803                                // chains back into an enclosing loop) are
2804                                // conditional break arms of the inner loop,
2805                                // already resolved inside the body — walking
2806                                // one as the continuation re-emits the jump
2807                                // unconditionally (jdk11
2808                                // FutureTask.removeWaiter `continue retry`
2809                                // stubs became an unconditional continue
2810                                // after the inner while — 无法访问的语句 on
2811                                // the tail return, x3 trees).
2812                                && !ctx.loop_stack.iter().any(|h| {
2813                                    h != e
2814                                        && self.is_stmt_free_chain_to_block(*e, *h)
2815                                        && !self.stub_chain_claims_continuation(
2816                                            *e,
2817                                            *h,
2818                                            &claim_cands,
2819                                        )
2820                                })
2821                            })
2822                            .collect();
2823                        cands.sort_by_key(|e| self.cfg.blocks[*e].start);
2824                        cands.first().copied()
2825                    })
2826                };
2827                match follow_pick {
2828                    Some(f) => {
2829                        cur = f;
2830                        continue;
2831                    }
2832                    None => {
2833                        // An exit that is an ENCLOSING loop's barrier must
2834                        // be materialized as a Goto (the labeled break of
2835                        // the enclosing loop); silently ending the body
2836                        // makes the inner loop's normal completion
2837                        // re-enter the outer (jdk11
2838                        // FutureTask.removeWaiter — see the walk-side
2839                        // twin in structure.rs).
2840                        if !body_done {
2841                            let barrier_exit = exits
2842                                .iter()
2843                                .copied()
2844                                .filter(|e| {
2845                                    stop.contains(e)
2846                                        && !ctx.loop_stack.contains(e)
2847                                        && ctx.universe.contains(e)
2848                                        && !self.is_handler(*e)
2849                                })
2850                                .min_by_key(|e| self.cfg.blocks[*e].start);
2851                            if let Some(e) = barrier_exit {
2852                                parts.push(Region::Goto { target: e });
2853                            }
2854                        }
2855                        break;
2856                    }
2857                }
2858            }
2859
2860            ctx.consumed.insert(cur);
2861            match self.results[cur].term.clone() {
2862                Term::Cond { cond } => {
2863                    let succs = self.cfg.blocks[cur].succ.clone();
2864                    if succs.len() != 2 {
2865                        parts.push(Region::Basic { block: cur });
2866                        match succs.first().copied() {
2867                            Some(n) => {
2868                                cur = n;
2869                                continue;
2870                            }
2871                            None => break,
2872                        }
2873                    }
2874                    let (fall, taken) = (succs[0], succs[1]);
2875                    // Follow = true immediate post-dominator; when None (the
2876                    // branches diverge to different terminals) fall back to
2877                    // convergent_merge, which recovers a shared loop tail
2878                    // (Legacy6 `if (a==2 && b==2) break outer;`) but REFUSES
2879                    // candidates dominating a branch target — ancestor
2880                    // confluentes like `if (A || B) fixup;` (Integer.toString)
2881                    // keep follow=None so the branches are walked naturally
2882                    // and the re-reached continuation is duplicated by
2883                    // copy_walk (walk-parity shape).
2884                    let follow = self
2885                        .sese_ipdom(ctx, cur)
2886                        .filter(|f| ctx.universe.contains(f) && !stop.contains(f))
2887                        .or_else(|| self.live_merge(ctx, &[taken, fall], stop))
2888                        // A follow that IS one of the branch targets only
2889                        // works when the OTHER target flows to it — that
2890                        // branch completes normally and falls through
2891                        // (empty branch). When the sibling instead exits
2892                        // (return/throw) or escapes to a stop, the target
2893                        // is shared-tail code: choosing it as follow
2894                        // leaves the tail unstructured after the sibling
2895                        // consumes it (Fin/Long$LongCache: lost
2896                        // `cache = archivedCache;` tail => final
2897                        // double-assign in the branch copy / "variable f
2898                        // might not have been initialized"). follow=None
2899                        // keeps the tail inside the branch (walk parity).
2900                        .filter(|f| {
2901                            ![taken, fall].contains(f)
2902                                || [taken, fall].iter().any(|&t| {
2903                                    t != *f
2904                                        && (stop.contains(&t)
2905                                            || self.reaches_within(ctx, t, *f, stop))
2906                                })
2907                        })
2908                        // A shared TERMINATOR as follow means some branch
2909                        // never completes normally — it must be a branch that
2910                        // flows to f within this region's stop set. When a
2911                        // target instead escapes to a stop (a jump OUT: the
2912                        // enclosing if-follow / loop exit), f post-dominates
2913                        // only through the other branch, and choosing it
2914                        // elides that branch's terminator as "natural
2915                        // fall-through" while re-emitting it AFTER the if —
2916                        // jdk17 String(byte[],int,int,Charset) lost the
2917                        // LATIN1 fast-path `return;` (goto 839 = shared
2918                        // ctor-exit) inside `else { assigns }`, double-
2919                        // assigning the final fields ("variable value might
2920                        // already have been assigned") and blocking every
2921                        // jdk17 corpus family. follow=None keeps the return
2922                        // inside the branch (walk-parity).
2923                        .filter(|f| {
2924                            !matches!(self.results[*f].term, Term::Return(_) | Term::Throw(_))
2925                                || [taken, fall].iter().all(|&t| {
2926                                    stop.contains(&t)
2927                                        || ctx.consumed.contains(&t)
2928                                        || self.reaches_within(ctx, t, *f, stop)
2929                                })
2930                        })
2931                        // The convergent shortcut result gets the same two
2932                        // screens as the live_merge result: a branch-target
2933                        // follow needs a sibling route (reaches) and a
2934                        // shared-terminator follow needs every target to
2935                        // flow to it. (Empirically census-neutral; the
2936                        // stronger all_routes_via variant of screen #1 is
2937                        // documented-FAILED in memory
2938                        // ocsp-sese-follow-diagnosis — it trades OCSPResponse
2939                        // against BasicImageReader/keytool codegen cliffs.)
2940                        .or_else(|| self.convergent_merge(ctx, &[taken, fall], stop))
2941                        .filter(|f| {
2942                            ![taken, fall].contains(f)
2943                                || [taken, fall].iter().any(|&t| {
2944                                    t != *f
2945                                        && (stop.contains(&t)
2946                                            || self.reaches_within(ctx, t, *f, stop))
2947                                })
2948                        })
2949                        .filter(|f| {
2950                            !matches!(self.results[*f].term, Term::Return(_) | Term::Throw(_))
2951                                || [taken, fall].iter().all(|&t| {
2952                                    stop.contains(&t)
2953                                        || ctx.consumed.contains(&t)
2954                                        || self.reaches_within(ctx, t, *f, stop)
2955                                })
2956                        });
2957                    // FALSE-MERGE RECONCILIATION against the walk-side
2958                    // picker: a branch-target follow is exactly the class
2959                    // immediate_postdom's successor-candidate rejection
2960                    // was hardened against (OCSPResponse's parked
2961                    // UNSPECIFIED block — its sibling's values[reason]
2962                    // route bypasses it into the post-flow; the walk
2963                    // renders the golden arm-exclusive copies via this
2964                    // rejection). When the walk picker disagrees with the
2965                    // SESE resolvers, defer to it: adopt its confluence
2966                    // (BasicImageReader's `map!=null && MAP_ALL` chain —
2967                    // the shared else-arm block is a false merge whose
2968                    // real confluence is the third-conjunct test) or
2969                    // reject to None when it finds no merge at all. The
2970                    // walk's own gates (is_fall, same_body, group-owned
2971                    // exemption, stmt-free stubs, depth-capped bypass
2972                    // probe, big-tail exception) come along verbatim.
2973                    let recon_enabled = !crate::dbg_flag!("JCDC_NO_RECON");
2974                    let follow = match follow {
2975                        Some(f)
2976                            if recon_enabled && (f == taken || f == fall)
2977                            // Switch-case territory keeps its own follow
2978                            // discipline: walk's picker REJECTS the case
2979                            // epilogue targets on purpose so each arm gets
2980                            // per-arrival try copies, while SESE parks them
2981                            // under the confluence bar (keytool doCommands'
2982                            // 28-pred TWR epilogue — deferring to the walk
2983                            // picker there re-armed the 12x copy storm,
2984                            // try 语句的代码过长 x525).
2985                            && self.switch_depth == 0
2986                            // Many-pred tail confluences are owned by the
2987                            // SESE copy/confluence-bar machinery for the
2988                            // same reason.
2989                            && !self.shared_tail_confluence(f)
2990                            // Only MULTI-PRED targets can be false merges:
2991                            // the pathology is arm CONTENT shared by both
2992                            // branch routes (OCSPResponse's UNSPECIFIED
2993                            // block has the two range-check arms as preds;
2994                            // BasicImageReader's channel-open else-arm has
2995                            // both conjunct tests). A SINGLE-pred taken
2996                            // target is an ordinary if-else-if chain arm
2997                            // entry whose parking IS the dispatch shape
2998                            // (keytool doCommands' command bodies — every
2999                            // reconciliation there, even pure-stub
3000                            // adoption, re-armed the epilogue copy storm).
3001                            && self.cfg.blocks[f].pred.len() >= 2
3002                            // AND the parked target must carry STATEMENTS:
3003                            // parking a statement-free test head is the
3004                            // healthy if-else-if chain flattening (keytool
3005                            // doGenCert's dispatch chain), not arm-content
3006                            // parking — there is nothing to cross.
3007                            && !self.results[f].stmts.is_empty()
3008                            // AND the sibling must actually BYPASS the
3009                            // parked target (a normal-completing route
3010                            // into its post-flow — the crossing that
3011                            // breaks the empty-arm contract). Without a
3012                            // bypass the parking is sound (every sibling
3013                            // route flows through the target and the empty
3014                            // arm falls into its emission correctly) and
3015                            // the SESE choice stands (keytool doPrintEntry
3016                            // dispatch parking).
3017                            && ![taken, fall].iter().any(|&t| {
3018                                t != f
3019                                    && (stop.contains(&t)
3020                                        || self.all_routes_via(ctx, t, f, stop))
3021                            }) =>
3022                        {
3023                            let w = self.postdom_ipdom(&ctx.universe, cur);
3024                            match w {
3025                                Some(x)
3026                                    if x != f
3027                                        && self.results[x].stmts.is_empty()
3028                                        && self.results[x].out_stack.is_empty()
3029                                        && self.cfg.blocks[x].succ.len() == 1
3030                                        && matches!(
3031                                            self.results[x].term,
3032                                            Term::Goto | Term::Fallthrough
3033                                        ) =>
3034                                {
3035                                    // Adopt only PURE GOTO/FALL STUB
3036                                    // confluentes: in the arm-content
3037                                    // parking pathology the false merge's
3038                                    // real continuation is the transparent
3039                                    // stub past the parked statements
3040                                    // (OCSPResponse cur=5: w=9, the
3041                                    // `goto 166` stub after the parked
3042                                    // UNSPECIFIED block — adopting it puts
3043                                    // the parked block in BOTH arms as
3044                                    // per-arrival copies, the golden
3045                                    // walk-parity shape). Statement-bearing
3046                                    // or test-head confluentes are
3047                                    // case-arm/dispatch entries whose
3048                                    // adoption dissolves the SESE
3049                                    // parked-arm architecture (keytool
3050                                    // doCommands: every broader adoption
3051                                    // re-armed the epilogue copy storm,
3052                                    // try 语句的代码过长 x524-540).
3053                                    if crate::dbg_flag!("JCDC_DBG_WPD") {
3054                                        eprintln!(
3055                                            "WPD cur={} taken={} fall={} f={} ADOPT-STUB w={}",
3056                                            cur, taken, fall, f, x
3057                                        );
3058                                    }
3059                                    if ctx.universe.contains(&x)
3060                                        && !stop.contains(&x)
3061                                        && !ctx.consumed.contains(&x)
3062                                        && !ctx.loop_stack.contains(&x)
3063                                        // The stub must not be a loop
3064                                        // CONTINUE trampoline (backward
3065                                        // goto into a header): adopting it
3066                                        // as the follow re-routes the chain
3067                                        // into loop machinery (keytool
3068                                        // doGenCert's `goto 5` back-edge
3069                                        // stub).
3070                                        && !self.cfg.blocks[x].succ.iter().any(|&s| {
3071                                            ctx.loop_headers.contains(&s)
3072                                                && self.cfg.blocks[s].start
3073                                                    <= self.cfg.blocks[x].start
3074                                        })
3075                                    {
3076                                        Some(x)
3077                                    } else {
3078                                        Some(f)
3079                                    }
3080                                }
3081                                // w == None (walk rejects every confluence),
3082                                // w == f, or w not a pure stub: keep the
3083                                // SESE choice — walk's rejection/selection
3084                                // cues its own guard-walk architecture, not
3085                                // SESE's parked-follow + confluence-bar one.
3086                                _ => Some(f),
3087                            }
3088                        }
3089                        other => other,
3090                    };
3091                    let mut bstop: HashSet<usize> = stop.iter().copied().collect();
3092                    if let Some(f) = follow {
3093                        bstop.insert(f);
3094                    }
3095                    let then_r = self.sese_region(taken, &bstop, ctx);
3096                    let else_r = self.sese_region(fall, &bstop, ctx);
3097                    // Value-diamond / ternary: both branches are pure single
3098                    // pushes that merge — reuse the builder's folded merge so
3099                    // the ternary is recovered (parity with walk).
3100                    let ternary = self.sese_ternary(cur, taken, fall, follow, &then_r, &else_r);
3101                    parts.push(Region::If {
3102                        block: cur,
3103                        cond,
3104                        then_r: Box::new(then_r),
3105                        else_r: Box::new(else_r),
3106                        follow,
3107                        ternary,
3108                    });
3109                    match follow {
3110                        // A follow already consumed by the case regions (the
3111                        // shared terminator tail each case absorbed/duplicated)
3112                        // must not continue here — that would re-emit it after
3113                        // the switch.
3114                        Some(f) if reach.contains(&f) && !ctx.consumed.contains(&f) => {
3115                            cur = f;
3116                            last_via_goto = false;
3117                            continue;
3118                        }
3119                        _ => break,
3120                    }
3121                }
3122                Term::Goto | Term::Fallthrough => {
3123                    parts.push(Region::Basic { block: cur });
3124                    last_via_goto = matches!(self.results[cur].term, Term::Goto);
3125                    match self.cfg.blocks[cur].succ.first().copied() {
3126                        Some(n) => {
3127                            cur = n;
3128                            continue;
3129                        }
3130                        None => break,
3131                    }
3132                }
3133                Term::Return(_) | Term::Throw(_) => {
3134                    parts.push(Region::Basic { block: cur });
3135                    break;
3136                }
3137                Term::Switch {
3138                    selector,
3139                    targets,
3140                    default: _,
3141                } => {
3142                    // Reuse the tuned switch region builder (case fall-through,
3143                    // per-case epilogues). Case bodies are structured by walk
3144                    // over the case sub-scope; `consumed` is passed as the
3145                    // claimed set so SESE and the switch share consumption.
3146                    //
3147                    // follow = ipdom, else the convergent merge of all case
3148                    // targets. Inside a loop the shared tail (`++i`, back-edge)
3149                    // post-dominates the dispatch only at the virtual exit, so
3150                    // ipdom is None; convergent_merge recovers the tail as the
3151                    // follow so every case `break`s to it and it is structured
3152                    // ONCE after the switch (EnumSwitch — otherwise the first
3153                    // case swallows the tail as `++i; continue` and the rest
3154                    // spin forever).
3155                    let succs = self.cfg.blocks[cur].succ.clone();
3156                    if crate::dbg_flag!("JCDC_DBG_GOTO") {
3157                        eprintln!(
3158                            "SWFOLLOW cur={} ipdom={:?} vx={} succs={:?} stop={:?}",
3159                            cur,
3160                            ctx.ipdom.get(&cur),
3161                            ctx.vx,
3162                            succs,
3163                            stop
3164                        );
3165                    }
3166                    let follow = self
3167                        .sese_ipdom(ctx, cur)
3168                        .filter(|f| !stop.contains(f))
3169                        // A switch inside a loop body whose cases all end in `break`
3170                        // merges at the loop increment (a body_stop exit),
3171                        // and a throwing default kills the plain ipdom —
3172                        // live_merge recovers it (ObjectStreamClass
3173                        // .computeFieldOffsets: fall-through cases and
3174                        // dangling break labels).
3175                        .or_else(|| self.live_merge(ctx, &succs, stop))
3176                        .or_else(|| self.convergent_merge(ctx, &succs, stop))
3177                        // Copied/shared-tail regions: the confluence lives
3178                        // in `stop` (enclosing flow owns it) — still the
3179                        // logical follow for case `break` resolution (jdk11
3180                        // Calendar.createCalendar catch-copy switch).
3181                        .or_else(|| self.switch_stop_confluence(cur, &ctx.universe, stop))
3182                        // Loop-tail epilogue: cases break the switch into a
3183                        // shared tail that flows back to the header; the
3184                        // forward resolvers refuse header-reaching paths
3185                        // (jdk26 Pattern.sequence lost the epilogue and the
3186                        // post-loop tail -> 缺少返回语句).
3187                        .or_else(|| self.loop_tail_switch_follow(ctx, cur, stop));
3188                    if crate::dbg_flag!("JCDC_DBG_SWF") {
3189                        eprintln!("SWF-RESOLVED cur={} follow={:?}", cur, follow);
3190                    }
3191                    // CROSSING follow: see the walk-side twin in
3192                    // structure.rs — a nested switch's stop-confluence
3193                    // belongs to an enclosing construct; region-level
3194                    // follow stays None so conversion binds the case-tail
3195                    // goto to the OWNER (labeled break), while `stop`
3196                    // still bounds the case walks at the confluence.
3197                    // Bindable exception (see switch_follow_bindable):
3198                    // when every route past the switch lands on the
3199                    // confluence anyway, rebuild with the follow so the
3200                    // arms get plain breaks (ClassPrinterImpl.toYaml/toXml
3201                    // 无法访问的语句 x2 trees).
3202                    let crossing = match follow {
3203                        Some(f) if stop.contains(&f) && self.switch_depth > 0 => Some(f),
3204                        _ => None,
3205                    };
3206                    let region_follow = match crossing {
3207                        Some(_) => None,
3208                        None => follow,
3209                    };
3210                    let mut claimed = ctx.consumed.clone();
3211                    self.switch_depth += 1;
3212                    let mut sw = self.structure_switch(
3213                        cur,
3214                        selector.clone(),
3215                        &targets,
3216                        &ctx.universe,
3217                        stop,
3218                        region_follow,
3219                        &ctx.top_groups,
3220                        &mut claimed,
3221                    );
3222                    if let Some(f) = crossing {
3223                        // See the walk-side twin: the post-switch
3224                        // continuation of THIS scope must already land on
3225                        // `f` (earlier parts abruptly complete, or the
3226                        // chain continues exactly at `f`).
3227                        let cont_dead = parts
3228                            .last()
3229                            .map(|p| crate::structure::region_terminates(p, self.results))
3230                            .unwrap_or(false);
3231                        let cont_is_f = reach.contains(&f);
3232                        let cont_via_case_break = self
3233                            .case_arm_ctx
3234                            .last()
3235                            .map(|&(head, ef, pat)| head == entry && pat && ef == Some(f))
3236                            .unwrap_or(false);
3237                        let bindable = (cont_dead || cont_is_f || cont_via_case_break)
3238                            && self.switch_follow_bindable(&sw, cur, &targets, f);
3239                        if crate::dbg_flag!("JCDC_DBG_SWF") {
3240                            eprintln!("SWBIND-SESE cur={} f={} cont_dead={} cont_is_f={} cont_case={} bindable={}",
3241                                cur, f, cont_dead, cont_is_f, cont_via_case_break, bindable);
3242                        }
3243                        if bindable {
3244                            let mut claimed2 = ctx.consumed.clone();
3245                            sw = self.structure_switch(
3246                                cur,
3247                                selector,
3248                                &targets,
3249                                &ctx.universe,
3250                                stop,
3251                                Some(f),
3252                                &ctx.top_groups,
3253                                &mut claimed2,
3254                            );
3255                            claimed = claimed2;
3256                        }
3257                    }
3258                    self.switch_depth -= 1;
3259                    ctx.consumed = claimed;
3260                    parts.push(sw);
3261                    if crate::dbg_flag!("JCDC_DBG_GOTO") {
3262                        eprintln!(
3263                            "SWCONT cur={} follow={:?} in_reach={:?} in_stop={:?} consumed={:?}",
3264                            cur,
3265                            follow,
3266                            follow.map(|f| reach.contains(&f)),
3267                            follow.map(|f| stop.contains(&f)),
3268                            ctx.consumed
3269                        );
3270                    }
3271                    match follow {
3272                        Some(f) if reach.contains(&f) => {
3273                            cur = f;
3274                            last_via_goto = false;
3275                            continue;
3276                        }
3277                        _ => break,
3278                    }
3279                }
3280                Term::Jsr | Term::Ret => {
3281                    parts.push(Region::Basic { block: cur });
3282                    break;
3283                }
3284            }
3285        }
3286        ctx.depth -= 1;
3287        match parts.len() {
3288            0 => Region::Empty,
3289            1 => parts.into_iter().next().unwrap(),
3290            _ => Region::Seq(parts),
3291        }
3292    }
3293
3294    /// Recover a folded value-diamond (ternary) at a Cond whose two branches
3295    /// are pure single-value pushes merging at `follow`. Mirrors walk's ternary
3296    /// detection so `x = c ? a : b;` is preserved. Returns None when not a
3297    /// pure diamond (the common control-flow case).
3298    fn sese_ternary(
3299        &self,
3300        cur: usize,
3301        taken: usize,
3302        fall: usize,
3303        follow: Option<usize>,
3304        then_r: &Region,
3305        else_r: &Region,
3306    ) -> Option<(Expr, Expr)> {
3307        let merge = follow?;
3308        // Both branches must be a single pure block that falls into `merge`
3309        // leaving exactly one value, and `merge` must be a builder-folded
3310        // diamond merge.
3311        if !self.diamond_merges.contains(&merge) {
3312            return None;
3313        }
3314        let pure_one = |r: &Region, blk: usize| -> Option<Expr> {
3315            match r {
3316                Region::Basic { block } if *block == blk => {
3317                    let res = &self.results[blk];
3318                    if res.stmts.is_empty() && res.out_stack.len() == 1 {
3319                        match &res.term {
3320                            Term::Fallthrough => Some(res.out_stack[0].clone()),
3321                            Term::Goto if self.cfg.blocks[blk].succ == vec![merge] => {
3322                                Some(res.out_stack[0].clone())
3323                            }
3324                            _ => None,
3325                        }
3326                    } else {
3327                        None
3328                    }
3329                }
3330                Region::Empty => {
3331                    // Branch jumps straight to the merge (empty side).
3332                    let res = &self.results[blk];
3333                    if res.stmts.is_empty() && res.out_stack.len() == 1 {
3334                        Some(res.out_stack[0].clone())
3335                    } else {
3336                        None
3337                    }
3338                }
3339                _ => None,
3340            }
3341        };
3342        let tv = pure_one(then_r, taken)?;
3343        let fv = pure_one(else_r, fall)?;
3344        let _ = cur;
3345        Some((tv, fv))
3346    }
3347}