1use std::marker::PhantomData;
2use std::num::NonZero;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{assert_matches, fs, io, str, thread};
89use rustc_abi::Size;
10use rustc_data_structures::jobserver::{self, Acquired};
11use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
12use rustc_errors::emitter::Emitter;
13use rustc_errors::{
14Diag, DiagCtxt, DiagCtxtHandle, DiagInner, FatalError, FatalErrorMarker, Level,
15catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_incremental::{
19copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir_sess, in_old_incr_comp_dir_sess,
20};
21use rustc_macros::{Decodable, Encodable};
22use rustc_metadata::fs::copy_to_stdout;
23use rustc_middle::dep_graph::{BorrowedIncrCompSession, IncrCompSession, WorkProduct};
24use rustc_middle::ty::TyCtxt;
25use rustc_session::Session;
26use rustc_session::config::{
27self, JobsMode, Lto, OptimizationObjective, OutFileName, OutputFilenames, Passes,
28SwitchWithOptPath,
29};
30use rustc_session::output::OutputType;
31use rustc_span::source_map::SourceMap;
32use rustc_span::{BytePos, FileName, InnerSpan, Span, SyntaxContext, bug};
33use rustc_structures::CrateType;
34use rustc_target::spec::{MergeFunctions, SanitizerSet};
35use tracing::debug;
3637use crate::back::link::ensure_removed;
38use crate::back::lto::{self, SerializedModule, check_lto_allowed};
39use crate::diagnostics::ErrorCreatingRemarkDir;
40use crate::traits::*;
41use crate::{
42CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
43diagnostics,
44};
4546const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4748/// What kind of object file to emit.
49#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for EmitObj {
}
#[automatically_derived]impl ::core::clone::Clone for EmitObj {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for EmitObj {
}
#[automatically_derived]impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::ObjectCode(__self_0), Self::ObjectCode(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmitObj {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmitObj::None => { 0usize }
EmitObj::Bitcode => { 1usize }
EmitObj::ObjectCode(ref __binding_0) => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmitObj::None => {}
EmitObj::Bitcode => {}
EmitObj::ObjectCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmitObj {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { EmitObj::None }
1usize => { EmitObj::Bitcode }
2usize => {
EmitObj::ObjectCode(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmitObj`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
50pub enum EmitObj {
51// No object file.
52None,
5354// Just uncompressed llvm bitcode. Provides easy compatibility with
55 // emscripten's ecc compiler, when used as the linker.
56Bitcode,
5758// Object code, possibly augmented with a bitcode section.
59ObjectCode(BitcodeSection),
60}
6162/// What kind of llvm bitcode section to embed in an object file.
63#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for BitcodeSection {
}
#[automatically_derived]impl ::core::clone::Clone for BitcodeSection {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
BitcodeSection {
}
#[automatically_derived]impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for BitcodeSection {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
BitcodeSection::None => { 0usize }
BitcodeSection::Full => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for BitcodeSection {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { BitcodeSection::None }
1usize => { BitcodeSection::Full }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BitcodeSection`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
64pub enum BitcodeSection {
65// No bitcode section.
66None,
6768// A full, uncompressed bitcode section.
69Full,
70}
7172/// Module-specific configuration for `optimize_and_codegen`.
73#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
let ModuleConfig {
passes: ref __binding_0,
opt_level: ref __binding_1,
pgo_gen: ref __binding_2,
pgo_use: ref __binding_3,
pgo_sample_use: ref __binding_4,
debug_info_for_profiling: ref __binding_5,
instrument_coverage: ref __binding_6,
sanitizer: ref __binding_7,
sanitizer_cfi_diag: ref __binding_8,
sanitizer_cfi_recover: ref __binding_9,
sanitizer_recover: ref __binding_10,
sanitizer_dataflow_abilist: ref __binding_11,
sanitizer_memory_track_origins: ref __binding_12,
emit_pre_lto_bc: ref __binding_13,
emit_bc: ref __binding_14,
emit_ir: ref __binding_15,
emit_asm: ref __binding_16,
emit_obj: ref __binding_17,
emit_thin_lto_summary: ref __binding_18,
verify_llvm_ir: ref __binding_19,
lint_llvm_ir: ref __binding_20,
no_prepopulate_passes: ref __binding_21,
no_builtins: ref __binding_22,
vectorize_loop: ref __binding_23,
vectorize_slp: ref __binding_24,
merge_functions: ref __binding_25,
emit_lifetime_markers: ref __binding_26,
llvm_plugins: ref __binding_27,
autodiff: ref __binding_28,
autodiff_post_passes: ref __binding_29,
offload: ref __binding_30 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_27,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_28,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_29,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_30,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ModuleConfig {
fn decode(__decoder: &mut __D) -> Self {
ModuleConfig {
passes: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
pgo_gen: ::rustc_serialize::Decodable::decode(__decoder),
pgo_use: ::rustc_serialize::Decodable::decode(__decoder),
pgo_sample_use: ::rustc_serialize::Decodable::decode(__decoder),
debug_info_for_profiling: ::rustc_serialize::Decodable::decode(__decoder),
instrument_coverage: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_diag: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_dataflow_abilist: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_memory_track_origins: ::rustc_serialize::Decodable::decode(__decoder),
emit_pre_lto_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_ir: ::rustc_serialize::Decodable::decode(__decoder),
emit_asm: ::rustc_serialize::Decodable::decode(__decoder),
emit_obj: ::rustc_serialize::Decodable::decode(__decoder),
emit_thin_lto_summary: ::rustc_serialize::Decodable::decode(__decoder),
verify_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
lint_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
no_prepopulate_passes: ::rustc_serialize::Decodable::decode(__decoder),
no_builtins: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_loop: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_slp: ::rustc_serialize::Decodable::decode(__decoder),
merge_functions: ::rustc_serialize::Decodable::decode(__decoder),
emit_lifetime_markers: ::rustc_serialize::Decodable::decode(__decoder),
llvm_plugins: ::rustc_serialize::Decodable::decode(__decoder),
autodiff: ::rustc_serialize::Decodable::decode(__decoder),
autodiff_post_passes: ::rustc_serialize::Decodable::decode(__decoder),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
74pub struct ModuleConfig {
75/// Names of additional optimization passes to run.
76pub passes: Vec<String>,
77/// Some(level) to optimize at a certain level, or None to run
78 /// absolutely no optimizations (used for the allocator module).
79pub opt_level: Option<config::OptLevel>,
8081pub pgo_gen: SwitchWithOptPath,
82pub pgo_use: Option<PathBuf>,
83pub pgo_sample_use: Option<PathBuf>,
84pub debug_info_for_profiling: bool,
85pub instrument_coverage: bool,
8687pub sanitizer: SanitizerSet,
88pub sanitizer_cfi_diag: Option<bool>,
89pub sanitizer_cfi_recover: Option<bool>,
90pub sanitizer_recover: SanitizerSet,
91pub sanitizer_dataflow_abilist: Vec<String>,
92pub sanitizer_memory_track_origins: usize,
9394// Flags indicating which outputs to produce.
95pub emit_pre_lto_bc: bool,
96pub emit_bc: bool,
97pub emit_ir: bool,
98pub emit_asm: bool,
99pub emit_obj: EmitObj,
100pub emit_thin_lto_summary: bool,
101102// Miscellaneous flags. These are mostly copied from command-line
103 // options.
104pub verify_llvm_ir: bool,
105pub lint_llvm_ir: bool,
106pub no_prepopulate_passes: bool,
107pub no_builtins: bool,
108pub vectorize_loop: bool,
109pub vectorize_slp: bool,
110pub merge_functions: bool,
111pub emit_lifetime_markers: bool,
112pub llvm_plugins: Vec<String>,
113pub autodiff: Vec<config::AutoDiff>,
114pub autodiff_post_passes: Option<String>,
115pub offload: Vec<config::Offload>,
116}
117118impl ModuleConfig {
119pub(crate) fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120// If it's a regular module, use `$regular`, otherwise use `$other`.
121 // `$regular` and `$other` are evaluated lazily.
122macro_rules! if_regular {
123 ($regular: expr, $other: expr) => {
124if let ModuleKind::Regular = kind { $regular } else { $other }
125 };
126 }
127128let sess = tcx.sess;
129let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
130131let save_temps = sess.opts.cg.save_temps;
132133let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 };
138139let emit_obj = if !should_emit_obj {
140 EmitObj::None141 } else if sess.target.obj_is_bitcode
142 || (sess.opts.cg.linker_plugin_lto.enabled()
143 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
144 {
145// This case is selected if the target uses objects as bitcode, or
146 // if linker plugin LTO is enabled. In the linker plugin LTO case
147 // the assumption is that the final link-step will read the bitcode
148 // and convert it to object code. This may be done by either the
149 // native linker or rustc itself.
150 //
151 // By default this branch is skipped for `#![no_builtins]` crates so
152 // they emit native object files (machine code), not LLVM bitcode
153 // objects for the linker (see rust-lang/rust#146133).
154 //
155 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
156 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
157 // intrinsics and related metadata that must be lowered by LLVM's
158 // `LowerTypeTests` pass before instruction selection during
159 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
160 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
161 // reaching the target backend, and LLVM may abort during codegen
162 // (for example in SelectionDAG type legalization) (see
163 // rust-lang/rust#142284).
164 //
165 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
166 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
167 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
168EmitObj::Bitcode169 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
170 EmitObj::ObjectCode(BitcodeSection::Full)
171 } else {
172 EmitObj::ObjectCode(BitcodeSection::None)
173 };
174175ModuleConfig {
176 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
177178 opt_level: opt_level_and_size,
179180 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
181 sess.opts.cg.profile_generate.clone(),
182 SwitchWithOptPath::Disabled
183 ),
184 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
185 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_sample_use.clone(), None),
186 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
187 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
188189 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
190 sanitizer_cfi_diag: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_diag
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_diag, None),
191 sanitizer_cfi_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_recover
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_recover, None),
192 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
193 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
194 Vec::new()
195 ),
196 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
197 sess.opts.unstable_opts.sanitizer_recover,
198 SanitizerSet::empty()
199 ),
200 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
201 sess.opts.unstable_opts.sanitizer_memory_track_origins,
2020
203),
204205 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
206 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
207false
208),
209 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
210 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
211 save_temps
212 ),
213 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
214 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
215false
216),
217 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
218 sess.opts.output_types.contains_key(&OutputType::Assembly),
219false
220),
221emit_obj,
222 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
223 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
224false
225),
226227 verify_llvm_ir: sess.verify_llvm_ir(),
228 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
229 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
230 no_builtins: no_builtins || sess.target.no_builtins,
231232// Copy what clang does by turning on loop vectorization at O2 and
233 // slp vectorization at O3.
234vectorize_loop: !sess.opts.cg.no_vectorize_loops
235 && sess.optimization_objective() == OptimizationObjective::Speed,
236 vectorize_slp: !sess.opts.cg.no_vectorize_slp
237 && sess.opts.optimize == config::OptLevel::Aggressive,
238239// Some targets (namely, NVPTX) interact badly with the
240 // MergeFunctions pass. This is because MergeFunctions can generate
241 // new function calls which may interfere with the target calling
242 // convention; e.g. for the NVPTX target, PTX kernels should not
243 // call other PTX kernels. MergeFunctions can also be configured to
244 // generate aliases instead, but aliases are not supported by some
245 // backends (again, NVPTX). Therefore, allow targets to opt out of
246 // the MergeFunctions pass, but otherwise keep the pass enabled (at
247 // O2 and O3) since it can be useful for reducing code size.
248merge_functions: match sess.merge_functions() {
249 MergeFunctions::Disabled => false,
250 MergeFunctions::Trampolines | MergeFunctions::Aliases => #[allow(non_exhaustive_omitted_patterns)] match sess.optimization_objective()
{
OptimizationObjective::Speed | OptimizationObjective::Size => true,
_ => false,
}matches!(
251 sess.optimization_objective(),
252 OptimizationObjective::Speed | OptimizationObjective::Size
253 ),
254 },
255256 emit_lifetime_markers: sess.emit_lifetime_markers(),
257 llvm_plugins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.llvm_plugins.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
258 autodiff: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
259 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
260 sess.opts.unstable_opts.autodiff_post_passes.clone(),
261None
262),
263 offload: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.offload.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
264 }
265 }
266267pub fn bitcode_needed(&self) -> bool {
268self.emit_bc
269 || self.emit_thin_lto_summary
270 || self.emit_obj == EmitObj::Bitcode271 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
272 }
273274pub fn embed_bitcode(&self) -> bool {
275self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
276 }
277}
278279/// Configuration passed to the function returned by the `target_machine_factory`.
280pub struct TargetMachineFactoryConfig {
281/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
282 /// so the path to the dwarf object has to be provided when we create the target machine.
283 /// This can be ignored by backends which do not need it for their Split DWARF support.
284pub split_dwarf_file: Option<PathBuf>,
285286/// The name of the output object file. Used for setting OutputFilenames in target options
287 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
288pub output_obj_file: Option<PathBuf>,
289}
290291impl TargetMachineFactoryConfig {
292pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
293let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294cgcx.output_filenames.split_dwarf_path(
295cgcx.split_debuginfo,
296cgcx.split_dwarf_kind,
297module_name,
298 )
299 } else {
300None301 };
302303let output_obj_file =
304Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
305TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
306 }
307}
308309pub type TargetMachineFactoryFn<B> = Arc<
310dyn Fn(
311DiagCtxtHandle<'_>,
312TargetMachineFactoryConfig,
313 ) -> <B as WriteBackendMethods>::TargetMachine314 + Send315 + Sync,
316>;
317318/// Additional resources used by optimize_and_codegen (not module specific)
319#[derive(#[automatically_derived]impl ::core::clone::Clone for CodegenContext {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
CodegenContext {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
rust_eh_personality_symbol: ::core::clone::Clone::clone(&self.rust_eh_personality_symbol),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
let CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
msvc_imps_needed: ref __binding_10,
is_pe_coff: ref __binding_11,
target_can_use_split_dwarf: ref __binding_12,
target_arch: ref __binding_13,
target_is_like_darwin: ref __binding_14,
target_is_like_aix: ref __binding_15,
target_is_like_gpu: ref __binding_16,
split_debuginfo: ref __binding_17,
split_dwarf_kind: ref __binding_18,
pointer_size: ref __binding_19,
rust_eh_personality_symbol: ref __binding_20,
remark: ref __binding_21,
remark_dir: ref __binding_22,
parallel: ref __binding_23 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
rust_eh_personality_symbol: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
320pub struct CodegenContext {
321// Resources needed when running LTO
322pub lto: Lto,
323pub use_linker_plugin_lto: bool,
324pub dylib_lto: bool,
325pub prefer_dynamic: bool,
326pub save_temps: bool,
327pub fewer_names: bool,
328pub time_trace: bool,
329pub crate_types: Vec<CrateType>,
330pub output_filenames: Arc<OutputFilenames>,
331pub module_config: Arc<ModuleConfig>,
332pub msvc_imps_needed: bool,
333pub is_pe_coff: bool,
334pub target_can_use_split_dwarf: bool,
335pub target_arch: String,
336pub target_is_like_darwin: bool,
337pub target_is_like_aix: bool,
338pub target_is_like_gpu: bool,
339pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
340pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
341pub pointer_size: Size,
342pub rust_eh_personality_symbol: String,
343344/// LLVM optimizations for which we want to print remarks.
345pub remark: Passes,
346/// Directory into which should the LLVM optimization remarks be written.
347 /// If `None`, they will be written to stderr.
348pub remark_dir: Option<PathBuf>,
349/// `Some(limit)` if the codegen should be run in parallel.
350 ///
351 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
352pub parallel: Option<NonZero<usize>>,
353}
354355fn generate_thin_lto_work<B: WriteBackendMethods>(
356 cgcx: &CodegenContext,
357 prof: &SelfProfilerRef,
358 incr_comp_session: Option<&BorrowedIncrCompSession>,
359 dcx: DiagCtxtHandle<'_>,
360 exported_symbols_for_lto: &[String],
361 each_linked_rlib_for_lto: &[PathBuf],
362 needs_thin_lto: Vec<ThinLtoInput<B>>,
363) -> Vec<(ThinLtoWorkItem<B>, u64)> {
364let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
365366let (lto_modules, copy_jobs) = B::run_thin_lto(
367cgcx,
368prof,
369incr_comp_session,
370dcx,
371exported_symbols_for_lto,
372each_linked_rlib_for_lto,
373needs_thin_lto,
374 );
375lto_modules376 .into_iter()
377 .map(|module| {
378let cost = module.cost();
379 (ThinLtoWorkItem::ThinLto(module), cost)
380 })
381 .chain(copy_jobs.into_iter().map(|wp| {
382 (
383 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
384 name: wp.cgu_name.clone(),
385 source: wp,
386 }),
3870, // copying is very cheap
388)
389 }))
390 .collect()
391}
392393enum MaybeLtoModules<B: WriteBackendMethods> {
394 NoLto(CompiledModules),
395 FatLto {
396 cgcx: CodegenContext,
397 needs_fat_lto: Vec<FatLtoInput<B>>,
398 },
399 ThinLto {
400 cgcx: CodegenContext,
401 needs_thin_lto: Vec<ThinLtoInput<B>>,
402 allocator_module: Option<CompiledModule>,
403 },
404}
405406fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
407let sess = tcx.sess;
408sess.opts.cg.embed_bitcode
409 && tcx.crate_types().contains(&CrateType::Rlib)
410 && sess.opts.output_types.contains_key(&OutputType::Exe)
411}
412413fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
414if sess.opts.incremental.is_none() {
415return false;
416 }
417418match sess.lto() {
419 Lto::No => false,
420 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
421 }
422}
423424pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
425 backend: B,
426 tcx: TyCtxt<'_>,
427 regular_config: Arc<ModuleConfig>,
428 allocator_config: Arc<ModuleConfig>,
429 allocator_module: Option<ModuleCodegen<B::Module>>,
430) -> OngoingCodegen<B> {
431let (coordinator_send, coordinator_receive) = channel();
432433let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
434let (codegen_worker_send, codegen_worker_receive) = channel();
435436let coordinator_thread = start_executing_work(
437backend.clone(),
438tcx,
439shared_emitter,
440codegen_worker_send,
441coordinator_receive,
442regular_config,
443allocator_config,
444allocator_module,
445coordinator_send.clone(),
446 );
447448OngoingCodegen {
449backend,
450451codegen_worker_receive,
452shared_emitter_main,
453 coordinator: Coordinator {
454 sender: coordinator_send,
455 future: Some(coordinator_thread),
456 phantom: PhantomData,
457 },
458 output_filenames: Arc::clone(tcx.output_filenames(())),
459 }
460}
461462fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
463 sess: &Session,
464 incr_comp_session: &mut IncrCompSession,
465 compiled_modules: &CompiledModules,
466) {
467if sess.opts.unstable_opts.disable_incr_comp_backend_caching {
468return;
469 }
470471let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
472473for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
474let mut files = Vec::new();
475if let Some(object_file_path) = &module.object {
476 files.push((OutputType::Object.extension(), object_file_path.as_path()));
477 }
478if let Some(global_asm_object_file_path) = &module.global_asm_object {
479 files.push(("asm.o", global_asm_object_file_path.as_path()));
480 }
481if let Some(dwarf_object_file_path) = &module.dwarf_object {
482 files.push(("dwo", dwarf_object_file_path.as_path()));
483 }
484if let Some(path) = &module.assembly {
485 files.push((OutputType::Assembly.extension(), path.as_path()));
486 }
487if let Some(path) = &module.llvm_ir {
488 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
489 }
490if let Some(path) = &module.bytecode {
491 files.push((OutputType::Bitcode.extension(), path.as_path()));
492 }
493 copy_cgu_workproduct_to_incr_comp_cache_dir(
494 sess,
495 incr_comp_session,
496&module.name,
497 files.as_slice(),
498 );
499 }
500}
501502pub fn produce_final_output_artifacts(
503 sess: &Session,
504 compiled_modules: &CompiledModules,
505 crate_output: &OutputFilenames,
506) {
507let mut user_wants_bitcode = false;
508let mut user_wants_objects = false;
509510// Produce final compile outputs.
511let copy_gracefully = |from: &Path, to: &OutFileName| match to {
512 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
513sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
514 }
515 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
516sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
517 }
518_ => {}
519 };
520521let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
522if let [module] = &compiled_modules.modules[..] {
523// 1) Only one codegen unit. In this case it's no difficulty
524 // to copy `foo.0.x` to `foo.x`.
525let path = crate_output.temp_path_for_cgu(output_type, &module.name);
526let output = crate_output.path(output_type);
527if !output_type.is_text_output() && output.is_tty() {
528sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
529 shorthand: output_type.shorthand(),
530 });
531 } else {
532copy_gracefully(&path, &output);
533 }
534if !sess.opts.cg.save_temps && !keep_numbered {
535// The user just wants `foo.x`, not `foo.#module-name#.x`.
536ensure_removed(sess.dcx(), &path);
537 }
538 } else {
539if crate_output.outputs.contains_explicit_name(&output_type) {
540// 2) Multiple codegen units, with `--emit foo=some_name`. We have
541 // no good solution for this case, so warn the user.
542sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
543 extension: output_type.extension(),
544 });
545 } else if crate_output.single_output_file.is_some() {
546// 3) Multiple codegen units, with `-o some_name`. We have
547 // no good solution for this case, so warn the user.
548sess.dcx()
549 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
550 } else {
551// 4) Multiple codegen units, but no explicit name. We
552 // just leave the `foo.0.x` files in place.
553 // (We don't have to do any work in this case.)
554}
555 }
556 };
557558// Flag to indicate whether the user explicitly requested bitcode.
559 // Otherwise, we produced it only as a temporary output, and will need
560 // to get rid of it.
561for output_type in crate_output.outputs.keys() {
562match *output_type {
563 OutputType::Bitcode => {
564 user_wants_bitcode = true;
565// Copy to .bc, but always keep the .0.bc. There is a later
566 // check to figure out if we should delete .0.bc files, or keep
567 // them for making an rlib.
568copy_if_one_unit(OutputType::Bitcode, true);
569 }
570 OutputType::ThinLinkBitcode => {
571 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
572 }
573 OutputType::LlvmAssembly => {
574 copy_if_one_unit(OutputType::LlvmAssembly, false);
575 }
576 OutputType::Assembly => {
577 copy_if_one_unit(OutputType::Assembly, false);
578 }
579 OutputType::Object => {
580 user_wants_objects = true;
581 copy_if_one_unit(OutputType::Object, true);
582 }
583 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
584 }
585 }
586587// Clean up unwanted temporary files.
588589 // We create the following files by default:
590 // - #crate#.#module-name#.rcgu.bc
591 // - #crate#.#module-name#.rcgu.o
592 // - #crate#.o (linked from crate.##.rcgu.o)
593 // - #crate#.bc (copied from crate.##.rcgu.bc)
594 // We may create additional files if requested by the user (through
595 // `-C save-temps` or `--emit=` flags).
596597if !sess.opts.cg.save_temps {
598// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
599 // explicitly request bitcode (with --emit=bc), and the bitcode is not
600 // needed for building an rlib, then we must remove .#module-name#.bc as
601 // well.
602603 // Specific rules for keeping .#module-name#.rcgu.bc:
604 // - If the user requested bitcode (`user_wants_bitcode`), and
605 // codegen_units > 1, then keep it.
606 // - If the user requested bitcode but codegen_units == 1, then we
607 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
608 // - If we're not building an rlib and the user didn't request
609 // bitcode, then delete .#module-name#.rcgu.bc.
610 // If you change how this works, also update back::link::link_rlib,
611 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
612 // rlib.
613let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
614615let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
616617let keep_numbered_objects =
618needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
619620for module in compiled_modules.modules.iter() {
621if !keep_numbered_objects {
622if let Some(ref path) = module.object {
623 ensure_removed(sess.dcx(), path);
624 }
625626if let Some(ref path) = module.global_asm_object {
627 ensure_removed(sess.dcx(), path);
628 }
629630if let Some(ref path) = module.dwarf_object {
631 ensure_removed(sess.dcx(), path);
632 }
633 }
634635if let Some(ref path) = module.bytecode {
636if !keep_numbered_bitcode {
637 ensure_removed(sess.dcx(), path);
638 }
639 }
640 }
641642if !user_wants_bitcode643 && let Some(ref allocator_module) = compiled_modules.allocator_module
644 && let Some(ref path) = allocator_module.bytecode
645 {
646ensure_removed(sess.dcx(), path);
647 }
648 }
649650if sess.opts.json_artifact_notifications {
651if let [module] = &compiled_modules.modules[..] {
652module.for_each_output(|_path, ty| {
653if sess.opts.output_types.contains_key(&ty) {
654let descr = ty.shorthand();
655// for single cgu file is renamed to drop cgu specific suffix
656 // so we regenerate it the same way
657let path = crate_output.path(ty);
658sess.dcx().emit_artifact_notification(path.as_path(), descr);
659 }
660 });
661 } else {
662for module in &compiled_modules.modules {
663 module.for_each_output(|path, ty| {
664if sess.opts.output_types.contains_key(&ty) {
665let descr = ty.shorthand();
666 sess.dcx().emit_artifact_notification(&path, descr);
667 }
668 });
669 }
670 }
671 }
672673// We leave the following files around by default:
674 // - #crate#.o
675 // - #crate#.bc
676 // These are used in linking steps and will be cleaned up afterward.
677}
678679pub(crate) enum WorkItem<B: WriteBackendMethods> {
680/// Optimize a newly codegened, totally unoptimized module.
681Optimize(ModuleCodegen<B::Module>),
682/// Copy the post-LTO artifacts from the incremental cache to the output
683 /// directory.
684CopyPostLtoArtifacts(CachedModuleCodegen),
685}
686687enum ThinLtoWorkItem<B: WriteBackendMethods> {
688/// Copy the post-LTO artifacts from the incremental cache to the output
689 /// directory.
690CopyPostLtoArtifacts(CachedModuleCodegen),
691/// Performs thin-LTO on the given module.
692ThinLto(lto::ThinModule<B>),
693}
694695// `pthread_setname()` on *nix ignores anything beyond the first 15
696// bytes. Use short descriptions to maximize the space available for
697// the module name.
698#[cfg(not(windows))]
699fn desc(short: &str, _long: &str, name: &str) -> String {
700// The short label is three bytes, and is followed by a space. That
701 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
702 // depends on the CGU name form.
703 //
704 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
705 // before the `-cgu.0` is the same for every CGU, so use the
706 // `cgu.0` part. The number suffix will be different for each
707 // CGU.
708 //
709 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
710 // name because each CGU will have a unique ASCII hash, and the
711 // first 11 bytes will be enough to identify it.
712 //
713 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
714 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
715 // name. The first 11 bytes won't be enough to uniquely identify
716 // it, but no obvious substring will, and this is a rarely used
717 // option so it doesn't matter much.
718 //
719{
match (&short.len(), &3) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(short.len(), 3);
720let name = if let Some(index) = name.find("-cgu.") {
721&name[index + 1..] // +1 skips the leading '-'.
722} else {
723name724 };
725::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")726}
727728// Windows has no thread name length limit, so use more descriptive names.
729#[cfg(windows)]
730fn desc(_short: &str, long: &str, name: &str) -> String {
731format!("{long} {name}")
732}
733734impl<B: WriteBackendMethods> WorkItem<B> {
735/// Generate a short description of this work item suitable for use as a thread name.
736fn short_description(&self) -> String {
737match self {
738 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
739 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
740 }
741 }
742}
743744impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
745/// Generate a short description of this work item suitable for use as a thread name.
746fn short_description(&self) -> String {
747match self {
748 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
749desc("cpy", "copy LTO artifacts for", &m.name)
750 }
751 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
752 }
753 }
754}
755756/// A result produced by the backend.
757pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
758/// The backend has finished compiling a CGU, nothing more required.
759Finished(CompiledModule),
760761/// The backend has finished compiling a CGU, which now needs to go through
762 /// fat LTO.
763NeedsFatLto(FatLtoInput<B>),
764765/// The backend has finished compiling a CGU, which now needs to go through
766 /// thin LTO.
767NeedsThinLto(String, B::ModuleBuffer),
768}
769770pub enum FatLtoInput<B: WriteBackendMethods> {
771 Serialized { name: String, bitcode_path: PathBuf },
772 InMemory(ModuleCodegen<B::Module>),
773}
774775pub enum ThinLtoInput<B: WriteBackendMethods> {
776 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
777 Green { wp: WorkProduct, bitcode_path: PathBuf },
778}
779780/// Actual LTO type we end up choosing based on multiple factors.
781pub(crate) enum ComputedLtoType {
782 No,
783 Thin,
784 Fat,
785}
786787pub(crate) fn compute_per_cgu_lto_type(
788 sess_lto: &Lto,
789 linker_does_lto: bool,
790 sess_crate_types: &[CrateType],
791) -> ComputedLtoType {
792// If the linker does LTO, we don't have to do it. Note that we
793 // keep doing full LTO, if it is requested, as not to break the
794 // assumption that the output will be a single module.
795796 // We ignore a request for full crate graph LTO if the crate type
797 // is only an rlib, as there is no full crate graph to process,
798 // that'll happen later.
799 //
800 // This use case currently comes up primarily for targets that
801 // require LTO so the request for LTO is always unconditionally
802 // passed down to the backend, but we don't actually want to do
803 // anything about it yet until we've got a final product.
804let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
805806match sess_lto {
807 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
808 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
809 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
810_ => ComputedLtoType::No,
811 }
812}
813814fn execute_optimize_work_item<B: WriteBackendMethods>(
815 cgcx: &CodegenContext,
816 prof: &SelfProfilerRef,
817 new_incr_comp_session_dir: Option<&Path>,
818 shared_emitter: SharedEmitter,
819mut module: ModuleCodegen<B::Module>,
820) -> WorkItemResult<B> {
821let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
822823 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
824825// After we've done the initial round of optimizations we need to
826 // decide whether to synchronously codegen this module or ship it
827 // back to the coordinator thread for further LTO processing (which
828 // has to wait for all the initial modules to be optimized).
829830let lto_type =
831compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
832833// If we're doing some form of incremental LTO then we need to be sure to
834 // save our module to disk first.
835let bitcode = if cgcx.module_config.emit_pre_lto_bc {
836let filename = pre_lto_bitcode_filename(&module.name);
837new_incr_comp_session_dir.map(|path| path.join(&filename))
838 } else {
839None840 };
841842match lto_type {
843 ComputedLtoType::No => {
844let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
845 WorkItemResult::Finished(module)
846 }
847 ComputedLtoType::Thin => {
848let thin_buffer = B::serialize_module(module.module_llvm, true);
849if let Some(path) = bitcode {
850 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
851{
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
852 });
853 }
854 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
855 }
856 ComputedLtoType::Fat => match bitcode {
857Some(path) => {
858let buffer = B::serialize_module(module.module_llvm, false);
859 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
860{
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
861 });
862 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
863 name: module.name,
864 bitcode_path: path,
865 })
866 }
867None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
868 },
869 }
870}
871872fn execute_copy_from_cache_work_item(
873 cgcx: &CodegenContext,
874 prof: &SelfProfilerRef,
875 old_incr_comp_session_dir: &Path,
876 shared_emitter: SharedEmitter,
877 module: CachedModuleCodegen,
878) -> CompiledModule {
879let _timer =
880prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
881882let dcx = DiagCtxt::new(Box::new(shared_emitter));
883let dcx = dcx.handle();
884885let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
886let source_file_in_incr_comp_dir = old_incr_comp_session_dir.join(saved_path);
887{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/write.rs:887",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(887u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file_in_incr_comp_dir,
output_path.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
888"copying preexisting module `{}` from {:?} to {}",
889 module.name,
890 source_file_in_incr_comp_dir,
891 output_path.display()
892 );
893match link_or_copy(
894&source_file_in_incr_comp_dir,
895&output_path,
896true, // allow_overwrite
897) {
898Ok(_) => Some(output_path),
899Err(error) => {
900dcx.emit_err(diagnostics::CopyPathBuf {
901 source_file: source_file_in_incr_comp_dir,
902output_path,
903error,
904 });
905None906 }
907 }
908 };
909910let dwarf_object =
911module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
912let dwarf_obj_out = cgcx913 .output_filenames
914 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
915 .expect(
916"saved dwarf object in work product but `split_dwarf_path` returned `None`",
917 );
918load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
919 });
920921let load_from_incr_cache = |perform, output_type: OutputType| {
922if perform {
923let saved_file = module.source.saved_files.get(output_type.extension())?;
924let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
925load_from_incr_comp_dir(output_path, &saved_file)
926 } else {
927None928 }
929 };
930931let module_config = &cgcx.module_config;
932let should_emit_obj = module_config.emit_obj != EmitObj::None;
933let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
934let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
935let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
936let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
937let global_asm_object =
938if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
939let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
940load_from_incr_comp_dir(output_path, &saved_file)
941 } else {
942None943 };
944if should_emit_obj && object.is_none() {
945dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
946 }
947948CompiledModule {
949 kind: ModuleKind::Regular,
950 name: module.name,
951object,
952global_asm_object,
953dwarf_object,
954bytecode,
955assembly,
956llvm_ir,
957 }
958}
959960fn do_fat_lto<B: WriteBackendMethods>(
961 sess: &Session,
962 cgcx: &CodegenContext,
963 shared_emitter: SharedEmitter,
964 tm_factory: TargetMachineFactoryFn<B>,
965 exported_symbols_for_lto: &[String],
966 each_linked_rlib_for_lto: &[PathBuf],
967 needs_fat_lto: Vec<FatLtoInput<B>>,
968) -> CompiledModule {
969let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
970971let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
972let dcx = dcx.handle();
973974check_lto_allowed(&cgcx, dcx);
975976 B::optimize_and_codegen_fat_lto(
977sess,
978cgcx,
979&shared_emitter,
980tm_factory,
981exported_symbols_for_lto,
982each_linked_rlib_for_lto,
983needs_fat_lto,
984 )
985}
986987fn do_thin_lto<B: WriteBackendMethods>(
988 cgcx: &CodegenContext,
989 prof: &SelfProfilerRef,
990 incr_comp_session: Option<BorrowedIncrCompSession>,
991 shared_emitter: SharedEmitter,
992 tm_factory: TargetMachineFactoryFn<B>,
993 exported_symbols_for_lto: &[String],
994 each_linked_rlib_for_lto: &[PathBuf],
995 needs_thin_lto: Vec<ThinLtoInput<B>>,
996 stack_size: usize,
997) -> Vec<CompiledModule> {
998let _timer = prof.verbose_generic_activity("LLVM_thinlto");
9991000let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1001let dcx = dcx.handle();
10021003check_lto_allowed(&cgcx, dcx);
10041005let (coordinator_send, coordinator_receive) = channel();
10061007// First up, convert our jobserver into a helper thread so we can use normal
1008 // mpsc channels to manage our messages and such.
1009 // After we've requested tokens then we'll, when we can,
1010 // get tokens on `coordinator_receive` which will
1011 // get managed in the main loop below.
1012 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1013 // tokens before releasing them, so we can never accidentally release the last token
1014 // permanently held by rustc process.
1015let jobserver_helper = cgcx.parallel.map(|_| {
1016let coordinator_send2 = coordinator_send.clone();
1017 jobserver::client()
1018 .into_helper_thread(move |token| {
1019drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1020 })
1021 .expect("failed to spawn helper thread")
1022 });
10231024let mut work_items = ::alloc::vec::Vec::new()vec![];
10251026// We have LTO work to do. Perform the serial work here of
1027 // figuring out what we're going to LTO and then push a
1028 // bunch of work items onto our queue to do LTO. This all
1029 // happens on the coordinator thread but it's very quick so
1030 // we don't worry about tokens.
1031for (i, (work, cost)) in generate_thin_lto_work::<B>(
1032 cgcx,
1033 prof,
1034 incr_comp_session.as_ref(),
1035 dcx,
1036&exported_symbols_for_lto,
1037&each_linked_rlib_for_lto,
1038 needs_thin_lto,
1039 )
1040 .into_iter()
1041 .enumerate()
1042 {
1043let insertion_index =
1044 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1045 work_items.insert(insertion_index, (work, cost));
1046if let Some(helper) = &jobserver_helper
1047 && i < cgcx.parallel.unwrap().get()
1048 {
1049 helper.request_token();
1050 }
1051 }
10521053let mut codegen_aborted = None;
10541055// These are the Jobserver Tokens we currently hold. Does not include
1056 // the implicit Token the compiler process owns no matter what.
1057let mut tokens = ::alloc::vec::Vec::new()vec![];
10581059// Amount of tokens that are used (including the implicit token).
1060let mut used_token_count = 0;
10611062let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10631064// Run the message loop while there's still anything that needs message
1065 // processing. Note that as soon as codegen is aborted we simply want to
1066 // wait for all existing work to finish, so many of the conditions here
1067 // only apply if codegen hasn't been aborted as they represent pending
1068 // work to be done.
1069loop {
1070if codegen_aborted.is_none() {
1071if used_token_count == 0 && work_items.is_empty() {
1072// All codegen work is done.
1073break;
1074 }
10751076// Spin up what work we can, only doing this while we've got available
1077 // parallelism slots and work left to spawn.
1078while used_token_count < tokens.len() + 1
1079&& let Some((item, _)) = work_items.pop()
1080 {
1081 spawn_thin_lto_work(
1082&cgcx,
1083 prof,
1084 incr_comp_session
1085 .as_ref()
1086 .and_then(|incr_comp_session| {
1087 incr_comp_session.old_session_directory.as_deref()
1088 })
1089 .map(ToOwned::to_owned),
1090 shared_emitter.clone(),
1091 Arc::clone(&tm_factory),
1092 coordinator_send.clone(),
1093 item,
1094 stack_size,
1095 );
1096 used_token_count += 1;
1097 }
1098 } else {
1099// Don't queue up any more work if codegen was aborted, we're
1100 // just waiting for our existing children to finish.
1101if used_token_count == 0 {
1102break;
1103 }
1104 }
11051106// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1107tokens.truncate(used_token_count.saturating_sub(1));
11081109match coordinator_receive.recv().unwrap() {
1110// Save the token locally and the next turn of the loop will use
1111 // this to spawn a new unit of work, or it may get dropped
1112 // immediately if we have no more work to spawn.
1113ThinLtoMessage::Token(token) => match token {
1114Ok(token) => {
1115tokens.push(token);
1116 }
1117Err(e) => {
1118let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1119shared_emitter.fatal(msg);
1120codegen_aborted = Some(FatalError);
1121 }
1122 },
11231124 ThinLtoMessage::WorkItem { result } => {
1125// If a thread exits successfully then we drop a token associated
1126 // with that worker and update our `used_token_count` count.
1127 // We may later re-acquire a token to continue running more work.
1128 // We may also not actually drop a token here if the worker was
1129 // running with an "ephemeral token".
1130used_token_count -= 1;
11311132match result {
1133Ok(compiled_module) => compiled_modules.push(compiled_module),
1134Err(Some(WorkerFatalError)) => {
1135// Like `CodegenAborted`, wait for remaining work to finish.
1136codegen_aborted = Some(FatalError);
1137 }
1138Err(None) => {
1139// If the thread failed that means it panicked, so
1140 // we abort immediately.
1141::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1142 }
1143 }
1144 }
1145 }
1146 }
11471148if let Some(codegen_aborted) = codegen_aborted {
1149codegen_aborted.raise();
1150 }
11511152compiled_modules1153}
11541155/// Messages sent to the coordinator.
1156pub(crate) enum Message<B: WriteBackendMethods> {
1157/// A jobserver token has become available. Sent from the jobserver helper
1158 /// thread.
1159Token(io::Result<Acquired>),
11601161/// The backend has finished processing a work item for a codegen unit.
1162 /// Sent from a backend worker thread.
1163WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11641165/// The frontend has finished generating something (backend IR or a
1166 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1167 /// backend. Sent from the main thread.
1168CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11691170/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1171 /// Sent from the main thread.
1172AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11731174/// The frontend has finished generating everything for all codegen units.
1175 /// Sent from the main thread.
1176CodegenComplete,
11771178/// Some normal-ish compiler error occurred, and codegen should be wound
1179 /// down. Sent from the main thread.
1180CodegenAborted,
1181}
11821183/// Messages sent to the coordinator.
1184pub(crate) enum ThinLtoMessage {
1185/// A jobserver token has become available. Sent from the jobserver helper
1186 /// thread.
1187Token(io::Result<Acquired>),
11881189/// The backend has finished processing a work item for a codegen unit.
1190 /// Sent from a backend worker thread.
1191WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1192}
11931194/// A message sent from the coordinator thread to the main thread telling it to
1195/// process another codegen unit.
1196pub struct CguMessage;
11971198#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
MainThreadState {
}
#[automatically_derived]impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for MainThreadState {
}
#[automatically_derived]impl ::core::clone::Clone for MainThreadState {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]impl ::core::fmt::Debug for MainThreadState {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1199enum MainThreadState {
1200/// Doing nothing.
1201Idle,
12021203/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1204Codegenning,
12051206/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1207Lending,
1208}
12091210fn start_executing_work<B: WriteBackendMethods>(
1211 backend: B,
1212 tcx: TyCtxt<'_>,
1213 shared_emitter: SharedEmitter,
1214 codegen_worker_send: Sender<CguMessage>,
1215 coordinator_receive: Receiver<Message<B>>,
1216 regular_config: Arc<ModuleConfig>,
1217 allocator_config: Arc<ModuleConfig>,
1218mut allocator_module: Option<ModuleCodegen<B::Module>>,
1219 coordinator_send: Sender<Message<B>>,
1220) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1221let sess = tcx.sess;
1222let prof = sess.prof.clone();
1223let incr_comp_session =
1224tcx.incr_comp_session.map(|incr_comp_session| incr_comp_session.borrow());
12251226// First up, convert our jobserver into a helper thread so we can use normal
1227 // mpsc channels to manage our messages and such.
1228 // After we've requested tokens then we'll, when we can,
1229 // get tokens on `coordinator_receive` which will
1230 // get managed in the main loop below.
1231 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1232 // tokens before releasing them, so we can never accidentally release the last token
1233 // permanently held by rustc process.
1234let parallel = match sess.opts.jobs.backend {
1235 JobsMode::Parallel(n) if backend.supports_parallel() => Some(n),
1236_ => None,
1237 };
1238let jobserver_helper = parallel.map(|_| {
1239let coordinator_send2 = coordinator_send.clone();
1240 jobserver::client()
1241 .into_helper_thread(move |token| {
1242drop(coordinator_send2.send(Message::Token::<B>(token)));
1243 })
1244 .expect("failed to spawn helper thread")
1245 });
12461247let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1248let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1249match result {
1250Ok(dir) => Some(dir),
1251Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1252 }
1253 } else {
1254None1255 };
12561257let stack_size = sess.opts.recommended_stack_size;
12581259let cgcx = CodegenContext {
1260 crate_types: tcx.crate_types().to_vec(),
1261 lto: sess.lto(),
1262 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1263 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1264 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1265 fewer_names: sess.fewer_names(),
1266 save_temps: sess.opts.cg.save_temps,
1267 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1268 remark: sess.opts.cg.remark.clone(),
1269remark_dir,
1270 output_filenames: Arc::clone(tcx.output_filenames(())),
1271 module_config: regular_config,
1272 msvc_imps_needed: msvc_imps_needed(tcx),
1273 is_pe_coff: tcx.sess.target.is_like_windows,
1274 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1275 target_arch: tcx.sess.target.arch.to_string(),
1276 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1277 target_is_like_aix: tcx.sess.target.is_like_aix,
1278 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1279 rust_eh_personality_symbol: rustc_symbol_mangling::eh_personality_symbol(tcx),
1280 split_debuginfo: tcx.sess.split_debuginfo(),
1281 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1282parallel,
1283 pointer_size: tcx.data_layout.pointer_size(),
1284 };
12851286// This is the "main loop" of parallel work happening for parallel codegen.
1287 // It's here that we manage parallelism, schedule work, and work with
1288 // messages coming from clients.
1289 //
1290 // There are a few environmental pre-conditions that shape how the system
1291 // is set up:
1292 //
1293 // - Error reporting can only happen on the main thread because that's the
1294 // only place where we have access to the compiler `Session`.
1295 // - LLVM work can be done on any thread.
1296 // - Codegen can only happen on the main thread.
1297 // - Each thread doing substantial work must be in possession of a `Token`
1298 // from the `Jobserver`.
1299 // - The compiler process always holds one `Token`. Any additional `Tokens`
1300 // have to be requested from the `Jobserver`.
1301 //
1302 // Error Reporting
1303 // ===============
1304 // The error reporting restriction is handled separately from the rest: We
1305 // set up a `SharedEmitter` that holds an open channel to the main thread.
1306 // When an error occurs on any thread, the shared emitter will send the
1307 // error message to the receiver main thread (`SharedEmitterMain`). The
1308 // main thread will periodically query this error message queue and emit
1309 // any error messages it has received. It might even abort compilation if
1310 // it has received a fatal error. In this case we rely on all other threads
1311 // being torn down automatically with the main thread.
1312 // Since the main thread will often be busy doing codegen work, error
1313 // reporting will be somewhat delayed, since the message queue can only be
1314 // checked in between two work packages.
1315 //
1316 // Work Processing Infrastructure
1317 // ==============================
1318 // The work processing infrastructure knows three major actors:
1319 //
1320 // - the coordinator thread,
1321 // - the main thread, and
1322 // - LLVM worker threads
1323 //
1324 // The coordinator thread is running a message loop. It instructs the main
1325 // thread about what work to do when, and it will spawn off LLVM worker
1326 // threads as open LLVM WorkItems become available.
1327 //
1328 // The job of the main thread is to codegen CGUs into LLVM work packages
1329 // (since the main thread is the only thread that can do this). The main
1330 // thread will block until it receives a message from the coordinator, upon
1331 // which it will codegen one CGU, send it to the coordinator and block
1332 // again. This way the coordinator can control what the main thread is
1333 // doing.
1334 //
1335 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1336 // available, it will spawn off a new LLVM worker thread and let it process
1337 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1338 // it will just shut down, which also frees all resources associated with
1339 // the given LLVM module, and sends a message to the coordinator that the
1340 // WorkItem has been completed.
1341 //
1342 // Work Scheduling
1343 // ===============
1344 // The scheduler's goal is to minimize the time it takes to complete all
1345 // work there is, however, we also want to keep memory consumption low
1346 // if possible. These two goals are at odds with each other: If memory
1347 // consumption were not an issue, we could just let the main thread produce
1348 // LLVM WorkItems at full speed, assuring maximal utilization of
1349 // Tokens/LLVM worker threads. However, since codegen is usually faster
1350 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1351 // WorkItem potentially holds on to a substantial amount of memory.
1352 //
1353 // So the actual goal is to always produce just enough LLVM WorkItems as
1354 // not to starve our LLVM worker threads. That means, once we have enough
1355 // WorkItems in our queue, we can block the main thread, so it does not
1356 // produce more until we need them.
1357 //
1358 // Doing LLVM Work on the Main Thread
1359 // ----------------------------------
1360 // Since the main thread owns the compiler process's implicit `Token`, it is
1361 // wasteful to keep it blocked without doing any work. Therefore, what we do
1362 // in this case is: We spawn off an additional LLVM worker thread that helps
1363 // reduce the queue. The work it is doing corresponds to the implicit
1364 // `Token`. The coordinator will mark the main thread as being busy with
1365 // LLVM work. (The actual work happens on another OS thread but we just care
1366 // about `Tokens`, not actual threads).
1367 //
1368 // When any LLVM worker thread finishes while the main thread is marked as
1369 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1370 // of the just finished thread to the LLVM worker thread that is working on
1371 // behalf of the main thread's implicit Token, thus freeing up the main
1372 // thread again. The coordinator can then again decide what the main thread
1373 // should do. This allows the coordinator to make decisions at more points
1374 // in time.
1375 //
1376 // Striking a Balance between Throughput and Memory Consumption
1377 // ------------------------------------------------------------
1378 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1379 // memory consumption as low as possible, are in conflict with each other,
1380 // we have to find a trade off between them. Right now, the goal is to keep
1381 // all workers busy, which means that no worker should find the queue empty
1382 // when it is ready to start.
1383 // How do we do achieve this? Good question :) We actually never know how
1384 // many `Tokens` are potentially available so it's hard to say how much to
1385 // fill up the queue before switching the main thread to LLVM work. Also we
1386 // currently don't have a means to estimate how long a running LLVM worker
1387 // will still be busy with it's current WorkItem. However, we know the
1388 // maximal count of available Tokens that makes sense (=the number of CPU
1389 // cores), so we can take a conservative guess. The heuristic we use here
1390 // is implemented in the `queue_full_enough()` function.
1391 //
1392 // Some Background on Jobservers
1393 // -----------------------------
1394 // It's worth also touching on the management of parallelism here. We don't
1395 // want to just spawn a thread per work item because while that's optimal
1396 // parallelism it may overload a system with too many threads or violate our
1397 // configuration for the maximum amount of cpu to use for this process. To
1398 // manage this we use the `jobserver` crate.
1399 //
1400 // Job servers are an artifact of GNU make and are used to manage
1401 // parallelism between processes. A jobserver is a glorified IPC semaphore
1402 // basically. Whenever we want to run some work we acquire the semaphore,
1403 // and whenever we're done with that work we release the semaphore. In this
1404 // manner we can ensure that the maximum number of parallel workers is
1405 // capped at any one point in time.
1406 //
1407 // LTO and the coordinator thread
1408 // ------------------------------
1409 //
1410 // The final job the coordinator thread is responsible for is managing LTO
1411 // and how that works. When LTO is requested what we'll do is collect all
1412 // optimized LLVM modules into a local vector on the coordinator. Once all
1413 // modules have been codegened and optimized we hand this to the `lto`
1414 // module for further optimization. The `lto` module will return back a list
1415 // of more modules to work on, which the coordinator will continue to spawn
1416 // work for.
1417 //
1418 // Each LLVM module is automatically sent back to the coordinator for LTO if
1419 // necessary. There's already optimizations in place to avoid sending work
1420 // back to the coordinator if LTO isn't requested.
1421let f = move || {
1422let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14231424// This is where we collect codegen units that have gone all the way
1425 // through codegen and LLVM.
1426let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1427let mut needs_fat_lto = Vec::new();
1428let mut needs_thin_lto = Vec::new();
1429let mut lto_import_only_modules = Vec::new();
14301431/// Possible state transitions:
1432 /// - Ongoing -> Completed
1433 /// - Ongoing -> Aborted
1434 /// - Completed -> Aborted
1435#[derive(#[automatically_derived]impl ::core::fmt::Debug for CodegenState {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
CodegenState {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1436enum CodegenState {
1437 Ongoing,
1438 Completed,
1439 Aborted,
1440 }
1441use CodegenState::*;
1442let mut codegen_state = Ongoing;
14431444// This is the queue of LLVM work items that still need processing.
1445let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14461447// This are the Jobserver Tokens we currently hold. Does not include
1448 // the implicit Token the compiler process owns no matter what.
1449let mut tokens = Vec::new();
14501451let mut main_thread_state = MainThreadState::Idle;
14521453// How many LLVM worker threads are running while holding a Token. This
1454 // *excludes* any that the main thread is lending a Token to.
1455let mut running_with_own_token = 0;
14561457// How many LLVM worker threads are running in total. This *includes*
1458 // any that the main thread is lending a Token to.
1459let running_with_any_token = |main_thread_state, running_with_own_token| {
1460running_with_own_token1461 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1462 };
14631464let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14651466if let Some(allocator_module) = &mut allocator_module {
1467 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1468 }
14691470// Run the message loop while there's still anything that needs message
1471 // processing. Note that as soon as codegen is aborted we simply want to
1472 // wait for all existing work to finish, so many of the conditions here
1473 // only apply if codegen hasn't been aborted as they represent pending
1474 // work to be done.
1475loop {
1476// While there are still CGUs to be codegened, the coordinator has
1477 // to decide how to utilize the compiler processes implicit Token:
1478 // For codegenning more CGU or for running them through LLVM.
1479if codegen_state == Ongoing {
1480if main_thread_state == MainThreadState::Idle {
1481// Compute the number of workers that will be running once we've taken as many
1482 // items from the work queue as we can, plus one for the main thread. It's not
1483 // critically important that we use this instead of just
1484 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1485 // from fluctuating just because a worker finished up and we decreased the
1486 // `running_with_own_token` count, even though we're just going to increase it
1487 // right after this when we put a new worker to work.
1488let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1489let additional_running = std::cmp::min(extra_tokens, work_items.len());
1490let anticipated_running = running_with_own_token + additional_running + 1;
14911492if !queue_full_enough(work_items.len(), anticipated_running) {
1493// The queue is not full enough, process more codegen units:
1494if codegen_worker_send.send(CguMessage).is_err() {
1495{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1496 }
1497main_thread_state = MainThreadState::Codegenning;
1498 } else {
1499// The queue is full enough to not let the worker
1500 // threads starve. Use the implicit Token to do some
1501 // LLVM work too.
1502let (item, _) =
1503work_items.pop().expect("queue empty - queue_full_enough() broken?");
1504main_thread_state = MainThreadState::Lending;
1505spawn_work(
1506&cgcx,
1507&prof,
1508incr_comp_session.as_ref(),
1509shared_emitter.clone(),
1510coordinator_send.clone(),
1511&mut llvm_start_time,
1512item,
1513stack_size,
1514 );
1515 }
1516 }
1517 } else if codegen_state == Completed {
1518if running_with_any_token(main_thread_state, running_with_own_token) == 0
1519&& work_items.is_empty()
1520 {
1521// All codegen work is done.
1522break;
1523 }
15241525// In this branch, we know that everything has been codegened,
1526 // so it's just a matter of determining whether the implicit
1527 // Token is free to use for LLVM work.
1528match main_thread_state {
1529 MainThreadState::Idle => {
1530if let Some((item, _)) = work_items.pop() {
1531main_thread_state = MainThreadState::Lending;
1532spawn_work(
1533&cgcx,
1534&prof,
1535incr_comp_session.as_ref(),
1536shared_emitter.clone(),
1537coordinator_send.clone(),
1538&mut llvm_start_time,
1539item,
1540stack_size,
1541 );
1542 } else {
1543// There is no unstarted work, so let the main thread
1544 // take over for a running worker. Otherwise the
1545 // implicit token would just go to waste.
1546 // We reduce the `running` counter by one. The
1547 // `tokens.truncate()` below will take care of
1548 // giving the Token back.
1549if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1550running_with_own_token -= 1;
1551main_thread_state = MainThreadState::Lending;
1552 }
1553 }
1554 MainThreadState::Codegenning => ::rustc_span::macros::bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1555"codegen worker should not be codegenning after \
1556 codegen was already completed"
1557),
1558 MainThreadState::Lending => {
1559// Already making good use of that token
1560}
1561 }
1562 } else {
1563// Don't queue up any more work if codegen was aborted, we're
1564 // just waiting for our existing children to finish.
1565if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1566if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1567break;
1568 }
1569 }
15701571// Spin up what work we can, only doing this while we've got available
1572 // parallelism slots and work left to spawn.
1573if codegen_state != Aborted {
1574while running_with_own_token < tokens.len()
1575 && let Some((item, _)) = work_items.pop()
1576 {
1577 spawn_work(
1578&cgcx,
1579&prof,
1580 incr_comp_session.as_ref(),
1581 shared_emitter.clone(),
1582 coordinator_send.clone(),
1583&mut llvm_start_time,
1584 item,
1585 stack_size,
1586 );
1587 running_with_own_token += 1;
1588 }
1589 }
15901591// Relinquish accidentally acquired extra tokens.
1592tokens.truncate(running_with_own_token);
15931594match coordinator_receive.recv().unwrap() {
1595// Save the token locally and the next turn of the loop will use
1596 // this to spawn a new unit of work, or it may get dropped
1597 // immediately if we have no more work to spawn.
1598Message::Token(token) => {
1599match token {
1600Ok(token) => {
1601tokens.push(token);
16021603if main_thread_state == MainThreadState::Lending {
1604// If the main thread token is used for LLVM work
1605 // at the moment, we turn that thread into a regular
1606 // LLVM worker thread, so the main thread is free
1607 // to react to codegen demand.
1608main_thread_state = MainThreadState::Idle;
1609running_with_own_token += 1;
1610 }
1611 }
1612Err(e) => {
1613let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1614shared_emitter.fatal(msg);
1615codegen_state = Aborted;
1616 }
1617 }
1618 }
16191620 Message::CodegenDone { llvm_work_item, cost } => {
1621// We keep the queue sorted by estimated processing cost,
1622 // so that more expensive items are processed earlier. This
1623 // is good for throughput as it gives the main thread more
1624 // time to fill up the queue and it avoids scheduling
1625 // expensive items to the end.
1626 // Note, however, that this is not ideal for memory
1627 // consumption, as LLVM module sizes are not evenly
1628 // distributed.
1629let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1630let insertion_index = match insertion_index {
1631Ok(idx) | Err(idx) => idx,
1632 };
1633work_items.insert(insertion_index, (llvm_work_item, cost));
16341635if let Some(helper) = &jobserver_helper1636 && running_with_any_token(main_thread_state, running_with_own_token)
1637 < cgcx.parallel.unwrap().get()
1638 {
1639helper.request_token();
1640 }
1641{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1642main_thread_state = MainThreadState::Idle;
1643 }
16441645 Message::CodegenComplete => {
1646if codegen_state != Aborted {
1647codegen_state = Completed;
1648 }
1649{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1650main_thread_state = MainThreadState::Idle;
1651 }
16521653// If codegen is aborted that means translation was aborted due
1654 // to some normal-ish compiler error. In this situation we want
1655 // to exit as soon as possible, but we want to make sure all
1656 // existing work has finished. Flag codegen as being done, and
1657 // then conditions above will ensure no more work is spawned but
1658 // we'll keep executing this loop until `running_with_own_token`
1659 // hits 0.
1660Message::CodegenAborted => {
1661codegen_state = Aborted;
1662 }
16631664 Message::WorkItem { result } => {
1665// If a thread exits successfully then we drop a token associated
1666 // with that worker and update our `running_with_own_token` count.
1667 // We may later re-acquire a token to continue running more work.
1668 // We may also not actually drop a token here if the worker was
1669 // running with an "ephemeral token".
1670if main_thread_state == MainThreadState::Lending {
1671main_thread_state = MainThreadState::Idle;
1672 } else {
1673running_with_own_token -= 1;
1674 }
16751676match result {
1677Ok(WorkItemResult::Finished(compiled_module)) => {
1678compiled_modules.push(compiled_module);
1679 }
1680Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1681if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1682needs_fat_lto.push(fat_lto_input);
1683 }
1684Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1685if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1686needs_thin_lto.push(ThinLtoInput::Red {
1687name,
1688 buffer: SerializedModule::Local(thin_buffer),
1689 });
1690 }
1691Err(Some(WorkerFatalError)) => {
1692// Like `CodegenAborted`, wait for remaining work to finish.
1693codegen_state = Aborted;
1694 }
1695Err(None) => {
1696// If the thread failed that means it panicked, so
1697 // we abort immediately.
1698::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1699 }
1700 }
1701 }
17021703 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1704{
match (&codegen_state, &Ongoing) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(codegen_state, Ongoing);
1705{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1706lto_import_only_modules.push((bitcode_path, work_product));
1707main_thread_state = MainThreadState::Idle;
1708 }
1709 }
1710 }
17111712// Drop to print timings
1713drop(llvm_start_time);
17141715if codegen_state == Aborted {
1716return Err(());
1717 }
17181719drop(codegen_state);
1720drop(tokens);
1721drop(jobserver_helper);
1722if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17231724if !needs_fat_lto.is_empty() {
1725if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1726if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17271728if let Some(allocator_module) = allocator_module.take() {
1729needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1730 }
17311732for (bitcode_path, wp) in lto_import_only_modules {
1733 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1734 }
17351736return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1737 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1738if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1739if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17401741for (bitcode_path, wp) in lto_import_only_modules {
1742 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1743 }
17441745let allocator_module = if let Some(allocator_module) = allocator_module {
1746if cgcx.lto == Lto::ThinLocal {
1747Some(B::codegen(
1748&cgcx,
1749&prof,
1750&shared_emitter,
1751allocator_module,
1752&allocator_config,
1753 ))
1754 } else {
1755let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1756needs_thin_lto.push(ThinLtoInput::Red {
1757 name: allocator_module.name,
1758 buffer: SerializedModule::Local(thin_buffer),
1759 });
17601761None1762 }
1763 } else {
1764None1765 };
17661767return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto, allocator_module });
1768 }
17691770Ok(MaybeLtoModules::NoLto(CompiledModules {
1771 modules: compiled_modules,
1772 allocator_module: allocator_module.map(|allocator_module| {
1773 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1774 }),
1775 }))
1776 };
1777return std::thread::Builder::new()
1778 .name("coordinator".to_owned())
1779 .spawn(f)
1780 .expect("failed to spawn coordinator thread");
17811782// A heuristic that determines if we have enough LLVM WorkItems in the
1783 // queue so that the main thread can do LLVM work instead of codegen
1784fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1785// This heuristic scales ahead-of-time codegen according to available
1786 // concurrency, as measured by `workers_running`. The idea is that the
1787 // more concurrency we have available, the more demand there will be for
1788 // work items, and the fuller the queue should be kept to meet demand.
1789 // An important property of this approach is that we codegen ahead of
1790 // time only as much as necessary, so as to keep fewer LLVM modules in
1791 // memory at once, thereby reducing memory consumption.
1792 //
1793 // When the number of workers running is less than the max concurrency
1794 // available to us, this heuristic can cause us to instruct the main
1795 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1796 // of codegen, even though it seems like it *should* be codegenning so
1797 // that we can create more work items and spawn more LLVM workers.
1798 //
1799 // But this is not a problem. When the main thread is told to LLVM,
1800 // according to this heuristic and how work is scheduled, there is
1801 // always at least one item in the queue, and therefore at least one
1802 // pending jobserver token request. If there *is* more concurrency
1803 // available, we will immediately receive a token, which will upgrade
1804 // the main thread's LLVM worker to a real one (conceptually), and free
1805 // up the main thread to codegen if necessary. On the other hand, if
1806 // there isn't more concurrency, then the main thread working on an LLVM
1807 // item is appropriate, as long as the queue is full enough for demand.
1808 //
1809 // Speaking of which, how full should we keep the queue? Probably less
1810 // full than you'd think. A lot has to go wrong for the queue not to be
1811 // full enough and for that to have a negative effect on compile times.
1812 //
1813 // Workers are unlikely to finish at exactly the same time, so when one
1814 // finishes and takes another work item off the queue, we often have
1815 // ample time to codegen at that point before the next worker finishes.
1816 // But suppose that codegen takes so long that the workers exhaust the
1817 // queue, and we have one or more workers that have nothing to work on.
1818 // Well, it might not be so bad. Of all the LLVM modules we create and
1819 // optimize, one has to finish last. It's not necessarily the case that
1820 // by losing some concurrency for a moment, we delay the point at which
1821 // that last LLVM module is finished and the rest of compilation can
1822 // proceed. Also, when we can't take advantage of some concurrency, we
1823 // give tokens back to the job server. That enables some other rustc to
1824 // potentially make use of the available concurrency. That could even
1825 // *decrease* overall compile time if we're lucky. But yes, if no other
1826 // rustc can make use of the concurrency, then we've squandered it.
1827 //
1828 // However, keeping the queue full is also beneficial when we have a
1829 // surge in available concurrency. Then items can be taken from the
1830 // queue immediately, without having to wait for codegen.
1831 //
1832 // So, the heuristic below tries to keep one item in the queue for every
1833 // four running workers. Based on limited benchmarking, this appears to
1834 // be more than sufficient to avoid increasing compilation times.
1835let quarter_of_workers = workers_running - 3 * workers_running / 4;
1836items_in_queue > 0 && items_in_queue >= quarter_of_workers1837 }
1838}
18391840/// `FatalError` is explicitly not `Send`.
1841#[must_use]
1842pub(crate) struct WorkerFatalError;
18431844fn spawn_work<'a, B: WriteBackendMethods>(
1845 cgcx: &CodegenContext,
1846 prof: &'a SelfProfilerRef,
1847 incr_comp_session: Option<&BorrowedIncrCompSession>,
1848 shared_emitter: SharedEmitter,
1849 coordinator_send: Sender<Message<B>>,
1850 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1851 work: WorkItem<B>,
1852 stack_size: usize,
1853) {
1854if llvm_start_time.is_none() {
1855*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1856 }
18571858let old_incr_comp_session_dir = incr_comp_session1859 .and_then(|incr_comp_session| incr_comp_session.old_session_directory.clone());
1860let new_incr_comp_session_dir =
1861incr_comp_session.map(|incr_comp_session| incr_comp_session.new_session_directory.clone());
18621863let cgcx = cgcx.clone();
1864let prof = prof.clone();
18651866let name = work.short_description();
1867let f = move || {
1868let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18691870let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1871 WorkItem::Optimize(m) => execute_optimize_work_item(
1872&cgcx,
1873&prof,
1874new_incr_comp_session_dir.as_deref(),
1875shared_emitter,
1876m,
1877 ),
1878 WorkItem::CopyPostLtoArtifacts(m) => {
1879 WorkItemResult::Finished(execute_copy_from_cache_work_item(
1880&cgcx,
1881&prof,
1882old_incr_comp_session_dir.as_deref().unwrap(),
1883shared_emitter,
1884m,
1885 ))
1886 }
1887 }));
18881889let msg = match result {
1890Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18911892// We ignore any `FatalError` coming out of `execute_work_item`, as a
1893 // diagnostic was already sent off to the main thread - just surface
1894 // that there was an error in this worker.
1895Err(err) if err.is::<FatalErrorMarker>() => {
1896 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1897 }
18981899Err(_) => Message::WorkItem::<B> { result: Err(None) },
1900 };
1901drop(coordinator_send.send(msg));
1902 };
1903 std::thread::Builder::new()
1904 .name(name)
1905 .stack_size(stack_size)
1906 .spawn(f)
1907 .expect("failed to spawn work thread");
1908}
19091910fn spawn_thin_lto_work<B: WriteBackendMethods>(
1911 cgcx: &CodegenContext,
1912 prof: &SelfProfilerRef,
1913 old_incr_comp_session_dir: Option<PathBuf>,
1914 shared_emitter: SharedEmitter,
1915 tm_factory: TargetMachineFactoryFn<B>,
1916 coordinator_send: Sender<ThinLtoMessage>,
1917 work: ThinLtoWorkItem<B>,
1918 stack_size: usize,
1919) {
1920let cgcx = cgcx.clone();
1921let prof = prof.clone();
19221923let name = work.short_description();
1924let f = move || {
1925let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19261927let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1928 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => execute_copy_from_cache_work_item(
1929&cgcx,
1930&prof,
1931old_incr_comp_session_dir.as_deref().unwrap(),
1932shared_emitter,
1933m,
1934 ),
1935 ThinLtoWorkItem::ThinLto(m) => {
1936let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1937 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1938 }
1939 }));
19401941let msg = match result {
1942Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19431944// We ignore any `FatalError` coming out of `execute_work_item`, as a
1945 // diagnostic was already sent off to the main thread - just surface
1946 // that there was an error in this worker.
1947Err(err) if err.is::<FatalErrorMarker>() => {
1948 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1949 }
19501951Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1952 };
1953drop(coordinator_send.send(msg));
1954 };
1955 std::thread::Builder::new()
1956 .name(name)
1957 .stack_size(stack_size)
1958 .spawn(f)
1959 .expect("failed to spawn work thread");
1960}
19611962enum SharedEmitterMessage {
1963 Diagnostic(DiagInner),
1964 InlineAsmError(InlineAsmError),
1965 Fatal(String),
1966}
19671968pub struct InlineAsmError {
1969// We store byte positions rather than a `Span` because this error is created on a codegen
1970 // thread which doesn't have access to the span interner within the session globals. The byte
1971 // positions are converted to a `Span` once they reach a thread with access to the span
1972 // interner.
1973pub lo: BytePos,
1974pub hi: BytePos,
1975pub msg: String,
1976pub level: Level,
1977pub source: Option<(String, Vec<InnerSpan>)>,
1978}
19791980#[derive(#[automatically_derived]impl ::core::clone::Clone for SharedEmitter {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1981pub struct SharedEmitter {
1982 sender: Sender<SharedEmitterMessage>,
1983}
19841985pub struct SharedEmitterMain {
1986 receiver: Receiver<SharedEmitterMessage>,
1987}
19881989impl SharedEmitter {
1990fn new() -> (SharedEmitter, SharedEmitterMain) {
1991let (sender, receiver) = channel();
19921993 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1994 }
19951996pub fn inline_asm_error(&self, err: InlineAsmError) {
1997drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1998 }
19992000fn fatal(&self, msg: &str) {
2001drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2002 }
2003}
20042005impl Emitterfor SharedEmitter {
2006fn emit_diagnostic(&mut self, diag: DiagInner) {
2007drop(self.sender.send(SharedEmitterMessage::Diagnostic(diag)));
2008 }
20092010fn source_map(&self) -> Option<&SourceMap> {
2011None2012 }
2013}
20142015impl SharedEmitterMain {
2016fn check(&self, sess: &Session, blocking: bool) {
2017loop {
2018let message = if blocking {
2019match self.receiver.recv() {
2020Ok(message) => Ok(message),
2021Err(_) => Err(()),
2022 }
2023 } else {
2024match self.receiver.try_recv() {
2025Ok(message) => Ok(message),
2026Err(_) => Err(()),
2027 }
2028 };
20292030match message {
2031Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2032let dcx = sess.dcx();
2033dcx.emit_diagnostic(diag);
2034sess.dcx().abort_if_errors();
2035 }
2036Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2037{
match inner.level {
Level::Error | Level::Warning(None) | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning(None) | Level::Note",
::core::option::Option::None);
}
}
};assert_matches!(inner.level, Level::Error | Level::Warning(None) | Level::Note);
2038let mut err = Diag::new(sess.dcx(), inner.level, inner.msg);
2039let span = Span::new(inner.lo, inner.hi, SyntaxContext::root(), None);
2040if !span.is_dummy() {
2041err.span(span);
2042 }
20432044// Point to the generated assembly if it is available.
2045if let Some((buffer, spans)) = inner.source {
2046let source = sess2047 .source_map()
2048 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2049let spans: Vec<_> = spans2050 .iter()
2051 .map(|sp| {
2052Span::with_root_ctxt(
2053source.normalized_byte_pos(sp.start as u32),
2054source.normalized_byte_pos(sp.end as u32),
2055 )
2056 })
2057 .collect();
2058err.span_note(spans, "instantiated into assembly here");
2059 }
20602061err.emit();
2062 }
2063Ok(SharedEmitterMessage::Fatal(msg)) => {
2064sess.dcx().fatal(msg);
2065 }
2066Err(_) => {
2067break;
2068 }
2069 }
2070 }
2071 }
2072}
20732074pub struct Coordinator<B: WriteBackendMethods> {
2075 sender: Sender<Message<B>>,
2076 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2077// Only used for the Message type.
2078phantom: PhantomData<B>,
2079}
20802081impl<B: WriteBackendMethods> Coordinator<B> {
2082fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2083self.future.take().unwrap().join()
2084 }
2085}
20862087impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2088fn drop(&mut self) {
2089if let Some(future) = self.future.take() {
2090// If we haven't joined yet, signal to the coordinator that it should spawn no more
2091 // work, and wait for worker threads to finish.
2092drop(self.sender.send(Message::CodegenAborted::<B>));
2093drop(future.join());
2094 }
2095 }
2096}
20972098pub struct OngoingCodegen<B: WriteBackendMethods> {
2099 backend: B,
2100 output_filenames: Arc<OutputFilenames>,
2101// Field order below is intended to terminate the coordinator thread before two fields below
2102 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2103 // `Drop` implementation for more info.
2104pub(crate) coordinator: Coordinator<B>,
2105 codegen_worker_receive: Receiver<CguMessage>,
2106 shared_emitter_main: SharedEmitterMain,
2107}
21082109impl<B: WriteBackendMethods> OngoingCodegen<B> {
2110pub fn join(
2111self,
2112 sess: &Session,
2113 incr_comp_session: Option<&mut IncrCompSession>,
2114 crate_info: &CrateInfo,
2115 ) -> CompiledModules {
2116self.shared_emitter_main.check(sess, true);
21172118let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2119Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2120Ok(Err(())) => {
2121sess.dcx().abort_if_errors();
2122{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2123 }
2124Err(_) => {
2125::rustc_span::macros::bug_impl(None,
format_args!("panic during codegen/LLVM phase"), Location::caller());bug!("panic during codegen/LLVM phase");
2126 }
2127 });
21282129sess.dcx().abort_if_errors();
21302131let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21322133// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2134let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2135 MaybeLtoModules::NoLto(compiled_modules) => {
2136drop(shared_emitter);
21372138if let Some(incr_comp_session) = incr_comp_session {
2139copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2140sess,
2141incr_comp_session,
2142&compiled_modules,
2143 );
2144 }
21452146compiled_modules2147 }
2148 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2149let tm_factory = self.backend.target_machine_factory(sess);
21502151// FIXME cache local pre-LTO bitcode
21522153CompiledModules {
2154 modules: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[do_fat_lto(sess, &cgcx, shared_emitter, tm_factory,
&crate_info.exported_symbols_for_lto,
&crate_info.each_linked_rlib_file_for_lto, needs_fat_lto)]))vec![do_fat_lto(
2155 sess,
2156&cgcx,
2157 shared_emitter,
2158 tm_factory,
2159&crate_info.exported_symbols_for_lto,
2160&crate_info.each_linked_rlib_file_for_lto,
2161 needs_fat_lto,
2162 )],
2163 allocator_module: None,
2164 }
2165 }
2166 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto, allocator_module } => {
2167let tm_factory = self.backend.target_machine_factory(sess);
21682169let compiled_modules = CompiledModules {
2170 modules: do_thin_lto::<B>(
2171&cgcx,
2172&sess.prof,
2173incr_comp_session.as_deref().map(IncrCompSession::borrow),
2174shared_emitter,
2175tm_factory,
2176&crate_info.exported_symbols_for_lto,
2177&crate_info.each_linked_rlib_file_for_lto,
2178needs_thin_lto,
2179sess.opts.recommended_stack_size,
2180 ),
2181allocator_module,
2182 };
21832184// FIXME include pre-LTO bitcode in workproduct tracking
2185 // FIXME add separate incr comp session for post-LTO outputs to use during link step
2186if let Some(incr_comp_session) = incr_comp_session {
2187copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2188sess,
2189incr_comp_session,
2190&compiled_modules,
2191 );
2192 }
21932194compiled_modules2195 }
2196 });
21972198shared_emitter_main.check(sess, true);
21992200sess.dcx().abort_if_errors();
22012202let mut compiled_modules =
2203compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
22042205// Regardless of what order these modules completed in, report them to
2206 // the backend in the same order every time to ensure that we're handing
2207 // out deterministic results.
2208compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22092210produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22112212compiled_modules2213 }
22142215pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2216self.wait_for_signal_to_codegen_item();
2217self.check_for_errors(tcx.sess);
2218drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2219 }
22202221pub(crate) fn check_for_errors(&self, sess: &Session) {
2222self.shared_emitter_main.check(sess, false);
2223 }
22242225pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2226match self.codegen_worker_receive.recv() {
2227Ok(CguMessage) => {
2228// Ok to proceed.
2229}
2230Err(_) => {
2231// One of the LLVM threads must have panicked, fall through so
2232 // error handling can be reached.
2233}
2234 }
2235 }
2236}
22372238pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2239 coordinator: &Coordinator<B>,
2240 module: ModuleCodegen<B::Module>,
2241 cost: u64,
2242) {
2243let llvm_work_item = WorkItem::Optimize(module);
2244drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2245}
22462247pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2248 coordinator: &Coordinator<B>,
2249 module: CachedModuleCodegen,
2250) {
2251let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2252drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2253}
22542255pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2256 sess: &Session,
2257 incr_comp_session: &IncrCompSession,
2258 coordinator: &Coordinator<B>,
2259 module: CachedModuleCodegen,
2260) {
2261let filename = pre_lto_bitcode_filename(&module.name);
2262let old_bitcode_path = in_old_incr_comp_dir_sess(incr_comp_session, &filename).unwrap();
2263let bitcode_path = in_incr_comp_dir_sess(incr_comp_session, &filename);
22642265match link_or_copy(&old_bitcode_path, &bitcode_path, false /* allow_overwrite */) {
2266Ok(_) => {}
2267Err(error) => {
2268sess.dcx().emit_err(diagnostics::CopyPathBuf {
2269 source_file: old_bitcode_path,
2270 output_path: bitcode_path,
2271error,
2272 });
2273return;
2274 }
2275 }
22762277// Schedule the module to be loaded
2278drop(
2279coordinator2280 .sender
2281 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2282 );
2283}
22842285fn pre_lto_bitcode_filename(module_name: &str) -> String {
2286::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2287}
22882289fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2290// This should never be true (because it's not supported). If it is true,
2291 // something is wrong with commandline arg validation.
2292if !!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
tcx.sess.target.is_like_windows &&
tcx.sess.opts.cg.prefer_dynamic) {
::core::panicking::panic("assertion failed: !(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n tcx.sess.target.is_like_windows &&\n tcx.sess.opts.cg.prefer_dynamic)")
};assert!(
2293 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2294 && tcx.sess.target.is_like_windows
2295 && tcx.sess.opts.cg.prefer_dynamic)
2296 );
22972298// We need to generate _imp__ symbol if we are generating an rlib or we include one
2299 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2300 // these, but it currently does not do so.
2301let can_have_static_objects =
2302tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23032304tcx.sess.target.is_like_windows &&
2305can_have_static_objects &&
2306// ThinLTO can't handle this workaround in all cases, so we don't
2307 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2308 // dynamic linking when linker plugin LTO is enabled.
2309!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2310}