← Back to Pull requests

codegen: shrink-wrap the GC shadow-stack frame #61596

Open
gbaraldi opened this pull request with 368 lines diff across 6 files
View on GitHub
gbaraldi gbaraldi commented on Apr 16, 2026 23:09 UTC
Author

This sadly doesn't do as much as I wanted it to because swiftself seems to interact badly with the backend. It forces spills of the swiftself arg even where it's not needed. So a second thing might be to disable swiftcc and just pass the ptls as a normal argument

Summary

The GC frame is allocated and pushed unconditionally at function entry.
For many functions it's only needed in a subsection of the CFG — the
cold branch of a diamond, a loop body that occasionally takes a rare
branch, or the throw path of a boundscheck — and the fast paths pay
the memset + shadow-stack push for nothing.

LateLowerGCFrame now picks a sink block (NCD of the BBs that actually
use the frame, hoisted out of loops) and places julia.push_gc_frame
there instead of at entry. Pops are inserted before in-sink returns
and on split CFG edges that leave the sink region. Functions that call
jl_enter_handler / jl_pop_handler[_noexcept] are skipped, since a
sunk push/pop must bracket the same enter/leave set.

FinalLowerGC keeps the backing alloca in the entry block (LLVM static
alloca) and only emits the memset plus llvm.lifetime.start at the
possibly-sunk call site. llvm.lifetime.end is emitted after each pop.

Modeled on LLVM's ShrinkWrap pass.

