From a174fff4576ef850be57172869d1195b71cb595f Mon Sep 17 00:00:00 2001 From: Naman Bajpai Date: Wed, 25 Nov 2026 09:21:55 +0000 Subject: [PATCH 1/2] driver: -j with --legacy-codegen checks in parallel, then the AST code generator makes the MLIR `vxc -j N --legacy-codegen` stopped with "-j does not support --legacy-codegen yet". The parallel compile in execute_parallel gave its work only to the flat code generator. So a RUN line with -j could not run on the AST code generator, and the parity mode skipped those lines. Now -j with --legacy-codegen runs the parallel frontend. The new check_modules_for_ast_codegen in src/pipeline.rs then builds the modules in the form that the sequential driver gives to MeliorGenerator. It takes the generic instances in the order of the sequential checks, keeps the first copy of each by name and removes comptime functions. The MLIR is the same bytes as a normal --legacy-codegen compile. The checker names closures, tasks and vec! values with a counter, such as Closure_1. Each parallel check starts the counter again, so two functions would get the same name. A program that has one goes to the sequential driver, with a note on stderr. The parity mode no longer skips -j lines. Four -j fixtures checked text that only the flat code generator writes. Two now end with `# flat-codegen`, and two use -DAG checks. Fixes: #3139 Co-Authored-By: Claude Opus 5.5 --- src/driver.rs | 99 ++++++++--- src/hir/check/tasks.rs | 6 + src/pipeline.rs | 161 +++++++++++++++++- .../jobs_refuses_a_flag_it_cannot_honour.vx | 8 +- ..._compiles_through_the_parallel_frontend.vx | 4 +- ...jobs_falls_back_outside_the_flat_subset.vx | 4 +- ...put_does_not_depend_on_the_thread_count.vx | 4 +- .../jobs_warns_once_when_it_falls_back.vx | 2 +- .../jobs_with_legacy_codegen_and_closures.vx | 37 ++++ ...ith_legacy_codegen_gives_the_same_bytes.vx | 76 +++++++++ tests/integration_test/compile_test.rs | 15 +- 11 files changed, 366 insertions(+), 50 deletions(-) create mode 100644 tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx create mode 100644 tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx diff --git a/src/driver.rs b/src/driver.rs index fb88beb43..1dc8f298f 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -527,7 +527,8 @@ impl CompilerDriver { self.execute_vx_pipeline(main_file, &filename, &mlir_args) } - /// `-j N`: the parallel frontend, then the same backend as the sequential path. + /// `-j N`: the parallel frontend, then the same backend as the sequential path. The flat code + /// generator makes the module, or the AST code generator with `--legacy-codegen`. /// /// Returns `Ok(None)` when the parallel frontend cannot take the program, after saying why on /// stderr; the caller then runs the sequential driver, which takes everything. A flag whose @@ -541,7 +542,6 @@ impl CompilerDriver { jobs: usize, ) -> Result, String> { let unsupported = [ - (self.options.legacy_codegen, "--legacy-codegen"), (self.options.link_interface.is_some(), "--link-interface"), ( self.options.diagnostics_json.is_some(), @@ -577,7 +577,7 @@ impl CompilerDriver { Self::widen_heap_growth(); } - let compile = || -> Result)>, String> { + let compile = || -> Result)>, String> { let (mut programs, interfaces) = self.load_modules(filename, sched)?; crate::hir::check::audit::mark_refused_packages( &mut programs, @@ -594,23 +594,42 @@ impl CompilerDriver { let host_arch = Self::host_arch_of(programs.iter()); // Only the file the user named reports its diagnostics, matching what the // sequential driver keeps from its own import pass. - let reported = - crate::pipeline::Reported::OnlyEntry(self.module_loader().root_name(filename)); + let entry = self.module_loader().root_name(filename); // A failed check ends with the line the sequential driver prints, with the file. + let failed = |e| match e { + crate::pipeline::PipelineError::Failed { count, .. } => format!( + "Semantic check failed on '{}': {} error(s) emitted", + filename, count + ), + other => other.to_string(), + }; + if self.options.legacy_codegen { + let checked = crate::pipeline::check_modules_for_ast_codegen( + programs, + sched, + intern_mode, + self.options.auto_schedule_levels(), + entry, + ) + .map_err(failed)?; + let Some(checked) = checked else { + eprintln!( + "[parallel-frontend] the program has a closure, a task or a `vec!` value. \ + The names the checks give them depend on the order of the checks, so the \ + sequential driver compiles the program" + ); + return Ok(None); + }; + return Ok(Some((Frontended::Ast(Box::new(checked)), host_arch))); + } let text = crate::pipeline::compile_modules_mlir_in( programs, sched, intern_mode, self.options.auto_schedule_levels(), - reported, + crate::pipeline::Reported::OnlyEntry(entry), ) - .map_err(|e| match e { - crate::pipeline::PipelineError::Failed { count, .. } => format!( - "Semantic check failed on '{}': {} error(s) emitted", - filename, count - ), - other => other.to_string(), - })?; + .map_err(failed)?; let Some(text) = text else { // Worded so it cannot be mistaken for the flat emitter's own decline, which // `flat_corpus_sweep` classifies a program by: the two say different things @@ -622,7 +641,7 @@ impl CompilerDriver { ); return Ok(None); }; - Ok(Some((text, host_arch))) + Ok(Some((Frontended::Mlir(text), host_arch))) }; let compiled = if jobs == 1 { compile() @@ -633,11 +652,24 @@ impl CompilerDriver { .map_err(|e| format!("could not start {jobs} compiler threads: {e}"))?; pool.install(compile) }; - let Some((text, host_arch)) = compiled? else { + let Some((frontended, host_arch)) = compiled? else { return Ok(None); }; eprintln!("[parallel-frontend] emitted module with -j {jobs}"); - self.emit_from_mlir_text(&text, host_arch, filename, main_file, mlir_args) + match frontended { + Frontended::Mlir(text) => { + self.emit_from_mlir_text(&text, host_arch, filename, main_file, mlir_args) + } + Frontended::Ast(checked) => { + let (main_ast, module_syntaxes) = *checked; + let context = self.backend_context(); + let module = crate::intern_mode::timed("codegen", || { + self.ast_module(&context, &main_ast, &module_syntaxes) + })?; + self.lower_and_emit(&context, module, host_arch, filename, main_file, mlir_args) + .map(Some) + } + } } /// Under `VX_PIPELINE_PHASES`, the per-phase wall clock of this compile, one line per phase @@ -1686,21 +1718,30 @@ impl CompilerDriver { if !self.options.legacy_codegen { eprintln!("[flat-codegen] program outside the flat subset; using the AST path"); } - let mut codegen = - MeliorGenerator::new(&context, monomorphized_ast.module_path.to_string()); - codegen.emit_seam_certs = self.options.emit_seam_certs; - codegen.describe_params = - matches!(self.options.action, Action::EmitPtx | Action::EmitMsl); - codegen - .generate(&monomorphized_ast, &module_syntaxes) - .map_err(|e| format!("Codegen Error: {:?}", e))?; - codegen.into_module() + self.ast_module(&context, &monomorphized_ast, &module_syntaxes)? } }; self.lower_and_emit(&context, module, host_arch, filename, main_file, mlir_args) } + /// The module that the AST code generator makes from the checked entry module and the + /// modules it imports. + fn ast_module<'c>( + &self, + context: &'c melior::Context, + main_ast: &crate::syntax::Program, + module_syntaxes: &std::collections::HashMap, + ) -> Result, String> { + let mut codegen = MeliorGenerator::new(context, main_ast.module_path.to_string()); + codegen.emit_seam_certs = self.options.emit_seam_certs; + codegen.describe_params = matches!(self.options.action, Action::EmitPtx | Action::EmitMsl); + codegen + .generate(main_ast, module_syntaxes) + .map_err(|e| format!("Codegen Error: {:?}", e))?; + Ok(codegen.into_module()) + } + /// The backend from an MLIR module to the action's output: verification, the pass pipeline, /// then print, JIT or object file. Shared by the sequential driver and `-j`. fn lower_and_emit<'c>( @@ -2211,6 +2252,14 @@ impl CompilerDriver { } } +/// What the parallel frontend hands to the backend. +enum Frontended { + /// The MLIR text of the flat code generator. + Mlir(String), + /// The checked modules, for the AST code generator. + Ast(Box), +} + /// The module as text with its source locations, so that `mlir-translate` can make DWARF. fn module_text_with_locations(module: &melior::ir::Module) -> Result { use melior::ir::operation::{OperationLike, OperationPrintingFlags}; diff --git a/src/hir/check/tasks.rs b/src/hir/check/tasks.rs index 0d7bea912..fe35e44cd 100644 --- a/src/hir/check/tasks.rs +++ b/src/hir/check/tasks.rs @@ -251,6 +251,12 @@ const TASK_PREFIX: &str = "task#"; const COPY_SUFFIX: &str = "/copy"; impl TypeChecker<'_> { + /// Whether this checker gave a name from one of its counters, such as `Closure_1`, a task + /// or a `tasks` block. Such a name depends on what the checker checked before. + pub(crate) fn named_by_counter(&self) -> bool { + self.next_id != 1 || self.tasks.next_id != 0 || self.tasks.next_block != 0 + } + /// Sentences to add to a borrow error on `var` when the borrow `b` belongs to a task. They /// name the `spawn` of the task, the line where it uses `var`, and the join that ends it. fn held_by_task_note(&self, b: &crate::hir::env::BorrowRecord, var: &str) -> String { diff --git a/src/pipeline.rs b/src/pipeline.rs index d91305207..06740f7ca 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -477,6 +477,99 @@ pub fn compile_modules_mlir_in( Ok(text) } +/// The checked entry module, and the modules it imports by name. +pub type CheckedModules = ( + syntax::Program, + std::collections::HashMap, +); + +/// The parallel frontend for the AST code generator: what `vxc -j --legacy-codegen` compiles. +/// +/// Returns the entry module and the imported modules by name, as the sequential driver hands +/// them to the AST code generator. The entry module gets every generic instance, in the order +/// the sequential driver makes them, so the two compiles emit the same bytes. +/// +/// `Ok(None)` when a check gave a name from a counter, such as `Closure_1`. Each check starts +/// its counters again, so the names are not the ones the sequential driver gives. +pub fn check_modules_for_ast_codegen( + modules: Vec, + sched: Schedule, + intern_mode: crate::intern_mode::InternMode, + auto_schedule_levels: bool, + entry: crate::symbol::Symbol, +) -> Result, PipelineError> { + let Frontend { + mut modules, + checks, + warnings, + .. + } = run_frontend_on( + modules, + sched, + intern_mode, + auto_schedule_levels, + Reported::OnlyEntry(entry.clone()), + )?; + if checks.iter().any(|c| c.named_by_counter) { + return Ok(None); + } + report_warnings(&warnings); + let entry_idx = modules + .iter() + .position(|m| m.module_path == entry) + .expect("the entry module is among the checked modules"); + + // The order of the sequential driver's checks: every check of the entry module, then the + // transfer lowerings of the other modules, then their non-generic free functions. It does + // not check the impl methods or the generic functions of the other modules. + let mut imported: Vec = (0..modules.len()).filter(|&i| i != entry_idx).collect(); + imported.sort_by(|&a, &b| modules[a].module_path.cmp(&modules[b].module_path)); + let all = &checks; + let of = move |module: usize, item: CheckedItem| { + all.iter() + .filter(move |c| c.module_idx == module && c.item == item) + }; + let in_order: Vec<&FunctionCheck> = checks + .iter() + .filter(|c| c.module_idx == entry_idx) + .chain(imported.iter().flat_map(|&m| of(m, CheckedItem::Lowering))) + .chain(imported.iter().flat_map(|&m| of(m, CheckedItem::Function))) + .collect(); + + // A generic instance is made once in the sequential driver, the first time a check needs + // it. Here each check makes its own, so the first one by name is kept. + let mut seen = std::collections::HashSet::new(); + let mut functions: Vec = in_order + .iter() + .flat_map(|c| c.monomorphs.iter().map(|(f, _)| f)) + .filter(|f| seen.insert(f.name.clone())) + .cloned() + .collect(); + // Only a closure makes a struct, and a program with a closure returned above. + assert!( + checks.iter().all(|c| c.generated_structs.is_empty()), + "a check made a struct, but only a closure makes one, and a closure goes to the \ + sequential driver" + ); + let comptime: std::collections::HashSet<&str> = checks + .iter() + .filter(|c| c.module_idx == entry_idx && c.item == CheckedItem::Function && c.was_comptime) + .map(|c| c.function.as_str()) + .collect(); + + let mut main = modules.remove(entry_idx); + functions.extend(main.functions.drain(..).filter(|f| f.generics.is_empty())); + functions.retain(|f| { + !comptime.contains(f.name.as_ref()) && !crate::hir::TypeChecker::is_comptime_fn(f) + }); + main.functions = functions; + let others = modules + .into_iter() + .map(|m| (m.module_path.clone(), m)) + .collect(); + Ok(Some((main, others))) +} + /// The module path a file is known by: its stem, so `.../m0.vx` is the module `m0`. /// /// This is the name an `import` can write, which is the whole point. `ModuleLoader` — the loader @@ -618,6 +711,21 @@ struct FunctionCheck { /// Capacity summaries this worker produced (the function, plus any generic it was first /// to instantiate) -- the cross-call fold's input, collected after the parallel phase. capacity_summaries: Vec, + /// What the check read: a free function, an impl method or a transfer lowering. + item: CheckedItem, + /// The function was a comptime function before its check folded it. + was_comptime: bool, + /// The check named something with a counter of its checker, such as a closure. + named_by_counter: bool, +} + +/// The kind of item a check read. The sequential driver checks the kinds in a fixed order, +/// and that order decides the order of the generic instances. +#[derive(Clone, Copy, PartialEq)] +enum CheckedItem { + Function, + Method, + Lowering, } // ---- Phase 3: lowering AST types to the flat GID stream ------------------------------------ @@ -1317,15 +1425,18 @@ fn check_one_function( module_idx: usize, global_session: &std::sync::Arc, global_env: &GlobalAstEnv, + item: CheckedItem, lowering_edge: Option<(syntax::MemorySpace, syntax::MemorySpace, String)>, ) -> FunctionCheck { let function = func.name.to_string(); + let was_comptime = crate::hir::TypeChecker::is_comptime_fn(func); let mut worker = LocalWorkerState::new(global_session.clone()); let mut checker = TypeChecker::new(global_env, &mut worker); // Inside an `impl transfer` body the eight `raw::` primitives resolve; everywhere // else the edge is `None` and they do not (Vx#353). checker.seam.lowering_edge = lowering_edge; checker.check_function(func); + let named_by_counter = checker.named_by_counter(); let errors = checker.errors; // A comptime lambda's generated body is not emitted: every call to it folded, so @@ -1354,6 +1465,9 @@ fn check_one_function( module_idx, generated_structs: gen_structs, capacity_summaries, + item, + was_comptime, + named_by_counter, } } @@ -1504,7 +1618,16 @@ fn type_check_phase( let mut results: Vec = module .functions .iter_mut() - .map(|f| check_one_function(f, module_idx, global_session, global_env, None)) + .map(|f| { + check_one_function( + f, + module_idx, + global_session, + global_env, + CheckedItem::Function, + None, + ) + }) .collect(); // A copied default is checked as the instance a call creates, as in the driver. let impl_results: Vec = module @@ -1516,7 +1639,16 @@ fn type_check_phase( .iter_mut() .filter(move |f| !copied.contains(&f.name)) }) - .map(|f| check_one_function(f, module_idx, global_session, global_env, None)) + .map(|f| { + check_one_function( + f, + module_idx, + global_session, + global_env, + CheckedItem::Method, + None, + ) + }) .collect(); results.extend(impl_results); // Transfer lowerings, same walk (#353). Third traversal rather than folded @@ -1537,6 +1669,7 @@ fn type_check_phase( module_idx, global_session, global_env, + CheckedItem::Lowering, Some(edge.clone()), ) }) @@ -1554,7 +1687,16 @@ fn type_check_phase( let mut results: Vec = module .functions .par_iter_mut() - .map(|f| check_one_function(f, module_idx, global_session, global_env, None)) + .map(|f| { + check_one_function( + f, + module_idx, + global_session, + global_env, + CheckedItem::Function, + None, + ) + }) .collect(); let impl_results: Vec = module .impls @@ -1565,7 +1707,14 @@ fn type_check_phase( .par_iter_mut() .filter(move |f| !copied.contains(&f.name)) .map(|f| { - check_one_function(f, module_idx, global_session, global_env, None) + check_one_function( + f, + module_idx, + global_session, + global_env, + CheckedItem::Method, + None, + ) }) }) .collect(); @@ -1585,6 +1734,7 @@ fn type_check_phase( module_idx, global_session, global_env, + CheckedItem::Lowering, Some(edge.clone()), ) }) @@ -2187,6 +2337,9 @@ mod gid_stream_tests { module_idx: 0, generated_structs: Vec::new(), capacity_summaries: Vec::new(), + item: CheckedItem::Function, + was_comptime: false, + named_by_counter: false, }]; let (_s, arena, offsets, slow, gen) = deduplication_phase(&results, &session); let mut streams = extract_type_streams(&mut results); diff --git a/tests/frontend/fail/jobs_refuses_a_flag_it_cannot_honour.vx b/tests/frontend/fail/jobs_refuses_a_flag_it_cannot_honour.vx index 19143fc19..ac9f66d77 100644 --- a/tests/frontend/fail/jobs_refuses_a_flag_it_cannot_honour.vx +++ b/tests/frontend/fail/jobs_refuses_a_flag_it_cannot_honour.vx @@ -6,14 +6,14 @@ // //===----------------------------------------------------------------------===// // `-j` refuses a flag whose meaning it does not implement rather than dropping it: the -// parallel frontend has no AST codegen, so `--legacy-codegen` cannot be honoured, and a -// compile that quietly ran the flat path instead would report success for the wrong thing. +// parallel frontend does not run the seam checks of `--verify-seams`, and a compile that +// quietly skipped them would report success for the wrong thing. // -// RUN: (vxc -j 2 --legacy-codegen --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s +// RUN: (vxc -j 2 --verify-seams --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s fn main() -> i32 { return 0; } -// CHECK: -j does not support --legacy-codegen yet +// CHECK: -j does not support --verify-seams yet // CHECK: exit=1 diff --git a/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx b/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx index 3a42101c7..31e841e35 100644 --- a/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx +++ b/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx @@ -19,5 +19,5 @@ fn main() -> i32 { } // CHECK: [parallel-frontend] emitted module with -j 4 -// CHECK: func.func @double -// CHECK: func.func @main +// CHECK-DAG: func.func @double +// CHECK-DAG: func.func @main diff --git a/tests/frontend/pass/jobs_falls_back_outside_the_flat_subset.vx b/tests/frontend/pass/jobs_falls_back_outside_the_flat_subset.vx index b2315439b..8fef38932 100644 --- a/tests/frontend/pass/jobs_falls_back_outside_the_flat_subset.vx +++ b/tests/frontend/pass/jobs_falls_back_outside_the_flat_subset.vx @@ -14,8 +14,8 @@ // the sequential compile that emitted the program went unreported. // // This test checks the fallback, so it unsets VX_NO_AST_FALLBACK, which the test runner sets. -// RUN: (env -u VX_NO_AST_FALLBACK VX_FLAT_DECLINE=seven_or_nine vxc -j 2 --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s -// RUN: (VX_PIPELINE_PHASES=1 VX_FLAT_DECLINE=seven_or_nine env -u VX_NO_AST_FALLBACK vxc -j 2 --emit-mlir %s 2>&1 >/dev/null) | FileCheck --check-prefix=PHASES %s +// RUN: (env -u VX_NO_AST_FALLBACK VX_FLAT_DECLINE=seven_or_nine vxc -j 2 --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s # flat-codegen +// RUN: (VX_PIPELINE_PHASES=1 VX_FLAT_DECLINE=seven_or_nine env -u VX_NO_AST_FALLBACK vxc -j 2 --emit-mlir %s 2>&1 >/dev/null) | FileCheck --check-prefix=PHASES %s # flat-codegen fn seven_or_nine(n : i64) -> i32 { return match n { diff --git a/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx b/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx index e97a63494..e86d963e9 100644 --- a/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx +++ b/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx @@ -31,6 +31,6 @@ fn main() -> i32 { return total(p); } -// MLIR: func.func @main -// MLIR: func.func @wave_b +// MLIR-DAG: func.func @main +// MLIR-DAG: func.func @wave_b // CHECK: same bytes diff --git a/tests/frontend/pass/jobs_warns_once_when_it_falls_back.vx b/tests/frontend/pass/jobs_warns_once_when_it_falls_back.vx index df7b0eb1d..5593ab883 100644 --- a/tests/frontend/pass/jobs_warns_once_when_it_falls_back.vx +++ b/tests/frontend/pass/jobs_warns_once_when_it_falls_back.vx @@ -14,7 +14,7 @@ // produces the warning. // // This test checks the fallback, so it unsets VX_NO_AST_FALLBACK, which the test runner sets. -// RUN: (env -u VX_NO_AST_FALLBACK VX_FLAT_DECLINE=seven_or_nine vxc -j 2 --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s +// RUN: (env -u VX_NO_AST_FALLBACK VX_FLAT_DECLINE=seven_or_nine vxc -j 2 --emit-mlir %s 2>&1; echo "exit=$?") | FileCheck %s # flat-codegen fn seven_or_nine(n : i64) -> i32 { return match n { diff --git a/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx b/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx new file mode 100644 index 000000000..0355ce2c9 --- /dev/null +++ b/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx @@ -0,0 +1,37 @@ +//===- jobs_with_legacy_codegen_and_closures.vx - Vx Compiler ------*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// The checker names each closure with a counter, as in `Closure_1`. A parallel check starts the +// counter again in each function, so two functions would both make `Closure_1`. So +// `-j 2 --legacy-codegen` compiles a program with closures on the sequential driver, and each +// closure keeps its own body. +// +// RUN: vxc -j 2 --legacy-codegen %s 2>&1 | FileCheck %s --implicit-check-not=Error + +fn add_ten(x: i32) -> i32 { + let f = |y: i32| -> i32 { + return y + 10; + }; + return f(x); +} + +fn times_three(x: i32) -> i32 { + let g = |y: i32| -> i32 { + return y * 3; + }; + return g(x); +} + +fn main() -> i32 { + println!("{}", add_ten(1)); + println!("{}", times_three(2)); + return 0; +} + +// CHECK: [parallel-frontend] the program has a closure, a task or a `vec!` value. The names +// CHECK: {{^}}11{{$}} +// CHECK-NEXT: {{^}}6{{$}} diff --git a/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx b/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx new file mode 100644 index 000000000..0f2e5d238 --- /dev/null +++ b/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx @@ -0,0 +1,76 @@ +//===- jobs_with_legacy_codegen_gives_the_same_bytes.vx - Vx Compiler -*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// `-j 2 --legacy-codegen` checks the program in parallel, then the AST code generator makes the +// MLIR. The MLIR is the same bytes as a normal `--legacy-codegen` compile. The program has +// generic instances made by two functions, a comptime function, `Vec` from std and two +// imported modules, because the order of these is what a parallel check can change. The +// comptime function `eleven` folds, so it is not in the MLIR. +// +// RUN: vxc --package tests=tests --legacy-codegen --emit-mlir %s > %t.seq +// RUN: vxc --package tests=tests -j 2 --legacy-codegen --emit-mlir %s > %t.j2 2> %t.err +// RUN: FileCheck --check-prefix=PATH %s < %t.err +// RUN: FileCheck --check-prefix=MLIR %s --implicit-check-not=@eleven < %t.seq +// RUN: (cmp %t.seq %t.j2 && echo "same bytes") | FileCheck %s +// RUN: vxc --package tests=tests -j 2 --legacy-codegen %s 2>&1 | FileCheck --check-prefix=OUT %s --implicit-check-not=Error + +import std::vec; +import tests::modules::jobs_wave_a; + +struct Holder { + value: T, +} + +fn wrap(x: T) -> Holder { + return Holder { + value: x + }; +} + +fn second(a: T, b: T) -> T { + let _first = a; + return b; +} + +fn zeta() -> i64 { + let h = wrap(7 as i64); + return second(h.value, 8 as i64); +} + +fn alpha() -> i32 { + let mut v: Vec = Vec::new(); + v.push(3); + return second(1, v.get(0)); +} + +fn eleven() -> i32 { + return comptime { + 5 + 6 + }; +} + +fn main() -> i32 { + println!("{}", zeta()); + println!("{}", alpha()); + println!("{}", eleven()); + println!("{}", wave_a(1)); + return 0; +} + +// PATH: [parallel-frontend] emitted module with -j 2 +// MLIR: func.func @wave_b +// MLIR: func.func @main +// MLIR: func.func @zeta +// MLIR: func.func @wrap$i64 +// MLIR: func.func @second$i64 +// MLIR: func.func @alpha +// MLIR: func.func @second$i32 +// CHECK: same bytes +// OUT: {{^}}8{{$}} +// OUT-NEXT: {{^}}3{{$}} +// OUT-NEXT: {{^}}11{{$}} +// OUT-NEXT: {{^}}3{{$}} diff --git a/tests/integration_test/compile_test.rs b/tests/integration_test/compile_test.rs index b94e70723..3cf7d9d1b 100644 --- a/tests/integration_test/compile_test.rs +++ b/tests/integration_test/compile_test.rs @@ -1085,23 +1085,18 @@ fn run_lit_test_with_env(path: &Path, env: &[(&str, String)]) -> Result<(), Stri .collect(); // With VX_LEGACY_PARITY=1, the RUN lines run a second time, in order, after all of them // passed. In the second pass, each `vxc` command gets `--legacy-codegen`. These lines run - // again unchanged: a line that already names it, a parallel compile (`-j`, #3139), and a - // line that ends with the shell comment `# flat-codegen`. That comment says the line checks - // text that only the flat code generator writes, such as its MLIR. A file with - // `// REQUIRES: flat-codegen` uses a construct that only the flat code generator has, and - // does not run a second time. + // again unchanged: a line that already names it, and a line that ends with the shell + // comment `# flat-codegen`. That comment says the line checks text that only the flat code + // generator writes, such as its MLIR. A file with `// REQUIRES: flat-codegen` uses a + // construct that only the flat code generator has, and does not run a second time. let parity = std::env::var_os("VX_LEGACY_PARITY").is_some() && !xfail && !source.contains("// REQUIRES: flat-codegen"); - let parallel = regex::Regex::new(r"\s-j\s*\d").unwrap(); let again: Vec = if parity { commands .iter() .map(|c| { - if c.contains("--legacy-codegen") - || parallel.is_match(c) - || c.trim_end().ends_with("# flat-codegen") - { + if c.contains("--legacy-codegen") || c.trim_end().ends_with("# flat-codegen") { c.clone() } else { with_legacy_codegen(c).unwrap_or_else(|| c.clone()) From da7e70bda2bcb1489a91a1b06414b8b33cf6f882 Mon Sep 17 00:00:00 2001 From: Naman Bajpai Date: Wed, 25 Nov 2026 10:01:56 +0000 Subject: [PATCH 2/2] driver: only a closure sends -j --legacy-codegen to the sequential driver The rule that sent a program to the sequential driver read every counter of the checker. A `?` on a Result also counts, so every program with `?` took the sequential path, and the note on stderr named the wrong reason. Only the names of closures reach the MLIR. The names that `?`, `vec!` and tasks get stay in one function. So the rule now looks only for a closure, which is the one thing that makes a struct. The fixture now compares the bytes at -j 1, -j 2 and -j 8 with a sequential compile, and has functions with `?` and `vec!` that must take the parallel path. Two old -j fixtures keep their exact checks of the flat code generator's order, with `# flat-codegen` instead of -DAG. Issue: #3139 Co-Authored-By: Claude Opus 5.5 --- src/driver.rs | 6 +- src/hir/check/tasks.rs | 6 -- src/hir/check_state.rs | 2 +- src/pipeline.rs | 26 ++++---- ..._compiles_through_the_parallel_frontend.vx | 6 +- ...put_does_not_depend_on_the_thread_count.vx | 8 +-- .../jobs_with_legacy_codegen_and_closures.vx | 2 +- ...ith_legacy_codegen_gives_the_same_bytes.vx | 63 ++++++++++++++++--- 8 files changed, 77 insertions(+), 42 deletions(-) diff --git a/src/driver.rs b/src/driver.rs index 1dc8f298f..d3d348745 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -614,9 +614,9 @@ impl CompilerDriver { .map_err(failed)?; let Some(checked) = checked else { eprintln!( - "[parallel-frontend] the program has a closure, a task or a `vec!` value. \ - The names the checks give them depend on the order of the checks, so the \ - sequential driver compiles the program" + "[parallel-frontend] the program has a closure. The name of a closure \ + depends on the order of the checks, so the sequential driver compiles \ + the program" ); return Ok(None); }; diff --git a/src/hir/check/tasks.rs b/src/hir/check/tasks.rs index fe35e44cd..0d7bea912 100644 --- a/src/hir/check/tasks.rs +++ b/src/hir/check/tasks.rs @@ -251,12 +251,6 @@ const TASK_PREFIX: &str = "task#"; const COPY_SUFFIX: &str = "/copy"; impl TypeChecker<'_> { - /// Whether this checker gave a name from one of its counters, such as `Closure_1`, a task - /// or a `tasks` block. Such a name depends on what the checker checked before. - pub(crate) fn named_by_counter(&self) -> bool { - self.next_id != 1 || self.tasks.next_id != 0 || self.tasks.next_block != 0 - } - /// Sentences to add to a borrow error on `var` when the borrow `b` belongs to a task. They /// name the `spawn` of the task, the line where it uses `var`, and the join that ends it. fn held_by_task_note(&self, b: &crate::hir::env::BorrowRecord, var: &str) -> String { diff --git a/src/hir/check_state.rs b/src/hir/check_state.rs index 791b728a6..9c7f7e090 100644 --- a/src/hir/check_state.rs +++ b/src/hir/check_state.rs @@ -735,7 +735,7 @@ impl Default for ConstEvalState { pub struct MonoState { /// Concrete instantiations produced during checking, with the hash of the arguments. pub functions: Vec<(Function, u64)>, - /// Structs synthesized during checking (closure environments, instantiated generics). + /// The environment structs of the closures made during checking. pub generated_structs: Vec, /// Topology generic parameters (``) of the function being instantiated. Set /// around the deduction unify at a generic call so `unify_types` can bind a `Pinned<_, D>` diff --git a/src/pipeline.rs b/src/pipeline.rs index 06740f7ca..f26b388fd 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -489,8 +489,11 @@ pub type CheckedModules = ( /// them to the AST code generator. The entry module gets every generic instance, in the order /// the sequential driver makes them, so the two compiles emit the same bytes. /// -/// `Ok(None)` when a check gave a name from a counter, such as `Closure_1`. Each check starts -/// its counters again, so the names are not the ones the sequential driver gives. +/// `Ok(None)` when the program has a closure. The checker names a closure with a counter, as in +/// `Closure_1`, and the name is in the MLIR. Each check starts the counter again, so the names +/// are not the ones the sequential driver gives. The other names from counters, such as those +/// of `?` and `vec!`, are local to one function, and the sequential driver also gives them again +/// in each function. pub fn check_modules_for_ast_codegen( modules: Vec, sched: Schedule, @@ -510,7 +513,7 @@ pub fn check_modules_for_ast_codegen( auto_schedule_levels, Reported::OnlyEntry(entry.clone()), )?; - if checks.iter().any(|c| c.named_by_counter) { + if checks.iter().any(|c| c.made_closure) { return Ok(None); } report_warnings(&warnings); @@ -545,12 +548,6 @@ pub fn check_modules_for_ast_codegen( .filter(|f| seen.insert(f.name.clone())) .cloned() .collect(); - // Only a closure makes a struct, and a program with a closure returned above. - assert!( - checks.iter().all(|c| c.generated_structs.is_empty()), - "a check made a struct, but only a closure makes one, and a closure goes to the \ - sequential driver" - ); let comptime: std::collections::HashSet<&str> = checks .iter() .filter(|c| c.module_idx == entry_idx && c.item == CheckedItem::Function && c.was_comptime) @@ -715,8 +712,8 @@ struct FunctionCheck { item: CheckedItem, /// The function was a comptime function before its check folded it. was_comptime: bool, - /// The check named something with a counter of its checker, such as a closure. - named_by_counter: bool, + /// The check made a closure, which the checker names with a counter. + made_closure: bool, } /// The kind of item a check read. The sequential driver checks the kinds in a fixed order, @@ -1436,7 +1433,6 @@ fn check_one_function( // else the edge is `None` and they do not (Vx#353). checker.seam.lowering_edge = lowering_edge; checker.check_function(func); - let named_by_counter = checker.named_by_counter(); let errors = checker.errors; // A comptime lambda's generated body is not emitted: every call to it folded, so @@ -1452,6 +1448,8 @@ fn check_one_function( }) .collect(); let gen_structs = checker.mono.generated_structs; + // Only a closure makes a struct. + let made_closure = !gen_structs.is_empty(); let capacity_summaries = std::mem::take(&mut checker.traffic.capacity_summaries); // Lower this function's type references to the flat GID stream (Phase 3). @@ -1467,7 +1465,7 @@ fn check_one_function( capacity_summaries, item, was_comptime, - named_by_counter, + made_closure, } } @@ -2339,7 +2337,7 @@ mod gid_stream_tests { capacity_summaries: Vec::new(), item: CheckedItem::Function, was_comptime: false, - named_by_counter: false, + made_closure: false, }]; let (_s, arena, offsets, slow, gen) = deduplication_phase(&results, &session); let mut streams = extract_type_streams(&mut results); diff --git a/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx b/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx index 31e841e35..c1daac25c 100644 --- a/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx +++ b/tests/frontend/pass/jobs_compiles_through_the_parallel_frontend.vx @@ -8,7 +8,7 @@ // `-j N` compiles through the parallel frontend and then the ordinary backend. The note on // stderr says which frontend ran; the function in the MLIR says the backend got its output. // -// RUN: vxc -j 4 --emit-mlir %s 2>&1 | FileCheck %s +// RUN: vxc -j 4 --emit-mlir %s 2>&1 | FileCheck %s # flat-codegen fn double(x: i32) -> i32 { return x + x; @@ -19,5 +19,5 @@ fn main() -> i32 { } // CHECK: [parallel-frontend] emitted module with -j 4 -// CHECK-DAG: func.func @double -// CHECK-DAG: func.func @main +// CHECK: func.func @double +// CHECK: func.func @main diff --git a/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx b/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx index e86d963e9..3cb668409 100644 --- a/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx +++ b/tests/frontend/pass/jobs_output_does_not_depend_on_the_thread_count.vx @@ -9,8 +9,8 @@ // path, and at four, where the modules and functions are checked and lowered concurrently. // Two modules deep in imports, so module order is part of what is compared. // -// RUN: vxc --package tests=tests -j 1 --emit-mlir %s > %t.j1 -// RUN: vxc --package tests=tests -j 4 --emit-mlir %s > %t.j4 +// RUN: vxc --package tests=tests -j 1 --emit-mlir %s > %t.j1 # flat-codegen +// RUN: vxc --package tests=tests -j 4 --emit-mlir %s > %t.j4 # flat-codegen // RUN: FileCheck --check-prefix=MLIR %s < %t.j1 // RUN: (cmp %t.j1 %t.j4 && echo "same bytes") | FileCheck %s @@ -31,6 +31,6 @@ fn main() -> i32 { return total(p); } -// MLIR-DAG: func.func @main -// MLIR-DAG: func.func @wave_b +// MLIR: func.func @main +// MLIR: func.func @wave_b // CHECK: same bytes diff --git a/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx b/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx index 0355ce2c9..b0ce7025f 100644 --- a/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx +++ b/tests/frontend/pass/jobs_with_legacy_codegen_and_closures.vx @@ -32,6 +32,6 @@ fn main() -> i32 { return 0; } -// CHECK: [parallel-frontend] the program has a closure, a task or a `vec!` value. The names +// CHECK: [parallel-frontend] the program has a closure. The name of a closure // CHECK: {{^}}11{{$}} // CHECK-NEXT: {{^}}6{{$}} diff --git a/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx b/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx index 0f2e5d238..b992183cc 100644 --- a/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx +++ b/tests/frontend/pass/jobs_with_legacy_codegen_gives_the_same_bytes.vx @@ -5,19 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// -// `-j 2 --legacy-codegen` checks the program in parallel, then the AST code generator makes the -// MLIR. The MLIR is the same bytes as a normal `--legacy-codegen` compile. The program has -// generic instances made by two functions, a comptime function, `Vec` from std and two -// imported modules, because the order of these is what a parallel check can change. The -// comptime function `eleven` folds, so it is not in the MLIR. +// `-j N --legacy-codegen` checks the program in parallel, then the AST code generator makes the +// MLIR. At 1, 2 and 8 threads, the MLIR is the same bytes as a normal `--legacy-codegen` +// compile. The program has generic instances made by two functions, a comptime function, `Vec` +// from std and two imported modules, because a parallel check can change their order. The +// comptime function `eleven` folds, so it is not in the MLIR. Two functions use `?` and one +// uses `vec!`. The checker names their values with a counter, but the names stay in one +// function, so the compile takes the parallel path. // // RUN: vxc --package tests=tests --legacy-codegen --emit-mlir %s > %t.seq -// RUN: vxc --package tests=tests -j 2 --legacy-codegen --emit-mlir %s > %t.j2 2> %t.err -// RUN: FileCheck --check-prefix=PATH %s < %t.err +// RUN: vxc --package tests=tests -j 1 --legacy-codegen --emit-mlir %s > %t.j1 2> %t.err1 +// RUN: vxc --package tests=tests -j 2 --legacy-codegen --emit-mlir %s > %t.j2 2> %t.err2 +// RUN: vxc --package tests=tests -j 8 --legacy-codegen --emit-mlir %s > %t.j8 2> %t.err8 +// RUN: cat %t.err1 %t.err2 %t.err8 | FileCheck --check-prefix=PATH %s // RUN: FileCheck --check-prefix=MLIR %s --implicit-check-not=@eleven < %t.seq -// RUN: (cmp %t.seq %t.j2 && echo "same bytes") | FileCheck %s +// RUN: (cmp %t.seq %t.j1 && echo "same bytes at -j 1") | FileCheck --check-prefix=J1 %s +// RUN: (cmp %t.seq %t.j2 && echo "same bytes at -j 2") | FileCheck --check-prefix=J2 %s +// RUN: (cmp %t.seq %t.j8 && echo "same bytes at -j 8") | FileCheck --check-prefix=J8 %s // RUN: vxc --package tests=tests -j 2 --legacy-codegen %s 2>&1 | FileCheck --check-prefix=OUT %s --implicit-check-not=Error +import core::result; import std::vec; import tests::modules::jobs_wave_a; @@ -47,6 +54,32 @@ fn alpha() -> i32 { return second(1, v.get(0)); } +fn plus_one(r: Result) -> Result { + let v = r?; + return Result::Ok(v + 1); +} + +fn plus_two(r: Result) -> Result { + let v = r?; + return Result::Ok(v + 2); +} + +fn value(r: Result) -> i64 { + match r { + Result::Ok(v) => { + return v; + } + Result::Err(e) => { + return 0 - (e as i64); + } + } +} + +fn first_of_three() -> i32 { + let v = vec![4, 5, 6]; + return v.get(0); +} + fn eleven() -> i32 { return comptime { 5 + 6 @@ -58,10 +91,12 @@ fn main() -> i32 { println!("{}", alpha()); println!("{}", eleven()); println!("{}", wave_a(1)); + println!("{}", value(plus_one(Result::Ok(1)))); + println!("{}", value(plus_two(Result::Err(5)))); + println!("{}", first_of_three()); return 0; } -// PATH: [parallel-frontend] emitted module with -j 2 // MLIR: func.func @wave_b // MLIR: func.func @main // MLIR: func.func @zeta @@ -69,8 +104,16 @@ fn main() -> i32 { // MLIR: func.func @second$i64 // MLIR: func.func @alpha // MLIR: func.func @second$i32 -// CHECK: same bytes +// PATH: [parallel-frontend] emitted module with -j 1 +// PATH: [parallel-frontend] emitted module with -j 2 +// PATH: [parallel-frontend] emitted module with -j 8 +// J1: same bytes at -j 1 +// J2: same bytes at -j 2 +// J8: same bytes at -j 8 // OUT: {{^}}8{{$}} // OUT-NEXT: {{^}}3{{$}} // OUT-NEXT: {{^}}11{{$}} // OUT-NEXT: {{^}}3{{$}} +// OUT-NEXT: {{^}}2{{$}} +// OUT-NEXT: {{^}}-5{{$}} +// OUT-NEXT: {{^}}4{{$}}