Skip to content

fix: drop top-level statements made dead by imported constants before chunk linking - #11053

Merged
hyfdev merged 4 commits into
rolldown:mainfrom
elliott-with-the-longest-name-on-github:elliott/fix-dead-cross-chunk-export
Nov 7, 2026
Merged

hyfdev merged 4 commits into
rolldown:mainfrom
elliott-with-the-longest-name-on-github:elliott/fix-dead-cross-chunk-export

Conversation

@elliott-with-the-longest-name-on-github

@elliott-with-the-longest-name-on-github elliott-with-the-longest-name-on-github commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Refs #6939

If a top-level statement is only dead because of an imported constant, it still pulls its dependencies into the output. For example, if (DEV) warn() where DEV = false comes from another module. The scanner can't see through imports, so it marks the statement as having side effects. Tree-shaking then includes it and demands warn. The finalizer later inlines DEV and the minifier's DCE deletes the call, but by then chunk linking is done. If warn lives in a shared chunk, it has already been exported from that chunk. That export is a DCE root, so the dead function survives. With the default inlineConst single pass, nothing re-checked these statements after linking.

This adds refine_constant_statement_side_effects, which runs in link() right after cross_module_optimization and before include_statements. It re-analyzes a top-level statement only if the statement:

  • still has side effects,
  • has no import records, and
  • references a linked immutable ESM constant.

If the re-analysis proves the statement effect-free, its side-effect flag is cleared. The pass runs in parallel per module, and the filter means most statements are never re-walked. Details:

  • A known-false condition skips its branch, but the condition itself is still analyzed. So if ((sideEffect(), DEV)) keeps sideEffect().
  • Linked constants report their value type to Oxc via value_type_for_reference_id. This lets Oxc prove that `${CONST}` and 'x' + CONST can't run user code or throw, while mutable bindings and objects with custom toString stay effectful.
  • Substitution-free template literals (export const x = `...`) are now collected as string constants during scanning. This is what [Bug]: propagate value type information in cross-chunk tree-shaking #6939 needs. It also means these values are now inlined like other string constants, so it's a small behavior change on its own.
  • The pass only clears effects, never adds them. Statements with import records are skipped, because import lowering is the only post-scan pass that forces side effects today. This invariant is documented in the code and in internal-docs/linking/reference-needed-symbols/implementation.md.

This only covers top-level statements. Dead branches inside live functions (function f() { if (DEV) warn() }) still keep warn, because the enclosing declaration is included and so are its references. Fixing that means removing references from retained statements, which is only sound if the finalizer is guaranteed to delete the matching branch. Today that branch removal only happens in minifier DCE, which can be turned off (with minify: false, if (false) warn(); is emitted as-is). Getting this wrong leaves a reference to a symbol that is no longer imported or declared, so it's a follow-up. Also not handled: if (DEV) import('./x') (has an import record), if (ns.DEV), and ??.