Test plan

  • FileCheck test test/llvmpasses/late-lower-gc-shrink-wrap.jl covers five patterns: early-exit diamond, loop preheader, boundscheck throw, hot-path regression guard, try/catch EH bailout.

  • Full bootstrap (sysimg) builds clean.

  • Smoke: exception-heavy stdlib paths (parse, dict with tuple values, generators) run correctly.
  • This pull request was written with the assistance of generative AI (Claude Opus 4.7).

    Diff: 368 lines (+348 / -20) across 6 files Reviewer: xal-0 Review duration: 296777m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.53) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.53 · 368 lines diff across 6 files
    0.53
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.354
    Real PR Conversation Timeline
    6 items
    gbaraldi gbaraldi commented on Apr 17, 2026 17:41 UTC
    Author

    @nanosoldier runtests()

    nanosoldier nanosoldier commented on Apr 18, 2026 14:17 UTC
    Contributor

    The package evaluation job you requested has completed - possible new issues were detected.
    The full report is available.

    <details><summary>Report summary</summary>

    ❗ Packages that crashed

    3 packages crashed only on the current version.

    - The process was aborted: 1 packages
    - An internal error was encountered: 1 packages
    - A segmentation fault happened: 1 packages

    452 packages crashed on the previous version too.

    ✖ Packages that failed

    17 packages failed only on the current version.

    - Package has test failures: 1 packages
    - Package tests unexpectedly errored: 1 packages
    - Tests became inactive: 2 packages
    - Test duration exceeded the time limit: 13 packages

    3918 packages failed on the previous version too.

    ✔ Packages that passed tests

    17 packages passed tests only on the current version.

    - Other: 17 packages

    5893 packages passed tests on the previous version too.

    ➖ Packages that were skipped altogether

    1412 packages were skipped on the previous version too.

    </details>

    gbaraldi gbaraldi commented on May 28, 2026 17:49 UTC
    Author

    Bump!

    xal-0 xal-0 commented on code on Jun 17, 2026 23:50 UTC
    Code Review
    src/llvm-late-gc-lowering.cpp:1
    @@ -2411,17 +2437,104 @@ void LateLowerGCFrame::PlaceRootsAndUpdateCalls(ArrayRef<int> Colors, int PreAss
     
         // Insert instructions for the actual gc frame
         if (MaxColor != -1 || !S.ArrayAllocas.empty() || !S.TrackedStores.empty()) {
    +        // Shrink-wrap: by default the frame goes in the entry block, but if all
    +        // blocks that actually use the frame share a common dominator outside
    +        // any loop, sink the alloc+push into that dominator so paths which
    +        // never use the frame pay nothing. Modeled on LLVM's ShrinkWrap pass.
    +        BasicBlock *EntryBB = &F->getEntryBlock();
    +        BasicBlock *SaveBB = EntryBB;
    +
    +        // TODO: sink inside EH regions. For v1 we bail when the function
    +        // has any runtime EH call, because a sunk push/pop must bracket the
    +        // same set of jl_enter_handler / jl_pop_handler[_noexcept] calls
    +        // (otherwise jl_eh_restore_state_noexcept's gcstack assertion fires).
    +        if (!functionHasEH(*F)) {
    +            if (!S.DT)
    +                S.DT = &GetDT();
    +            DominatorTree &DT = *S.DT;
    +            LoopInfo LI(DT);
    +
    +            BasicBlock *NCD = nullptr;
    +            auto addUser = [&](BasicBlock *BB) {
    +                NCD = NCD ? DT.findNearestCommonDominator(NCD, BB) : BB;
    +            };

    Claude Fable was mad about this failing an assertion if the input has any unreachable blocks in the CFG (it gives julia<lower_intrinsics;no_enable_early_simplifications;no_enable_scalar_optimizations;no_enable_loop_optimizations;no_enable_vector_pipeline> as an example of a pipeline that won't run SimplifyCFG first). I think we always run SimplifyCFG in any of the -On levels, so I'm fine leaving it either way.

    xal-0 xal-0 commented on code on Jun 18, 2026 00:02 UTC
    Code Review
    src/llvm-late-gc-lowering.cpp:1
    @@ -2411,17 +2437,104 @@ void LateLowerGCFrame::PlaceRootsAndUpdateCalls(ArrayRef<int> Colors, int PreAss
     
         // Insert instructions for the actual gc frame
         if (MaxColor != -1 || !S.ArrayAllocas.empty() || !S.TrackedStores.empty()) {
    +        // Shrink-wrap: by default the frame goes in the entry block, but if all
    +        // blocks that actually use the frame share a common dominator outside
    +        // any loop, sink the alloc+push into that dominator so paths which
    +        // never use the frame pay nothing. Modeled on LLVM's ShrinkWrap pass.
    +        BasicBlock *EntryBB = &F->getEntryBlock();
    +        BasicBlock *SaveBB = EntryBB;
    +
    +        // TODO: sink inside EH regions. For v1 we bail when the function
    +        // has any runtime EH call, because a sunk push/pop must bracket the
    +        // same set of jl_enter_handler / jl_pop_handler[_noexcept] calls
    +        // (otherwise jl_eh_restore_state_noexcept's gcstack assertion fires).
    +        if (!functionHasEH(*F)) {
    +            if (!S.DT)
    +                S.DT = &GetDT();
    +            DominatorTree &DT = *S.DT;
    +            LoopInfo LI(DT);
    +
    +            BasicBlock *NCD = nullptr;
    +            auto addUser = [&](BasicBlock *BB) {
    +                NCD = NCD ? DT.findNearestCommonDominator(NCD, BB) : BB;
    +            };
    +            for (auto &KV : S.BBStates) {
    +                const BBState &BBS = KV.second;
    +                if (!BBS.HasSafepoint)
    +                    continue;
    +                // LiveOut matters too: a value produced here and phi'd into
    +                // a successor may be slot-rooted.
    +                bool FrameLive = !BBS.LiveIn.empty() || !BBS.LiveOut.empty();
    +                if (!FrameLive) {
    +                    for (int SP = BBS.LastSafepoint; SP <= BBS.FirstSafepoint; ++SP) {
    +                        if (!S.LiveSets[SP].empty()) {
    +                            FrameLive = true;
    +                            break;
    +                        }
    +                    }
    +                }
    +                if (!FrameLive)
    +                    continue;
    +                addUser(const_cast<BasicBlock*>(KV.first));
    +            }
    +            // Special-ptr phis: the phi result can be a slot address carried
    +            // from a sink predecessor into a non-sink block.
    +            for (auto &BB : *F) {
    +                for (auto &PN : BB.phis()) {
    +                    if (isSpecialPtr(PN.getType())) {
    +                        addUser(&BB);
    +                        break;
    +                    }
    +                }
    +            }
    +            // ArrayAlloca users become users of the slot GEP; TrackedStore
    +            // sites store into slots. Both must be dominated by SaveBB. For
    +            // phi operands the relevant "user BB" is the incoming block,
    +            // not the phi's parent (the phi operand must be dominated by
    +            // the incoming predecessor's terminator).
    +            for (auto &KV : S.ArrayAllocas) {
    +                for (Use &U : KV.first->uses()) {
    +                    if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
    +                        addUser(PN->getIncomingBlock(U));
    +                    } else if (auto *I = dyn_cast<Instruction>(U.getUser())) {
    +                        addUser(I->getParent());
    +                    }
    +                }
    +            }
    +            for (auto &Store : S.TrackedStores)
    +                addUser(Store.first->getParent());

    This is a little sketchy to me, since what we actually need is to addUser every basic block containing a store or load to an alloca that has a tracked store. I had Fable make an attempt at creating a Julia reproducer for this but it flailed; I think we avoid it by chance. If we ever made the getfield with boundscheck off generate better code, I think it would be possible to get AllocOpt create an alloca used in this way and trigger the problem from Julia.

    Reviewers
    Assignees
    gbaraldi gbaraldi
    Labels
    risk: low confidence: 84.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52.7% (MEDIUM) · Higher = larger blast radius
    52.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.5% · Lower = rushed or shallow review
    84.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.2% · Safe to merge
    8.2%