Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,10 @@ impl GenericParam {
GenericParamKind::Const { span, .. } => *span,
}
}

pub fn span_with_attributes(&self) -> Span {
if let Some(first) = self.attrs.first() { first.span.to(self.span()) } else { self.span() }
}
}

/// Represents lifetime, type and const parameters attached to a declaration of
Expand Down
49 changes: 27 additions & 22 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
use rustc_middle::middle::dependency_format::Linkage;
use rustc_middle::middle::exported_symbols::SymbolExportKind;
use rustc_session::config::{
self, CFGuard, DebugInfo, InstrumentMcount, LinkerFeaturesCli, LinkerJobs, OutFileName,
OutputFilenames, OutputType, PrintKind, SplitDwarfKind, Strip,
self, CFGuard, DebugInfo, InstrumentMcount, JobsMode, LinkerFeaturesCli, LinkerJobs,
OutFileName, OutputFilenames, OutputType, PrintKind, SplitDwarfKind, Strip,
};
use rustc_session::output::{check_file_is_writeable, invalid_output_for_target, out_filename};
use rustc_session::search_paths::PathKind;
Expand Down Expand Up @@ -3207,32 +3207,37 @@ fn linker_with_args(

// Only LLD supports controlling parallelism at the moment.
let mut tokens = Vec::new();
if let LinkerJobs::Explicit(limit) = sess.opts.jobs.linker
if let LinkerJobs::Explicit(mode) = sess.opts.jobs.linker
&& flavor.uses_lld()
{
// Try obtaining as many jobserver tokens as possible (within the limit) to run parallel
// linking. One token is available implicitly since we are running on the main thread.
let client = jobserver::client();

let mut unsupported = false;
for _ in 0..limit.get() - 1 {
match client.try_acquire() {
Ok(Some(token)) => tokens.push(token),
Ok(None) => {}
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
assert!(tokens.is_empty());
unsupported = true;
break;
let threads = if let JobsMode::Parallel(limit) = mode {
// Try obtaining as many jobserver tokens as possible (within the limit) to run parallel
// linking. One token is available implicitly since we are running on the main thread.
let client = jobserver::client();

let mut unsupported = false;
for _ in 0..limit.get() - 1 {
match client.try_acquire() {
Ok(Some(token)) => tokens.push(token),
Ok(None) => {}
Err(e) if e.kind() == io::ErrorKind::Unsupported => {
assert!(tokens.is_empty());
unsupported = true;
break;
}
Err(e) => bug!("IO error when acquiring jobserver token: {e}"),
}
Err(e) => bug!("IO error when acquiring jobserver token: {e}"),
}
}

// Error on the side of oversubscription if non-blocking token acquiring is unsupported.
// Linking is typically the last step in a multi-crate project build,
// so the resources should usually be free.
if unsupported { limit.get() } else { 1 + tokens.len() }
} else {
1
};

let prefix = if sess.target.is_like_windows { "/threads:" } else { "--threads=" };
// Error on the side of oversubscription if non-blocking token acquiring is unsupported.
// Linking is typically the last step in a multi-crate project build,
// so the resources should usually be free.
let threads = if unsupported { limit.get() } else { 1 + tokens.len() };
cmd.link_arg(format!("{prefix}{threads}"));
}

Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ use rustc_metadata::fs::copy_to_stdout;
use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{
self, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
self, JobsMode, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes,
SwitchWithOptPath,
};
use rustc_session::{BorrowedIncrCompSession, IncrCompSession, Session};
use rustc_span::source_map::SourceMap;
Expand Down Expand Up @@ -1234,7 +1235,7 @@ fn start_executing_work<B: WriteBackendMethods>(
// tokens before releasing them, so we can never accidentally release the last token
// permanently held by rustc process.
let parallel = match sess.opts.jobs.backend {
Some(n) if backend.supports_parallel() => Some(n),
JobsMode::Parallel(n) if backend.supports_parallel() => Some(n),
_ => None,
};
let jobserver_helper = parallel.map(|_| {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItem
use rustc_middle::query::Providers;
use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized};
use rustc_session::config::{self, EntryFnType};
use rustc_session::config::{self, EntryFnType, JobsMode};
use rustc_span::{DUMMY_SP, Symbol, bug, span_bug};
use rustc_structures::CrateType;
use rustc_symbol_mangling::mangle_internal_symbol;
Expand Down Expand Up @@ -817,7 +817,7 @@ pub fn codegen_crate<
// This likely is a temporary measure. Once we don't have to support the
// non-parallel compiler anymore, we can compile CGUs end-to-end in
// parallel and get rid of the complicated scheduling logic.
let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend {
let mut pre_compiled_cgus = if let JobsMode::Parallel(threads) = tcx.sess.opts.jobs.frontend {
tcx.sess.time("compile_first_CGU_batch", || {
// Try to find one CGU to compile per thread.
let cgus: Vec<_> = cgu_reuse
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
| ExprKind::If(..)
| ExprKind::Let(..)
| ExprKind::Loop(..)
| ExprKind::Match(..) => {}
| ExprKind::Match(..)
| ExprKind::Become(..) => {}
// Do not warn on `as` casts from never to any,
// they are sometimes required to appeal typeck.
ExprKind::Cast(_, _) => {}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use rustc_parse::lexer::StripTokens;
use rustc_parse::new_parser_from_source_str;
use rustc_parse::parser::Recovery;
use rustc_query_impl::print_query_stack;
use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName};
use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, JobsMode, OutFileName};
use rustc_session::parse::ParseSess;
use rustc_session::{CompilerIO, EarlyDiagCtxt, EarlySession, Session};
use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs};
Expand Down Expand Up @@ -380,12 +380,12 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
trace!("run_compiler");

// Set parallel mode before thread pool creation, which will create `Lock`s.
rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.jobs.frontend.is_some());
rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.jobs.frontend.is_parallel());

// Initialize jobserver as early as possible.
let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
let jobs = config.opts.jobs;
if let Some(limit) = jobs.frontend.max(jobs.backend).max(jobs.linker.limit()) {
if let JobsMode::Parallel(limit) = jobs.frontend.max(jobs.backend).max(jobs.linker.mode()) {
jobserver::initialize(limit.get(), |err| {
let note = "the build environment is likely misconfigured";
early_dcx.early_struct_warn(err).with_note(note).emit()
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::any::Any;
use std::collections::BTreeMap;
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
use std::num::NonZero;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
Expand Down Expand Up @@ -248,7 +247,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce(CurrentGcx) -> R + Send,

let thread_stack_size = init_stack_size(thread_builder_diag);

let jobs_frontend = jobs.frontend.or(NonZero::new(1)).unwrap();
let jobs_frontend = jobs.frontend.limit();
let registry = sync::Registry::new(jobs_frontend);

let Some(proof) = sync::check_dyn_thread_safe() else {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,7 @@ pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
return;
};

if tcx.sess.opts.jobs.frontend.is_some() {
if tcx.sess.opts.jobs.frontend.is_parallel() {
// Prefetch some queries used by metadata encoding.
// This is not necessary for correctness, but is only done for performance reasons.
// It can be removed if it turns out to cause trouble or be detrimental to performance.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/dep_graph/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ impl DepGraphData {
let ok = match color {
DepNodeColor::Unknown => true,
DepNodeColor::Red => false,
DepNodeColor::Green(..) => sess.opts.jobs.frontend.is_some(), // Other threads may mark this green
DepNodeColor::Green(..) => sess.opts.jobs.frontend.is_parallel(), // Other threads may mark this green
};
if !ok {
panic!("{}", msg())
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_query_impl/src/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ fn try_execute_query<'tcx, C: QueryCache, const INCR: bool>(
// re-executing the query since `try_start` only checks that the query is not currently
// executing, but another thread may have already completed the query and stores it result
// in the query cache.
if tcx.sess.opts.jobs.frontend.is_some() {
if tcx.sess.opts.jobs.frontend.is_parallel() {
if let Some((value, index)) = query.cache.lookup(&key) {
tcx.prof.query_cache_hit(index.into());
return (value, Some(index));
Expand Down
12 changes: 8 additions & 4 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4067,8 +4067,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
// if removing within `<>` brackets, we also want to
// delete a leading or trailing comma as appropriate
match (
param.span().find_ancestor_inside(generics_span),
params[param_index + 1].span().find_ancestor_inside(generics_span),
param.span_with_attributes().find_ancestor_inside(generics_span),
params[param_index + 1]
.span_with_attributes()
.find_ancestor_inside(generics_span),
) {
(Some(param_span), Some(next_param_span)) => {
Some(param_span.to(next_param_span.shrink_to_lo()))
Expand All @@ -4079,8 +4081,10 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
// if removing within `<>` brackets, we also want to
// delete a leading or trailing comma as appropriate
match (
param.span().find_ancestor_inside(generics_span),
params[param_index - 1].span().find_ancestor_inside(generics_span),
param.span_with_attributes().find_ancestor_inside(generics_span),
params[param_index - 1]
.span_with_attributes()
.find_ancestor_inside(generics_span),
) {
(Some(param_span), Some(prev_param_span)) => {
Some(prev_param_span.shrink_to_hi().to(param_span))
Expand Down
64 changes: 47 additions & 17 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1536,7 +1536,11 @@ impl Default for Options {
verbose: false,
target_modifiers: BTreeMap::default(),
mitigation_coverage_map: Default::default(),
jobs: Jobs { frontend: None, backend: None, linker: LinkerJobs::Default },
jobs: Jobs {
frontend: JobsMode::Sequential,
backend: JobsMode::Sequential,
linker: LinkerJobs::Default,
},
recommended_stack_size: DEFAULT_STACK_SIZE,
}
}
Expand Down Expand Up @@ -1710,29 +1714,51 @@ impl PointerAuthOption {
}
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum JobsMode {
/// Everything runs on a single thread, and all the parallelization overhead
/// (locking, jobserver, prefetching, or anything else) is avoided when possible.
Sequential,
/// Multiple threads may be used and all the parallelization overhead is enabled.
/// Note that the actual parallelism can still be limited to 1 thread, which is useful for
/// perf testing the parallelization overhead (`--jobs*=sync` enables this mode).
Parallel(NonZero<usize>),
}

impl JobsMode {
pub fn limit(self) -> NonZero<usize> {
match self {
JobsMode::Sequential => NonZero::new(1).unwrap(),
JobsMode::Parallel(n) => n,
}
}

pub fn is_parallel(self) -> bool {
matches!(self, JobsMode::Parallel(..))
}
}

#[derive(Clone, Copy)]
pub enum LinkerJobs {
/// Do not pass anything to the linker, use it's default behavior.
Default,
/// Pass some specific number of jobs to use to the linker.
Explicit(NonZero<usize>),
Explicit(JobsMode),
}

impl LinkerJobs {
pub fn limit(self) -> Option<NonZero<usize>> {
pub fn mode(self) -> JobsMode {
match self {
LinkerJobs::Default => None,
LinkerJobs::Explicit(n) => Some(n),
LinkerJobs::Default => JobsMode::Sequential,
LinkerJobs::Explicit(n) => n,
}
}
}

/// `None` for frontend and backend means everything is single-threaded
/// and synchronization can be disabled.
#[derive(Clone, Copy)]
pub struct Jobs {
pub frontend: Option<NonZero<usize>>,
pub backend: Option<NonZero<usize>>,
pub frontend: JobsMode,
pub backend: JobsMode,
pub linker: LinkerJobs,
}

Expand All @@ -1750,9 +1776,9 @@ fn parse_jobs_all(
let jobs = matches
.opt_str("jobs")
.map(|s| parse_jobs_one(early_dcx, "--jobs", &s, unstable, &mut available));
let check_upper_limit = |value: Option<_>, opt_name| {
let check_upper_limit = |value: JobsMode, opt_name| {
if let Some(jobs) = jobs
&& value.or(NonZero::new(1)) > jobs.or(NonZero::new(1))
&& value.limit() > jobs.limit()
{
early_dcx.early_fatal(format!("`{opt_name}` cannot be larger than `--jobs`"));
}
Expand All @@ -1776,7 +1802,7 @@ fn parse_jobs_all(
check_upper_limit(frontend, opt_name);
frontend
}
None => None, // default to 1 thread irrespectively of `jobs` for now
None => JobsMode::Sequential, // default to 1 thread irrespectively of `jobs` for now
},
};
let backend = match matches.opt_str("jobs-backend") {
Expand All @@ -1799,10 +1825,10 @@ fn parse_jobs_all(
let linker =
parse_jobs_one(early_dcx, opt_name, &jobs_linker, unstable, &mut available);
check_upper_limit(linker, opt_name);
LinkerJobs::Explicit(linker.or(NonZero::new(1)).unwrap())
LinkerJobs::Explicit(linker)
}
None => match jobs {
Some(n) => LinkerJobs::Explicit(n.or(NonZero::new(1)).unwrap()),
Some(n) => LinkerJobs::Explicit(n),
None => LinkerJobs::Default, // back compat with lld
},
};
Expand All @@ -1817,13 +1843,13 @@ fn parse_jobs_one(
s: &str,
unstable: bool,
available: &mut Option<u8>,
) -> Option<NonZero<usize>> {
) -> JobsMode {
if s == "sync" {
// Enable synchronization overhead for benchmarking despite only using one thread.
if !unstable {
early_dcx.early_fatal(format!("`{opt_name}=sync` requires `-Z unstable-options`"));
}
return NonZero::new(1);
return JobsMode::Parallel(NonZero::new(1).unwrap());
}
// The number of jobs is capped by 255 (`u8::MAX`) to avoid arbitrary large numbers like 999999
// causing compiler panics (#117638). The limit can be potentially increased, because e.g.
Expand All @@ -1838,7 +1864,11 @@ fn parse_jobs_one(
.early_fatal(format!("`{opt_name}`: expected a number from 0 to 255 or `sync`")),
};
// `Jobs` uses `usize` for more convenient use, even if the actual values are limited to `u8`.
(n > 1).then_some(NonZero::new(usize::from(n)).unwrap())
match n {
0 => unreachable!(),
1 => JobsMode::Sequential,
_ => JobsMode::Parallel(NonZero::new(usize::from(n)).unwrap()),
}
}

pub fn build_configuration(sess: &Session, mut user_cfg: Cfg) -> Cfg {
Expand Down
1 change: 0 additions & 1 deletion library/core/src/intrinsics/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
#[must_use = "returns a pointer that does nothing unless used"]
#[rustc_intrinsic]
#[rustc_nounwind]
#[unstable(feature = "gpu_launch_sized_workgroup_mem", issue = "131513")]
#[cfg(any(doc, target_arch = "amdgpu", target_arch = "nvptx64"))]
pub fn gpu_launch_sized_workgroup_mem<T>() -> *mut T;

Expand Down
Loading
Loading