Tests:

  • inline_const/dead_shared_chunk_export: if, &&, ||, ternary, and namespace-call forms across a shared chunk. Includes a multi-pass variant, an all mode variant, and a treeshake: false variant.
  • inline_const/cross_chunk_value_type ([Bug]: propagate value type information in cross-chunk tree-shaking #6939): template interpolation and string concatenation of an imported constant.
  • inline_const/constant_effects_safety: effectful condition tests, live else branches, mutable let exports, and objects with custom coercion stay intact.

The smart_mode_import_removal snapshot also changes: the empty //#region markers are gone now that the dead if (foo) statement is dropped.

@codspeed

codspeed Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 4 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing elliott-with-the-longest-name-on-github:elliott/fix-dead-cross-chunk-export (f6055e7) with main (73a0b45)

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Take main's version of every conflicting file.
Main's `refine_stmt_side_effects_with_imported_constants` (rolldown#10825) re-checks statements that read imported constants, and main already collects template-literal constants and their value types.
So this drops the `refine_constant_statement_side_effects` pass, its `smart_mode_import_removal` snapshot change and its section in `internal-docs/linking/reference-needed-symbols/implementation.md`.
…e-effect analysis

The analysis skips the branch of an `if`, `? :`, `&&` or `||` whose test is a known constant or its negation.
The test is still analyzed, so `if ((effect(), DEV))` keeps `effect()`.
`ConstantTrustFinder` skips the same branches, so a global call there does not force the analysis without constants.
The link-time constant lookup also accepts an `export default <expression>` value, which no code can assign.
@hyfdev hyfdev self-assigned this Nov 7, 2026
@hyfdev

hyfdev commented Nov 7, 2026

Copy link
Copy Markdown
Member

Thanks, and sorry this waited so long!

Since #10825, main re-checks these statements in refine_stmt_side_effects_with_imported_constants.

So I merged main into this branch and moved your branch handling into that analysis:

  • It skips the branch of an if, ? :, && or || whose test is a known constant or its negation.
  • Its constant lookup now also accepts export default values, for your named.js cases.
  • The template-literal and value-type parts were already on main, so I dropped them.

Your three tests pass with the same output.

A module whose only code is if (DEV) console.warn() also no longer leaves an empty chunk.

@netlify

netlify Bot commented Nov 7, 2026

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit 0d076a8
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6aeeefa8f55a7f7eda2422d5
😎 Deploy Preview https://deploy-preview-11053--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Nov 7, 2026

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs canceled.

Name Link
🔨 Latest commit f6055e7
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6aeeefceabf027ea464002c5

@hyfdev hyfdev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@hyfdev
hyfdev merged commit 0a42a68 into rolldown:main Nov 7, 2026
36 checks passed
This was referenced Nov 9, 2026
shulaoda added a commit that referenced this pull request Nov 9, 2026
## [1.3.1] - 2026-11-09

### 🚀 Features

- inline-common-chunks: inline chunks using `import.meta.ROLLDOWN_FILE_URL_*` (#11543) by @mattlewis92

### 🐛 Bug Fixes

- cli: apply --environment before loading the binding (#11553) by @Brooooooklyn
- rolldown_plugin_vite_resolve: escape module names in generated error stubs (#11584) by @sapphi-red
- add the code location to transform logs and errors at position 0 (#11568) by @chinmayajha
- match sticky regexes only at the start of the string (#11569) by @chinmayajha
- iife/umd: skip namespace markers when the entry has no exports (#11567) by @lazerg
- keep a declaration's name when it clashes with an external import (#11052) by @Nic-Polumeyv
- drop top-level statements made dead by imported constants before chunk linking (#11053) by @elliott-with-the-longest-name-on-github
- keep `this.resolve` custom options apart for overlapping calls (#11505) by @wan9chi
- transform: reuse TsconfigCache's answer when no tsconfig owns the file (#11265) by @sarankumar1325
- treat top-level `this` of a required module without module syntax as its exports (#11271) by @sarankumar1325
- keep side effects of a module whose exported constant is inlined (#11440) by @hyfdev
- leave same-chunk dynamic imports out of `dynamicImports` (#11156) by @kkkhs

### 🚜 Refactor

- prepend transferred imports as AST fragments (#11464) by @Dunqing

### 📚 Documentation

- show `vp` first in setup commands (#11503) by @IWANABETHATGUY

### ⚡ Performance

- incremental: reuse link-time facade symbols across rebuilds (#11542) by @mattlewis92
- incremental: share module sourcemap chains across cache clones (#11540) by @mattlewis92
- chunk_optimizer: answer runtime-merge reachability from one chunk-level graph (#11541) by @mattlewis92
- send only changed chunk properties back to Rust from output hooks (#11488) by @anonrig

### 🧪 Testing

- remove review fixtures committed by mistake in #11052 (#11574) by @hyfdev
- wasi: cover raw context destruction (#11561) by @Brooooooklyn

### ⚙️ Miscellaneous Tasks

- deps: update rust crates (#11573) by @renovate[bot]
- deps: update mimalloc-safe to 0.1.70 (#11589) by @shulaoda
- renovate: update GitHub Actions that are pinned to a commit (#11583) by @hyfdev
- skip Playwright browser downloads in Prepare Release (#11579) by @shulaoda
- pin the rolldown crates to exact versions of each other on release (#11577) by @shulaoda
- update `CodSpeedHQ/action` to v5.6.3 for Ubuntu 26.04 (#11575) by @hyfdev
- remove stale entries from `.typos.toml` (#11571) by @iiio2
- pick the Prepare Release target branch from the version (#11525) by @shulaoda
- run every OS on pushes to maintenance branches (#11520) by @shulaoda
- rebase maintenance Vite branches onto their Vite minor (#11515) by @shulaoda
- run CI on pushes to maintenance branches (#11516) by @shulaoda
- support patch releases from maintenance branches (#11393) by @shulaoda

### ❤️ New Contributors

* @chinmayajha made their first contribution in [#11568](#11568)
* @lazerg made their first contribution in [#11567](#11567)
* @elliott-with-the-longest-name-on-github made their first contribution in [#11053](#11053)
* @sarankumar1325 made their first contribution in [#11265](#11265)
* @anonrig made their first contribution in [#11488](#11488)
* @kkkhs made their first contribution in [#11156](#11156)

Co-authored-by: shulaoda <[email protected]>
IWANABETHATGUY added a commit that referenced this pull request Nov 11, 2026
…unk linking (#11059)

Keeping a function currently keeps all of its references, including
references inside dead branches. For example, `function f() { if (DEV)
warn() }`, where `DEV = false` comes from another module, still demands
`warn`. If `warn` lives in a shared chunk, chunk linking exports it
before the minifier removes the call. That export then becomes a DCE
root, leaving an unused shared chunk in the output. This is the
function-body follow-up described in #11053.

This adds `prune_constant_branches` after cross-module constant
discovery and before statement inclusion. It removes references used
exclusively in known-dead branches and records the branch decisions for
the finalizer. The finalizer deletes those same branches before
rewriting their references, so this works with `minify: false` too.
Removing only the dependencies would leave emitted code referring to
symbols that are no longer imported or declared.

Details:
- Handles `if`, ternaries, and unreachable right-hand sides of `&&`,
`||`, and `??`.
- Preserves condition evaluation, including effects and exceptions, and
preserves indirect-call semantics when simplifying expression callees.
- Revisits only statements referencing known constants, in parallel per
module. Synthetic dependencies and symbols with reachable uses stay
intact.
- Conservatively skips statements containing import records, dead `if`
branches with hoisted declarations, and modules containing direct
`eval`. CommonJS property constants, reassigned bindings, and
namespace-member conditions are not used to decide branches.

The two-entry diagnostic-helper reproduction now emits only the two
entry chunks, with or without minification. Regression tests cover that
case, namespace helper references, disabled tree shaking/inlining, and
safety cases for effects, exceptions, mutable exports, shadowing, block
scope, hoisting, and indirect calls.

Validation: 2,020 integration tests and 105 unit tests passed; Clippy
with all features and formatting checks passed. Test262 was excluded
because its submodule wasn’t checked out.

---------

Co-authored-by: IWANABETHATGUY <[email protected]>
Co-authored-by: Jerry Zhao <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants