Unverified Commit d574c6a6 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: skip codegen effects when tracing (#83095)

Skip these effects when in a tracing-only asset context, since we never codegen these modules and these effects cannot add any references (which is the only thing we are interested in this case):

- `Effect::FreeVar`, `Effect::TypeOf`, `Effect::ImportMeta`, `Effect::Unreachable`, `Effect::Member`
parent 2cc54081
......@@ -64,7 +64,7 @@ pub fn benchmark(c: &mut Criterion) {
None,
None,
);
let var_graph = create_graph(&program, &eval_context);
let var_graph = create_graph(&program, &eval_context, false);
let input = BenchInput {
program,
......@@ -90,7 +90,7 @@ struct BenchInput {
}
fn bench_create_graph(b: &mut Bencher, input: &BenchInput) {
b.iter(|| create_graph(&input.program, &input.eval_context));
b.iter(|| create_graph(&input.program, &input.eval_context, false));
}
fn bench_link(b: &mut Bencher, input: &BenchInput) {
......
......@@ -3,8 +3,8 @@ extern crate turbo_tasks_malloc;
use criterion::{criterion_group, criterion_main};
mod analyzer;
mod full;
mod references;
criterion_group!(analyzer_benches, analyzer::benchmark);
criterion_group!(full_benches, full::benchmark);
criterion_group!(full_benches, references::benchmark);
criterion_main!(analyzer_benches, full_benches);
......@@ -53,9 +53,11 @@ pub fn benchmark(c: &mut Criterion) {
.resolved_cell();
let mut cases = vec![];
for file in [
r#"packages/next/dist/compiled/babel-packages/packages-bundle.js"#,
r#"node_modules/.pnpm/react-dom@19.2.0-canary-03fda05d-20250820_react@19.2.0-canary-03fda05d-20250820/node_modules/react-dom/cjs/react-dom-client.development.js"#,
for (file, is_tracing) in [
(r#"packages/next/dist/compiled/babel-packages/packages-bundle.js"#, false),
(r#"packages/next/dist/compiled/babel-packages/packages-bundle.js"#, true),
(r#"node_modules/.pnpm/react-dom@19.2.0-canary-03fda05d-20250820_react@19.2.0-canary-03fda05d-20250820/node_modules/react-dom/cjs/react-dom-client.development.js"#, false),
(r#"node_modules/.pnpm/react-dom@19.2.0-canary-03fda05d-20250820_react@19.2.0-canary-03fda05d-20250820/node_modules/react-dom/cjs/react-dom-client.development.js"#, true),
] {
let module = EcmascriptModuleAsset::builder(
ResolvedVc::upcast(
......@@ -67,6 +69,7 @@ pub fn benchmark(c: &mut Criterion) {
EcmascriptInputTransforms::empty().to_resolved().await?,
EcmascriptOptions {
tree_shaking_mode: Some(TreeShakingMode::ReexportsOnly),
is_tracing,
..Default::default()
}
.resolved_cell(),
......@@ -76,21 +79,21 @@ pub fn benchmark(c: &mut Criterion) {
.to_resolved()
.await?;
cases.push((file, module));
cases.push((file.rsplit("/").next().unwrap(), if is_tracing { "tracing" } else { "full" }, module));
}
anyhow::Ok(cases)
}))
.unwrap();
let mut group = c.benchmark_group("full");
let mut group = c.benchmark_group("references");
group.warm_up_time(Duration::from_secs(1));
group.measurement_time(Duration::from_secs(20));
group.measurement_time(Duration::from_secs(10));
for case in cases {
for (file, param, module) in cases {
group.bench_with_input(
BenchmarkId::new("full", case.0),
BenchmarkId::new(file, param),
&BenchInput {
module: case.1,
module,
storage: tt.clone(),
},
bench_full,
......
......@@ -274,7 +274,7 @@ impl VarGraph {
/// You should use same [Mark] for this function and
/// [swc_ecma_transforms_base::resolver::resolver_with_mark]
pub fn create_graph(m: &Program, eval_context: &EvalContext) -> VarGraph {
pub fn create_graph(m: &Program, eval_context: &EvalContext, is_tracing: bool) -> VarGraph {
let mut graph = VarGraph {
values: Default::default(),
free_var_ids: Default::default(),
......@@ -283,6 +283,7 @@ pub fn create_graph(m: &Program, eval_context: &EvalContext) -> VarGraph {
m.visit_with_ast_path(
&mut Analyzer {
is_tracing,
data: &mut graph,
state: analyzer_state::AnalyzerState::new(),
eval_context,
......@@ -788,6 +789,8 @@ pub fn as_parent_path_skip(
}
struct Analyzer<'a> {
is_tracing: bool,
data: &'a mut VarGraph,
state: analyzer_state::AnalyzerState,
......@@ -1274,6 +1277,10 @@ impl Analyzer<'_> {
member_expr: &'ast MemberExpr,
ast_path: &AstNodePath<AstParentNodeRef<'r>>,
) {
if self.is_tracing {
return;
}
let obj_value = Box::new(self.eval_context.eval(&member_expr.obj));
let prop_value = match &member_expr.prop {
// TODO avoid clone
......@@ -1315,7 +1322,9 @@ impl Analyzer<'_> {
start_ast_path,
} => {
self.effects = prev_effects;
self.effects.push(Effect::Unreachable { start_ast_path });
if !self.is_tracing {
self.effects.push(Effect::Unreachable { start_ast_path });
}
always_returns = true;
}
EarlyReturn::Conditional {
......@@ -2008,8 +2017,9 @@ impl VisitAstPath for Analyzer<'_> {
}
// If this variable is unresolved, track it as a free (unbound) variable
if is_unresolved(ident, self.eval_context.unresolved_mark)
|| self.eval_context.force_free_values.contains(&ident.to_id())
if !self.is_tracing
&& (is_unresolved(ident, self.eval_context.unresolved_mark)
|| self.eval_context.force_free_values.contains(&ident.to_id()))
{
self.add_effect(Effect::FreeVar {
var: ident.sym.clone(),
......@@ -2043,13 +2053,16 @@ impl VisitAstPath for Analyzer<'_> {
// We are in some scope that will rebind this
return;
}
// Otherwise 'this' is free
self.add_effect(Effect::FreeVar {
var: atom!("this"),
ast_path: as_parent_path(ast_path),
span: node.span(),
in_try: is_in_try(ast_path),
})
if !self.is_tracing {
// Otherwise 'this' is free
self.add_effect(Effect::FreeVar {
var: atom!("this"),
ast_path: as_parent_path(ast_path),
span: node.span(),
in_try: is_in_try(ast_path),
})
}
}
fn visit_meta_prop_expr<'ast: 'r, 'r>(
......@@ -2057,7 +2070,7 @@ impl VisitAstPath for Analyzer<'_> {
expr: &'ast MetaPropExpr,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) {
if expr.kind == MetaPropKind::ImportMeta {
if !self.is_tracing && expr.kind == MetaPropKind::ImportMeta {
// MetaPropExpr also covers `new.target`. Only consider `import.meta`
// an effect.
self.add_effect(Effect::ImportMeta {
......@@ -2292,8 +2305,9 @@ impl VisitAstPath for Analyzer<'_> {
n: &'ast UnaryExpr,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
if n.op == UnaryOp::TypeOf {
if n.op == UnaryOp::TypeOf && !self.is_tracing {
let arg_value = Box::new(self.eval_context.eval(&n.arg));
self.add_effect(Effect::TypeOf {
arg: arg_value,
ast_path: as_parent_path(ast_path),
......@@ -2414,7 +2428,10 @@ impl Analyzer<'_> {
(Some(then), Some(r#else)) => ConditionalKind::IfElse { then, r#else },
(Some(then), None) => ConditionalKind::If { then },
(None, Some(r#else)) => ConditionalKind::Else { r#else },
(None, None) => unreachable!(),
(None, None) => {
// No effects, ignore
return;
}
};
self.add_effect(Effect::Conditional {
condition,
......
......@@ -3828,7 +3828,7 @@ mod tests {
None,
);
let mut var_graph = create_graph(&m, &eval_context);
let mut var_graph = create_graph(&m, &eval_context, false);
let var_cache = Default::default();
let mut named_values = var_graph
......
......@@ -200,6 +200,9 @@ pub struct EcmascriptOptions {
/// parsing fails. This is useful to keep the module graph structure intact when syntax errors
/// are temporarily introduced.
pub keep_last_successful_parse: bool,
/// Whether the modules in this context are never chunked/codegen-ed, but only used for
/// tracing.
pub is_tracing: bool,
}
#[turbo_tasks::value]
......
......@@ -214,6 +214,8 @@ impl AnalyzeEcmascriptModuleResult {
/// A temporary analysis result builder to pass around, to be turned into an
/// `Vc<AnalyzeEcmascriptModuleResult>` eventually.
pub struct AnalyzeEcmascriptModuleResultBuilder {
is_tracing: bool,
references: FxIndexSet<ResolvedVc<Box<dyn ModuleReference>>>,
esm_references: FxHashSet<usize>,
......@@ -234,8 +236,9 @@ pub struct AnalyzeEcmascriptModuleResultBuilder {
}
impl AnalyzeEcmascriptModuleResultBuilder {
pub fn new() -> Self {
pub fn new(is_tracing: bool) -> Self {
Self {
is_tracing,
references: Default::default(),
esm_references: Default::default(),
esm_local_references: Default::default(),
......@@ -289,7 +292,9 @@ impl AnalyzeEcmascriptModuleResultBuilder {
where
C: Into<CodeGen>,
{
self.code_gens.push(code_gen.into())
if !self.is_tracing {
self.code_gens.push(code_gen.into())
}
}
/// Sets the analysis result ES export.
......@@ -418,12 +423,6 @@ impl AnalyzeEcmascriptModuleResultBuilder {
}
}
impl Default for AnalyzeEcmascriptModuleResultBuilder {
fn default() -> Self {
Self::new()
}
}
struct AnalysisState<'a> {
handler: &'a Handler,
source: ResolvedVc<Box<dyn Source>>,
......@@ -511,10 +510,11 @@ pub async fn analyse_ecmascript_module_internal(
let options = raw_module.options;
let options = options.await?;
let import_externals = options.import_externals;
let is_tracing = options.is_tracing;
let origin = ResolvedVc::upcast::<Box<dyn ResolveOrigin>>(module);
let mut analysis = AnalyzeEcmascriptModuleResultBuilder::new();
let mut analysis = AnalyzeEcmascriptModuleResultBuilder::new(is_tracing);
let path = origin.origin_path().owned().await?;
// Is this a typescript file that requires analyzing type references?
......@@ -717,8 +717,10 @@ pub async fn analyse_ecmascript_module_internal(
let handler = Handler::with_emitter(true, false, Box::new(emitter));
let mut var_graph = {
let _span = tracing::info_span!("analyze variable values");
set_handler_and_globals(&handler, globals, || create_graph(program, eval_context))
let _span = tracing::info_span!("analyze variable values").entered();
set_handler_and_globals(&handler, globals, || {
create_graph(program, eval_context, is_tracing)
})
};
let span = tracing::info_span!("esm import references");
......@@ -784,8 +786,12 @@ pub async fn analyse_ecmascript_module_internal(
let (webpack_runtime, webpack_entry, webpack_chunks, mut esm_exports) =
set_handler_and_globals(&handler, globals, || {
// TODO migrate to effects
let mut visitor =
ModuleReferencesVisitor::new(eval_context, &import_references, &mut analysis);
let mut visitor = ModuleReferencesVisitor::new(
eval_context,
&import_references,
&mut analysis,
is_tracing,
);
// ModuleReferencesVisitor has already called analysis.add_esm_reexport_reference
// for any references in esm_exports
program.visit_with_ast_path(&mut visitor, &mut Default::default());
......@@ -1034,6 +1040,11 @@ pub async fn analyse_ecmascript_module_internal(
match effect {
Effect::Unreachable { start_ast_path } => {
debug_assert!(
!is_tracing,
"unexpected Effect::Unreachable in tracing mode"
);
analysis
.add_code_gen(Unreachable::new(AstPathRange::StartAfter(start_ast_path)));
}
......@@ -1054,12 +1065,14 @@ pub async fn analyse_ecmascript_module_internal(
macro_rules! inactive {
($block:ident) => {
analysis.add_code_gen(Unreachable::new($block.range.clone()));
if !is_tracing {
analysis.add_code_gen(Unreachable::new($block.range.clone()));
}
};
}
macro_rules! condition {
($expr:expr) => {
if !condition_has_side_effects {
if !is_tracing && !condition_has_side_effects {
analysis.add_code_gen(ConstantConditionCodeGen::new(
$expr,
condition_ast_path.to_vec().into(),
......@@ -1308,6 +1321,8 @@ pub async fn analyse_ecmascript_module_internal(
span,
in_try: _,
} => {
debug_assert!(!is_tracing, "unexpected Effect::FreeVar in tracing mode");
// FreeVar("require") might be turbopackIgnore-d
if !analysis_state
.link_value(
......@@ -1335,6 +1350,8 @@ pub async fn analyse_ecmascript_module_internal(
span,
in_try: _,
} => {
debug_assert!(!is_tracing, "unexpected Effect::Member in tracing mode");
// Intentionally not awaited because `handle_member` reads this only when needed
let obj = analysis_state.link_value(*obj, ImportAttributes::empty_ref());
......@@ -1407,6 +1424,7 @@ pub async fn analyse_ecmascript_module_internal(
ast_path,
span,
} => {
debug_assert!(!is_tracing, "unexpected Effect::TypeOf in tracing mode");
let arg = analysis_state
.link_value(*arg, ImportAttributes::empty_ref())
.await?;
......@@ -1417,6 +1435,7 @@ pub async fn analyse_ecmascript_module_internal(
span: _,
in_try: _,
} => {
debug_assert!(!is_tracing, "unexpected Effect::ImportMeta in tracing mode");
if analysis_state.first_import_meta {
analysis_state.first_import_meta = false;
analysis.add_code_gen(ImportMetaBinding::new(
......@@ -3195,6 +3214,7 @@ impl StaticAnalyser {
/// A visitor that walks the AST and collects information about the various
/// references a module makes to other parts of the code.
struct ModuleReferencesVisitor<'a> {
is_tracing: bool,
eval_context: &'a EvalContext,
old_analyser: StaticAnalyser,
import_references: &'a [ResolvedVc<EsmAssetReference>],
......@@ -3210,8 +3230,10 @@ impl<'a> ModuleReferencesVisitor<'a> {
eval_context: &'a EvalContext,
import_references: &'a [ResolvedVc<EsmAssetReference>],
analysis: &'a mut AnalyzeEcmascriptModuleResultBuilder,
is_tracing: bool,
) -> Self {
Self {
is_tracing,
eval_context,
old_analyser: StaticAnalyser::default(),
import_references,
......@@ -3269,8 +3291,10 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
export: &'ast ExportAll,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
if !self.is_tracing {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
}
export.visit_children_with_ast_path(self, ast_path);
}
......@@ -3344,8 +3368,10 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
}
}
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
if !self.is_tracing {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
}
export.visit_children_with_ast_path(self, ast_path);
}
......@@ -3393,8 +3419,10 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
}
}
};
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
if !self.is_tracing {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
}
export.visit_children_with_ast_path(self, ast_path);
}
......@@ -3411,8 +3439,10 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
Liveness::Constant,
),
);
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
if !self.is_tracing {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
}
export.visit_children_with_ast_path(self, ast_path);
}
......@@ -3443,8 +3473,10 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
// ignore
}
}
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
if !self.is_tracing {
self.analysis
.add_code_gen(EsmModuleItem::new(as_parent_path(ast_path).into()));
}
export.visit_children_with_ast_path(self, ast_path);
}
......@@ -3489,7 +3521,9 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
}
}
}
self.analysis.add_code_gen(EsmModuleItem::new(path));
if !self.is_tracing {
self.analysis.add_code_gen(EsmModuleItem::new(path));
}
}
fn visit_var_declarator<'ast: 'r, 'r>(
......
......@@ -89,6 +89,7 @@ async fn node_file_trace_operation(
// Environment is not passed in order to avoid downleveling JS / CSS for
// node-file-trace.
environment: None,
is_tracing: true,
..Default::default()
}
.cell(),
......
......@@ -709,6 +709,7 @@ async fn externals_tracing_module_context(
// Environment is not passed in order to avoid downleveling JS / CSS for
// node-file-trace.
environment: None,
is_tracing: true,
..Default::default()
}
.cell(),
......
......@@ -150,6 +150,7 @@ impl ModuleOptions {
execution_context,
tree_shaking_mode,
keep_last_successful_parse,
is_tracing,
..
} = *module_options_context.await?;
......@@ -203,6 +204,7 @@ impl ModuleOptions {
ignore_dynamic_requests,
extract_source_map: matches!(ecmascript_source_maps, SourceMapsType::Full),
keep_last_successful_parse,
is_tracing,
..Default::default()
};
let ecmascript_options_vc = ecmascript_options.resolved_cell();
......
......@@ -174,6 +174,10 @@ pub struct ModuleOptionsContext {
/// context paths. The first matching is used.
pub rules: Vec<(ContextCondition, ResolvedVc<ModuleOptionsContext>)>,
/// Whether the modules in this context are never chunked/codegen-ed, but only used for
/// tracing.
pub is_tracing: bool,
pub placeholder_for_future_extensions: (),
}
......
......@@ -368,6 +368,7 @@ async fn node_file_trace_operation(
// Environment is not passed in order to avoid downleveling JS / CSS for
// node-file-trace.
environment: None,
is_tracing: true,
..Default::default()
}
.cell(),
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment