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, mem, 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, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
15Level, MultiSpan, Style, Sublevel, Suggestions, catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_incremental::{copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir_sess};
19use rustc_macros::{Decodable, Encodable};
20use rustc_metadata::fs::copy_to_stdout;
21use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
22use rustc_middle::ty::TyCtxt;
23use rustc_session::config::{
24self, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
25};
26use rustc_session::{IncrCompSession, Session};
27use rustc_span::source_map::SourceMap;
28use rustc_span::{FileName, InnerSpan, Span, SpanData, bug};
29use rustc_structures::CrateType;
30use rustc_target::spec::{MergeFunctions, SanitizerSet};
31use tracing::debug;
3233use crate::back::link::ensure_removed;
34use crate::back::lto::{self, SerializedModule, check_lto_allowed};
35use crate::diagnostics::ErrorCreatingRemarkDir;
36use crate::traits::*;
37use crate::{
38CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
39diagnostics,
40};
4142const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4344/// What kind of object file to emit.
45#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for EmitObj { }
#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> EmitObj {
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: &EmitObj) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(EmitObj::ObjectCode(__self_0), EmitObj::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)]
46pub enum EmitObj {
47// No object file.
48None,
4950// Just uncompressed llvm bitcode. Provides easy compatibility with
51 // emscripten's ecc compiler, when used as the linker.
52Bitcode,
5354// Object code, possibly augmented with a bitcode section.
55ObjectCode(BitcodeSection),
56}
5758/// What kind of llvm bitcode section to embed in an object file.
59#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BitcodeSection { }
#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> BitcodeSection { *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: &BitcodeSection) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}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)]
60pub enum BitcodeSection {
61// No bitcode section.
62None,
6364// A full, uncompressed bitcode section.
65Full,
66}
6768/// Module-specific configuration for `optimize_and_codegen`.
69#[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)]
70pub struct ModuleConfig {
71/// Names of additional optimization passes to run.
72pub passes: Vec<String>,
73/// Some(level) to optimize at a certain level, or None to run
74 /// absolutely no optimizations (used for the allocator module).
75pub opt_level: Option<config::OptLevel>,
7677pub pgo_gen: SwitchWithOptPath,
78pub pgo_use: Option<PathBuf>,
79pub pgo_sample_use: Option<PathBuf>,
80pub debug_info_for_profiling: bool,
81pub instrument_coverage: bool,
8283pub sanitizer: SanitizerSet,
84pub sanitizer_cfi_diag: Option<bool>,
85pub sanitizer_cfi_recover: Option<bool>,
86pub sanitizer_recover: SanitizerSet,
87pub sanitizer_dataflow_abilist: Vec<String>,
88pub sanitizer_memory_track_origins: usize,
8990// Flags indicating which outputs to produce.
91pub emit_pre_lto_bc: bool,
92pub emit_bc: bool,
93pub emit_ir: bool,
94pub emit_asm: bool,
95pub emit_obj: EmitObj,
96pub emit_thin_lto_summary: bool,
9798// Miscellaneous flags. These are mostly copied from command-line
99 // options.
100pub verify_llvm_ir: bool,
101pub lint_llvm_ir: bool,
102pub no_prepopulate_passes: bool,
103pub no_builtins: bool,
104pub vectorize_loop: bool,
105pub vectorize_slp: bool,
106pub merge_functions: bool,
107pub emit_lifetime_markers: bool,
108pub llvm_plugins: Vec<String>,
109pub autodiff: Vec<config::AutoDiff>,
110pub autodiff_post_passes: Option<String>,
111pub offload: Vec<config::Offload>,
112}
113114impl ModuleConfig {
115pub(crate) fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
116// If it's a regular module, use `$regular`, otherwise use `$other`.
117 // `$regular` and `$other` are evaluated lazily.
118macro_rules! if_regular {
119 ($regular: expr, $other: expr) => {
120if let ModuleKind::Regular = kind { $regular } else { $other }
121 };
122 }
123124let sess = tcx.sess;
125let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
126127let save_temps = sess.opts.cg.save_temps;
128129let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
130 || match kind {
131 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
132 ModuleKind::Allocator => false,
133 };
134135let emit_obj = if !should_emit_obj {
136 EmitObj::None137 } else if sess.target.obj_is_bitcode
138 || (sess.opts.cg.linker_plugin_lto.enabled()
139 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
140 {
141// This case is selected if the target uses objects as bitcode, or
142 // if linker plugin LTO is enabled. In the linker plugin LTO case
143 // the assumption is that the final link-step will read the bitcode
144 // and convert it to object code. This may be done by either the
145 // native linker or rustc itself.
146 //
147 // By default this branch is skipped for `#![no_builtins]` crates so
148 // they emit native object files (machine code), not LLVM bitcode
149 // objects for the linker (see rust-lang/rust#146133).
150 //
151 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
152 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
153 // intrinsics and related metadata that must be lowered by LLVM's
154 // `LowerTypeTests` pass before instruction selection during
155 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
156 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
157 // reaching the target backend, and LLVM may abort during codegen
158 // (for example in SelectionDAG type legalization) (see
159 // rust-lang/rust#142284).
160 //
161 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
162 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
163 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
164EmitObj::Bitcode165 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
166 EmitObj::ObjectCode(BitcodeSection::Full)
167 } else {
168 EmitObj::ObjectCode(BitcodeSection::None)
169 };
170171ModuleConfig {
172 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
173174 opt_level: opt_level_and_size,
175176 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
177 sess.opts.cg.profile_generate.clone(),
178 SwitchWithOptPath::Disabled
179 ),
180 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
181 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),
182 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
183 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
184185 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
186 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),
187 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),
188 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
189 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
190 Vec::new()
191 ),
192 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
193 sess.opts.unstable_opts.sanitizer_recover,
194 SanitizerSet::empty()
195 ),
196 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
197 sess.opts.unstable_opts.sanitizer_memory_track_origins,
1980
199),
200201 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
202 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
203false
204),
205 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
206 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
207 save_temps
208 ),
209 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
210 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
211false
212),
213 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
214 sess.opts.output_types.contains_key(&OutputType::Assembly),
215false
216),
217emit_obj,
218 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
219 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
220false
221),
222223 verify_llvm_ir: sess.verify_llvm_ir(),
224 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
225 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
226 no_builtins: no_builtins || sess.target.no_builtins,
227228// Copy what clang does by turning on loop vectorization at O2 and
229 // slp vectorization at O3.
230vectorize_loop: !sess.opts.cg.no_vectorize_loops
231 && (sess.opts.optimize == config::OptLevel::More232 || sess.opts.optimize == config::OptLevel::Aggressive),
233 vectorize_slp: !sess.opts.cg.no_vectorize_slp
234 && sess.opts.optimize == config::OptLevel::Aggressive,
235236// Some targets (namely, NVPTX) interact badly with the
237 // MergeFunctions pass. This is because MergeFunctions can generate
238 // new function calls which may interfere with the target calling
239 // convention; e.g. for the NVPTX target, PTX kernels should not
240 // call other PTX kernels. MergeFunctions can also be configured to
241 // generate aliases instead, but aliases are not supported by some
242 // backends (again, NVPTX). Therefore, allow targets to opt out of
243 // the MergeFunctions pass, but otherwise keep the pass enabled (at
244 // O2 and O3) since it can be useful for reducing code size.
245merge_functions: match sess246 .opts
247 .unstable_opts
248 .merge_functions
249 .unwrap_or(sess.target.merge_functions)
250 {
251 MergeFunctions::Disabled => false,
252 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
253use config::OptLevel::*;
254match sess.opts.optimize {
255Aggressive | More | SizeMin | Size => true,
256Less | No => false,
257 }
258 }
259 },
260261 emit_lifetime_markers: sess.emit_lifetime_markers(),
262 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![]),
263 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![]),
264 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
265 sess.opts.unstable_opts.autodiff_post_passes.clone(),
266None
267),
268 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![]),
269 }
270 }
271272pub fn bitcode_needed(&self) -> bool {
273self.emit_bc
274 || self.emit_thin_lto_summary
275 || self.emit_obj == EmitObj::Bitcode276 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
277 }
278279pub fn embed_bitcode(&self) -> bool {
280self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
281 }
282}
283284/// Configuration passed to the function returned by the `target_machine_factory`.
285pub struct TargetMachineFactoryConfig {
286/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
287 /// so the path to the dwarf object has to be provided when we create the target machine.
288 /// This can be ignored by backends which do not need it for their Split DWARF support.
289pub split_dwarf_file: Option<PathBuf>,
290291/// The name of the output object file. Used for setting OutputFilenames in target options
292 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
293pub output_obj_file: Option<PathBuf>,
294}
295296impl TargetMachineFactoryConfig {
297pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
298let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
299cgcx.output_filenames.split_dwarf_path(
300cgcx.split_debuginfo,
301cgcx.split_dwarf_kind,
302module_name,
303 )
304 } else {
305None306 };
307308let output_obj_file =
309Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
310TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
311 }
312}
313314pub type TargetMachineFactoryFn<B> = Arc<
315dyn Fn(
316DiagCtxtHandle<'_>,
317TargetMachineFactoryConfig,
318 ) -> <B as WriteBackendMethods>::TargetMachine319 + Send320 + Sync,
321>;
322323/// Additional resources used by optimize_and_codegen (not module specific)
324#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> CodegenContext {
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),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
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),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_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,
opt_level: ref __binding_10,
msvc_imps_needed: ref __binding_11,
is_pe_coff: ref __binding_12,
target_can_use_split_dwarf: ref __binding_13,
target_arch: ref __binding_14,
target_is_like_darwin: ref __binding_15,
target_is_like_aix: ref __binding_16,
target_is_like_gpu: ref __binding_17,
split_debuginfo: ref __binding_18,
split_dwarf_kind: ref __binding_19,
pointer_size: ref __binding_20,
remark: ref __binding_21,
remark_dir: ref __binding_22,
incr_comp_session_dir: ref __binding_23,
parallel: ref __binding_24 } = *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);
}
}
};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),
opt_level: ::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),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
325pub struct CodegenContext {
326// Resources needed when running LTO
327pub lto: Lto,
328pub use_linker_plugin_lto: bool,
329pub dylib_lto: bool,
330pub prefer_dynamic: bool,
331pub save_temps: bool,
332pub fewer_names: bool,
333pub time_trace: bool,
334pub crate_types: Vec<CrateType>,
335pub output_filenames: Arc<OutputFilenames>,
336pub module_config: Arc<ModuleConfig>,
337pub opt_level: OptLevel,
338pub msvc_imps_needed: bool,
339pub is_pe_coff: bool,
340pub target_can_use_split_dwarf: bool,
341pub target_arch: String,
342pub target_is_like_darwin: bool,
343pub target_is_like_aix: bool,
344pub target_is_like_gpu: bool,
345pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
346pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
347pub pointer_size: Size,
348349/// LLVM optimizations for which we want to print remarks.
350pub remark: Passes,
351/// Directory into which should the LLVM optimization remarks be written.
352 /// If `None`, they will be written to stderr.
353pub remark_dir: Option<PathBuf>,
354/// The incremental compilation session directory, or None if we are not
355 /// compiling incrementally
356pub incr_comp_session_dir: Option<PathBuf>,
357/// `Some(limit)` if the codegen should be run in parallel.
358 ///
359 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
360pub parallel: Option<NonZero<usize>>,
361}
362363fn generate_thin_lto_work<B: WriteBackendMethods>(
364 cgcx: &CodegenContext,
365 prof: &SelfProfilerRef,
366 dcx: DiagCtxtHandle<'_>,
367 exported_symbols_for_lto: &[String],
368 each_linked_rlib_for_lto: &[PathBuf],
369 needs_thin_lto: Vec<ThinLtoInput<B>>,
370) -> Vec<(ThinLtoWorkItem<B>, u64)> {
371let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
372373let (lto_modules, copy_jobs) = B::run_thin_lto(
374cgcx,
375prof,
376dcx,
377exported_symbols_for_lto,
378each_linked_rlib_for_lto,
379needs_thin_lto,
380 );
381lto_modules382 .into_iter()
383 .map(|module| {
384let cost = module.cost();
385 (ThinLtoWorkItem::ThinLto(module), cost)
386 })
387 .chain(copy_jobs.into_iter().map(|wp| {
388 (
389 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
390 name: wp.cgu_name.clone(),
391 source: wp,
392 }),
3930, // copying is very cheap
394)
395 }))
396 .collect()
397}
398399enum MaybeLtoModules<B: WriteBackendMethods> {
400 NoLto(CompiledModules),
401 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
402 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
403}
404405fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
406let sess = tcx.sess;
407sess.opts.cg.embed_bitcode
408 && tcx.crate_types().contains(&CrateType::Rlib)
409 && sess.opts.output_types.contains_key(&OutputType::Exe)
410}
411412fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
413if sess.opts.incremental.is_none() {
414return false;
415 }
416417match sess.lto() {
418 Lto::No => false,
419 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
420 }
421}
422423pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
424 backend: B,
425 tcx: TyCtxt<'_>,
426 regular_config: Arc<ModuleConfig>,
427 allocator_config: Arc<ModuleConfig>,
428 allocator_module: Option<ModuleCodegen<B::Module>>,
429) -> OngoingCodegen<B> {
430let (coordinator_send, coordinator_receive) = channel();
431432let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
433let (codegen_worker_send, codegen_worker_receive) = channel();
434435let coordinator_thread = start_executing_work(
436backend.clone(),
437tcx,
438shared_emitter,
439codegen_worker_send,
440coordinator_receive,
441regular_config,
442allocator_config,
443allocator_module,
444coordinator_send.clone(),
445 );
446447OngoingCodegen {
448backend,
449450codegen_worker_receive,
451shared_emitter_main,
452 coordinator: Coordinator {
453 sender: coordinator_send,
454 future: Some(coordinator_thread),
455 phantom: PhantomData,
456 },
457 output_filenames: Arc::clone(tcx.output_filenames(())),
458 }
459}
460461fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
462 sess: &Session,
463 incr_comp_session: Option<&IncrCompSession>,
464 compiled_modules: &CompiledModules,
465) -> WorkProductMap {
466let mut work_products = WorkProductMap::default();
467468if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
469 {
470return work_products;
471 }
472473let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
474475for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
476let mut files = Vec::new();
477if let Some(object_file_path) = &module.object {
478 files.push((OutputType::Object.extension(), object_file_path.as_path()));
479 }
480if let Some(global_asm_object_file_path) = &module.global_asm_object {
481 files.push(("asm.o", global_asm_object_file_path.as_path()));
482 }
483if let Some(dwarf_object_file_path) = &module.dwarf_object {
484 files.push(("dwo", dwarf_object_file_path.as_path()));
485 }
486if let Some(path) = &module.assembly {
487 files.push((OutputType::Assembly.extension(), path.as_path()));
488 }
489if let Some(path) = &module.llvm_ir {
490 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
491 }
492if let Some(path) = &module.bytecode {
493 files.push((OutputType::Bitcode.extension(), path.as_path()));
494 }
495let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
496 sess,
497 incr_comp_session.unwrap(),
498&module.name,
499 files.as_slice(),
500&module.links_from_incr_cache,
501 );
502 work_products.insert(id, product);
503 }
504505work_products506}
507508pub fn produce_final_output_artifacts(
509 sess: &Session,
510 compiled_modules: &CompiledModules,
511 crate_output: &OutputFilenames,
512) {
513let mut user_wants_bitcode = false;
514let mut user_wants_objects = false;
515516// Produce final compile outputs.
517let copy_gracefully = |from: &Path, to: &OutFileName| match to {
518 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
519sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
520 }
521 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
522sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
523 }
524_ => {}
525 };
526527let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
528if let [module] = &compiled_modules.modules[..] {
529// 1) Only one codegen unit. In this case it's no difficulty
530 // to copy `foo.0.x` to `foo.x`.
531let path = crate_output.temp_path_for_cgu(output_type, &module.name);
532let output = crate_output.path(output_type);
533if !output_type.is_text_output() && output.is_tty() {
534sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
535 shorthand: output_type.shorthand(),
536 });
537 } else {
538copy_gracefully(&path, &output);
539 }
540if !sess.opts.cg.save_temps && !keep_numbered {
541// The user just wants `foo.x`, not `foo.#module-name#.x`.
542ensure_removed(sess.dcx(), &path);
543 }
544 } else {
545if crate_output.outputs.contains_explicit_name(&output_type) {
546// 2) Multiple codegen units, with `--emit foo=some_name`. We have
547 // no good solution for this case, so warn the user.
548sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
549 extension: output_type.extension(),
550 });
551 } else if crate_output.single_output_file.is_some() {
552// 3) Multiple codegen units, with `-o some_name`. We have
553 // no good solution for this case, so warn the user.
554sess.dcx()
555 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
556 } else {
557// 4) Multiple codegen units, but no explicit name. We
558 // just leave the `foo.0.x` files in place.
559 // (We don't have to do any work in this case.)
560}
561 }
562 };
563564// Flag to indicate whether the user explicitly requested bitcode.
565 // Otherwise, we produced it only as a temporary output, and will need
566 // to get rid of it.
567for output_type in crate_output.outputs.keys() {
568match *output_type {
569 OutputType::Bitcode => {
570 user_wants_bitcode = true;
571// Copy to .bc, but always keep the .0.bc. There is a later
572 // check to figure out if we should delete .0.bc files, or keep
573 // them for making an rlib.
574copy_if_one_unit(OutputType::Bitcode, true);
575 }
576 OutputType::ThinLinkBitcode => {
577 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
578 }
579 OutputType::LlvmAssembly => {
580 copy_if_one_unit(OutputType::LlvmAssembly, false);
581 }
582 OutputType::Assembly => {
583 copy_if_one_unit(OutputType::Assembly, false);
584 }
585 OutputType::Object => {
586 user_wants_objects = true;
587 copy_if_one_unit(OutputType::Object, true);
588 }
589 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
590 }
591 }
592593// Clean up unwanted temporary files.
594595 // We create the following files by default:
596 // - #crate#.#module-name#.rcgu.bc
597 // - #crate#.#module-name#.rcgu.o
598 // - #crate#.o (linked from crate.##.rcgu.o)
599 // - #crate#.bc (copied from crate.##.rcgu.bc)
600 // We may create additional files if requested by the user (through
601 // `-C save-temps` or `--emit=` flags).
602603if !sess.opts.cg.save_temps {
604// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
605 // explicitly request bitcode (with --emit=bc), and the bitcode is not
606 // needed for building an rlib, then we must remove .#module-name#.bc as
607 // well.
608609 // Specific rules for keeping .#module-name#.rcgu.bc:
610 // - If the user requested bitcode (`user_wants_bitcode`), and
611 // codegen_units > 1, then keep it.
612 // - If the user requested bitcode but codegen_units == 1, then we
613 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
614 // - If we're not building an rlib and the user didn't request
615 // bitcode, then delete .#module-name#.rcgu.bc.
616 // If you change how this works, also update back::link::link_rlib,
617 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
618 // rlib.
619let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
620621let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
622623let keep_numbered_objects =
624needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
625626for module in compiled_modules.modules.iter() {
627if !keep_numbered_objects {
628if let Some(ref path) = module.object {
629 ensure_removed(sess.dcx(), path);
630 }
631632if let Some(ref path) = module.global_asm_object {
633 ensure_removed(sess.dcx(), path);
634 }
635636if let Some(ref path) = module.dwarf_object {
637 ensure_removed(sess.dcx(), path);
638 }
639 }
640641if let Some(ref path) = module.bytecode {
642if !keep_numbered_bitcode {
643 ensure_removed(sess.dcx(), path);
644 }
645 }
646 }
647648if !user_wants_bitcode649 && let Some(ref allocator_module) = compiled_modules.allocator_module
650 && let Some(ref path) = allocator_module.bytecode
651 {
652ensure_removed(sess.dcx(), path);
653 }
654 }
655656if sess.opts.json_artifact_notifications {
657if let [module] = &compiled_modules.modules[..] {
658module.for_each_output(|_path, ty| {
659if sess.opts.output_types.contains_key(&ty) {
660let descr = ty.shorthand();
661// for single cgu file is renamed to drop cgu specific suffix
662 // so we regenerate it the same way
663let path = crate_output.path(ty);
664sess.dcx().emit_artifact_notification(path.as_path(), descr);
665 }
666 });
667 } else {
668for module in &compiled_modules.modules {
669 module.for_each_output(|path, ty| {
670if sess.opts.output_types.contains_key(&ty) {
671let descr = ty.shorthand();
672 sess.dcx().emit_artifact_notification(&path, descr);
673 }
674 });
675 }
676 }
677 }
678679// We leave the following files around by default:
680 // - #crate#.o
681 // - #crate#.bc
682 // These are used in linking steps and will be cleaned up afterward.
683}
684685pub(crate) enum WorkItem<B: WriteBackendMethods> {
686/// Optimize a newly codegened, totally unoptimized module.
687Optimize(ModuleCodegen<B::Module>),
688/// Copy the post-LTO artifacts from the incremental cache to the output
689 /// directory.
690CopyPostLtoArtifacts(CachedModuleCodegen),
691}
692693enum ThinLtoWorkItem<B: WriteBackendMethods> {
694/// Copy the post-LTO artifacts from the incremental cache to the output
695 /// directory.
696CopyPostLtoArtifacts(CachedModuleCodegen),
697/// Performs thin-LTO on the given module.
698ThinLto(lto::ThinModule<B>),
699}
700701// `pthread_setname()` on *nix ignores anything beyond the first 15
702// bytes. Use short descriptions to maximize the space available for
703// the module name.
704#[cfg(not(windows))]
705fn desc(short: &str, _long: &str, name: &str) -> String {
706// The short label is three bytes, and is followed by a space. That
707 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
708 // depends on the CGU name form.
709 //
710 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
711 // before the `-cgu.0` is the same for every CGU, so use the
712 // `cgu.0` part. The number suffix will be different for each
713 // CGU.
714 //
715 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
716 // name because each CGU will have a unique ASCII hash, and the
717 // first 11 bytes will be enough to identify it.
718 //
719 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
720 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
721 // name. The first 11 bytes won't be enough to uniquely identify
722 // it, but no obvious substring will, and this is a rarely used
723 // option so it doesn't matter much.
724 //
725{
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);
726let name = if let Some(index) = name.find("-cgu.") {
727&name[index + 1..] // +1 skips the leading '-'.
728} else {
729name730 };
731::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")732}
733734// Windows has no thread name length limit, so use more descriptive names.
735#[cfg(windows)]
736fn desc(_short: &str, long: &str, name: &str) -> String {
737format!("{long} {name}")
738}
739740impl<B: WriteBackendMethods> WorkItem<B> {
741/// Generate a short description of this work item suitable for use as a thread name.
742fn short_description(&self) -> String {
743match self {
744 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
745 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
746 }
747 }
748}
749750impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
751/// Generate a short description of this work item suitable for use as a thread name.
752fn short_description(&self) -> String {
753match self {
754 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
755desc("cpy", "copy LTO artifacts for", &m.name)
756 }
757 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
758 }
759 }
760}
761762/// A result produced by the backend.
763pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
764/// The backend has finished compiling a CGU, nothing more required.
765Finished(CompiledModule),
766767/// The backend has finished compiling a CGU, which now needs to go through
768 /// fat LTO.
769NeedsFatLto(FatLtoInput<B>),
770771/// The backend has finished compiling a CGU, which now needs to go through
772 /// thin LTO.
773NeedsThinLto(String, B::ModuleBuffer),
774}
775776pub enum FatLtoInput<B: WriteBackendMethods> {
777 Serialized { name: String, bitcode_path: PathBuf },
778 InMemory(ModuleCodegen<B::Module>),
779}
780781pub enum ThinLtoInput<B: WriteBackendMethods> {
782 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
783 Green { wp: WorkProduct, bitcode_path: PathBuf },
784}
785786/// Actual LTO type we end up choosing based on multiple factors.
787pub(crate) enum ComputedLtoType {
788 No,
789 Thin,
790 Fat,
791}
792793pub(crate) fn compute_per_cgu_lto_type(
794 sess_lto: &Lto,
795 linker_does_lto: bool,
796 sess_crate_types: &[CrateType],
797) -> ComputedLtoType {
798// If the linker does LTO, we don't have to do it. Note that we
799 // keep doing full LTO, if it is requested, as not to break the
800 // assumption that the output will be a single module.
801802 // We ignore a request for full crate graph LTO if the crate type
803 // is only an rlib, as there is no full crate graph to process,
804 // that'll happen later.
805 //
806 // This use case currently comes up primarily for targets that
807 // require LTO so the request for LTO is always unconditionally
808 // passed down to the backend, but we don't actually want to do
809 // anything about it yet until we've got a final product.
810let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
811812match sess_lto {
813 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
814 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
815 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
816_ => ComputedLtoType::No,
817 }
818}
819820fn execute_optimize_work_item<B: WriteBackendMethods>(
821 cgcx: &CodegenContext,
822 prof: &SelfProfilerRef,
823 shared_emitter: SharedEmitter,
824mut module: ModuleCodegen<B::Module>,
825) -> WorkItemResult<B> {
826let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
827828 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
829830// After we've done the initial round of optimizations we need to
831 // decide whether to synchronously codegen this module or ship it
832 // back to the coordinator thread for further LTO processing (which
833 // has to wait for all the initial modules to be optimized).
834835let lto_type =
836compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
837838// If we're doing some form of incremental LTO then we need to be sure to
839 // save our module to disk first.
840let bitcode = if cgcx.module_config.emit_pre_lto_bc {
841let filename = pre_lto_bitcode_filename(&module.name);
842cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
843 } else {
844None845 };
846847match lto_type {
848 ComputedLtoType::No => {
849let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
850 WorkItemResult::Finished(module)
851 }
852 ComputedLtoType::Thin => {
853let thin_buffer = B::serialize_module(module.module_llvm, true);
854if let Some(path) = bitcode {
855 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
856{
::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);
857 });
858 }
859 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
860 }
861 ComputedLtoType::Fat => match bitcode {
862Some(path) => {
863let buffer = B::serialize_module(module.module_llvm, false);
864 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
865{
::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);
866 });
867 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
868 name: module.name,
869 bitcode_path: path,
870 })
871 }
872None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
873 },
874 }
875}
876877fn execute_copy_from_cache_work_item(
878 cgcx: &CodegenContext,
879 prof: &SelfProfilerRef,
880 shared_emitter: SharedEmitter,
881 module: CachedModuleCodegen,
882) -> CompiledModule {
883let _timer =
884prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
885886let dcx = DiagCtxt::new(Box::new(shared_emitter));
887let dcx = dcx.handle();
888889let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
890891let mut links_from_incr_cache = Vec::new();
892893let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
894let source_file_in_incr_comp_dir = incr_comp_session_dir.join(saved_path);
895{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/write.rs:895",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(895u32),
::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!(
896"copying preexisting module `{}` from {:?} to {}",
897 module.name,
898 source_file_in_incr_comp_dir,
899 output_path.display()
900 );
901match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
902Ok(_) => {
903links_from_incr_cache.push(source_file_in_incr_comp_dir);
904Some(output_path)
905 }
906Err(error) => {
907dcx.emit_err(diagnostics::CopyPathBuf {
908 source_file: source_file_in_incr_comp_dir,
909output_path,
910error,
911 });
912None913 }
914 }
915 };
916917let dwarf_object =
918module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
919let dwarf_obj_out = cgcx920 .output_filenames
921 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
922 .expect(
923"saved dwarf object in work product but `split_dwarf_path` returned `None`",
924 );
925load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
926 });
927928let mut load_from_incr_cache = |perform, output_type: OutputType| {
929if perform {
930let saved_file = module.source.saved_files.get(output_type.extension())?;
931let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
932load_from_incr_comp_dir(output_path, &saved_file)
933 } else {
934None935 }
936 };
937938let module_config = &cgcx.module_config;
939let should_emit_obj = module_config.emit_obj != EmitObj::None;
940let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
941let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
942let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
943let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
944let global_asm_object =
945if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
946let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
947load_from_incr_comp_dir(output_path, &saved_file)
948 } else {
949None950 };
951if should_emit_obj && object.is_none() {
952dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
953 }
954955CompiledModule {
956links_from_incr_cache,
957 kind: ModuleKind::Regular,
958 name: module.name,
959object,
960global_asm_object,
961dwarf_object,
962bytecode,
963assembly,
964llvm_ir,
965 }
966}
967968fn do_fat_lto<B: WriteBackendMethods>(
969 sess: &Session,
970 cgcx: &CodegenContext,
971 shared_emitter: SharedEmitter,
972 tm_factory: TargetMachineFactoryFn<B>,
973 exported_symbols_for_lto: &[String],
974 each_linked_rlib_for_lto: &[PathBuf],
975 needs_fat_lto: Vec<FatLtoInput<B>>,
976) -> CompiledModule {
977let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
978979let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
980let dcx = dcx.handle();
981982check_lto_allowed(&cgcx, dcx);
983984 B::optimize_and_codegen_fat_lto(
985sess,
986cgcx,
987&shared_emitter,
988tm_factory,
989exported_symbols_for_lto,
990each_linked_rlib_for_lto,
991needs_fat_lto,
992 )
993}
994995fn do_thin_lto<B: WriteBackendMethods>(
996 cgcx: &CodegenContext,
997 prof: &SelfProfilerRef,
998 shared_emitter: SharedEmitter,
999 tm_factory: TargetMachineFactoryFn<B>,
1000 exported_symbols_for_lto: &[String],
1001 each_linked_rlib_for_lto: &[PathBuf],
1002 needs_thin_lto: Vec<ThinLtoInput<B>>,
1003) -> Vec<CompiledModule> {
1004let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10051006let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1007let dcx = dcx.handle();
10081009check_lto_allowed(&cgcx, dcx);
10101011let (coordinator_send, coordinator_receive) = channel();
10121013// First up, convert our jobserver into a helper thread so we can use normal
1014 // mpsc channels to manage our messages and such.
1015 // After we've requested tokens then we'll, when we can,
1016 // get tokens on `coordinator_receive` which will
1017 // get managed in the main loop below.
1018 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1019 // tokens before releasing them, so we can never accidentally release the last token
1020 // permanently held by rustc process.
1021let jobserver_helper = cgcx.parallel.map(|_| {
1022let coordinator_send2 = coordinator_send.clone();
1023 jobserver::client()
1024 .into_helper_thread(move |token| {
1025drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1026 })
1027 .expect("failed to spawn helper thread")
1028 });
10291030let mut work_items = ::alloc::vec::Vec::new()vec![];
10311032// We have LTO work to do. Perform the serial work here of
1033 // figuring out what we're going to LTO and then push a
1034 // bunch of work items onto our queue to do LTO. This all
1035 // happens on the coordinator thread but it's very quick so
1036 // we don't worry about tokens.
1037for (i, (work, cost)) in generate_thin_lto_work::<B>(
1038 cgcx,
1039 prof,
1040 dcx,
1041&exported_symbols_for_lto,
1042&each_linked_rlib_for_lto,
1043 needs_thin_lto,
1044 )
1045 .into_iter()
1046 .enumerate()
1047 {
1048let insertion_index =
1049 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1050 work_items.insert(insertion_index, (work, cost));
1051if let Some(helper) = &jobserver_helper
1052 && i < cgcx.parallel.unwrap().get()
1053 {
1054 helper.request_token();
1055 }
1056 }
10571058let mut codegen_aborted = None;
10591060// These are the Jobserver Tokens we currently hold. Does not include
1061 // the implicit Token the compiler process owns no matter what.
1062let mut tokens = ::alloc::vec::Vec::new()vec![];
10631064// Amount of tokens that are used (including the implicit token).
1065let mut used_token_count = 0;
10661067let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10681069// Run the message loop while there's still anything that needs message
1070 // processing. Note that as soon as codegen is aborted we simply want to
1071 // wait for all existing work to finish, so many of the conditions here
1072 // only apply if codegen hasn't been aborted as they represent pending
1073 // work to be done.
1074loop {
1075if codegen_aborted.is_none() {
1076if used_token_count == 0 && work_items.is_empty() {
1077// All codegen work is done.
1078break;
1079 }
10801081// Spin up what work we can, only doing this while we've got available
1082 // parallelism slots and work left to spawn.
1083while used_token_count < tokens.len() + 1
1084&& let Some((item, _)) = work_items.pop()
1085 {
1086 spawn_thin_lto_work(
1087&cgcx,
1088 prof,
1089 shared_emitter.clone(),
1090 Arc::clone(&tm_factory),
1091 coordinator_send.clone(),
1092 item,
1093 );
1094 used_token_count += 1;
1095 }
1096 } else {
1097// Don't queue up any more work if codegen was aborted, we're
1098 // just waiting for our existing children to finish.
1099if used_token_count == 0 {
1100break;
1101 }
1102 }
11031104// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1105tokens.truncate(used_token_count.saturating_sub(1));
11061107match coordinator_receive.recv().unwrap() {
1108// Save the token locally and the next turn of the loop will use
1109 // this to spawn a new unit of work, or it may get dropped
1110 // immediately if we have no more work to spawn.
1111ThinLtoMessage::Token(token) => match token {
1112Ok(token) => {
1113tokens.push(token);
1114 }
1115Err(e) => {
1116let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1117shared_emitter.fatal(msg);
1118codegen_aborted = Some(FatalError);
1119 }
1120 },
11211122 ThinLtoMessage::WorkItem { result } => {
1123// If a thread exits successfully then we drop a token associated
1124 // with that worker and update our `used_token_count` count.
1125 // We may later re-acquire a token to continue running more work.
1126 // We may also not actually drop a token here if the worker was
1127 // running with an "ephemeral token".
1128used_token_count -= 1;
11291130match result {
1131Ok(compiled_module) => compiled_modules.push(compiled_module),
1132Err(Some(WorkerFatalError)) => {
1133// Like `CodegenAborted`, wait for remaining work to finish.
1134codegen_aborted = Some(FatalError);
1135 }
1136Err(None) => {
1137// If the thread failed that means it panicked, so
1138 // we abort immediately.
1139bug_impl(None, format_args!("worker thread panicked"), Location::caller());bug!("worker thread panicked");
1140 }
1141 }
1142 }
1143 }
1144 }
11451146if let Some(codegen_aborted) = codegen_aborted {
1147codegen_aborted.raise();
1148 }
11491150compiled_modules1151}
11521153/// Messages sent to the coordinator.
1154pub(crate) enum Message<B: WriteBackendMethods> {
1155/// A jobserver token has become available. Sent from the jobserver helper
1156 /// thread.
1157Token(io::Result<Acquired>),
11581159/// The backend has finished processing a work item for a codegen unit.
1160 /// Sent from a backend worker thread.
1161WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11621163/// The frontend has finished generating something (backend IR or a
1164 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1165 /// backend. Sent from the main thread.
1166CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11671168/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1169 /// Sent from the main thread.
1170AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11711172/// The frontend has finished generating everything for all codegen units.
1173 /// Sent from the main thread.
1174CodegenComplete,
11751176/// Some normal-ish compiler error occurred, and codegen should be wound
1177 /// down. Sent from the main thread.
1178CodegenAborted,
1179}
11801181/// Messages sent to the coordinator.
1182pub(crate) enum ThinLtoMessage {
1183/// A jobserver token has become available. Sent from the jobserver helper
1184 /// thread.
1185Token(io::Result<Acquired>),
11861187/// The backend has finished processing a work item for a codegen unit.
1188 /// Sent from a backend worker thread.
1189WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1190}
11911192/// A message sent from the coordinator thread to the main thread telling it to
1193/// process another codegen unit.
1194pub struct CguMessage;
11951196// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1197// can be used to send diagnostics from codegen threads to the main thread.
1198// It's missing the following fields from `rustc_errors::DiagInner`.
1199// - `span`: it doesn't impl `Send`.
1200// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1201// diagnostics.
1202// - `sort_span`: it doesn't impl `Send`.
1203// - `is_lint`: lints aren't relevant during codegen.
1204// - `emitted_at`: not used for codegen diagnostics.
1205struct Diagnostic {
1206 span: Vec<SpanData>,
1207 level: Level,
1208 messages: Vec<(DiagMessage, Style)>,
1209 code: Option<ErrCode>,
1210 children: Vec<Subdiagnostic>,
1211 args: DiagArgMap,
1212}
12131214// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1215// missing the following fields from `rustc_errors::Subdiag`.
1216// - `span`: it doesn't impl `Send`.
1217struct Subdiagnostic {
1218 level: Sublevel,
1219 messages: Vec<(DiagMessage, Style)>,
1220}
12211222#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for MainThreadState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &MainThreadState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MainThreadState { }
#[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
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)]
1223enum MainThreadState {
1224/// Doing nothing.
1225Idle,
12261227/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1228Codegenning,
12291230/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1231Lending,
1232}
12331234fn start_executing_work<B: WriteBackendMethods>(
1235 backend: B,
1236 tcx: TyCtxt<'_>,
1237 shared_emitter: SharedEmitter,
1238 codegen_worker_send: Sender<CguMessage>,
1239 coordinator_receive: Receiver<Message<B>>,
1240 regular_config: Arc<ModuleConfig>,
1241 allocator_config: Arc<ModuleConfig>,
1242mut allocator_module: Option<ModuleCodegen<B::Module>>,
1243 coordinator_send: Sender<Message<B>>,
1244) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1245let sess = tcx.sess;
1246let prof = sess.prof.clone();
12471248// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1249let exported_symbols_for_lto =
1250if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12511252// First up, convert our jobserver into a helper thread so we can use normal
1253 // mpsc channels to manage our messages and such.
1254 // After we've requested tokens then we'll, when we can,
1255 // get tokens on `coordinator_receive` which will
1256 // get managed in the main loop below.
1257 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1258 // tokens before releasing them, so we can never accidentally release the last token
1259 // permanently held by rustc process.
1260let parallel = match sess.opts.jobs.backend {
1261Some(n) if backend.supports_parallel() => Some(n),
1262_ => None,
1263 };
1264let jobserver_helper = parallel.map(|_| {
1265let coordinator_send2 = coordinator_send.clone();
1266 jobserver::client()
1267 .into_helper_thread(move |token| {
1268drop(coordinator_send2.send(Message::Token::<B>(token)));
1269 })
1270 .expect("failed to spawn helper thread")
1271 });
12721273let opt_level = tcx.backend_optimization_level(());
1274let tm_factory = backend.target_machine_factory(tcx.sess, opt_level);
12751276let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1277let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1278match result {
1279Ok(dir) => Some(dir),
1280Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1281 }
1282 } else {
1283None1284 };
12851286let cgcx = CodegenContext {
1287 crate_types: tcx.crate_types().to_vec(),
1288 lto: sess.lto(),
1289 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1290 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1291 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1292 fewer_names: sess.fewer_names(),
1293 save_temps: sess.opts.cg.save_temps,
1294 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1295 remark: sess.opts.cg.remark.clone(),
1296remark_dir,
1297 incr_comp_session_dir: tcx1298 .incr_comp_session
1299 .as_ref()
1300 .map(|incr_comp_session| incr_comp_session.session_directory.clone()),
1301 output_filenames: Arc::clone(tcx.output_filenames(())),
1302 module_config: regular_config,
1303opt_level,
1304 msvc_imps_needed: msvc_imps_needed(tcx),
1305 is_pe_coff: tcx.sess.target.is_like_windows,
1306 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1307 target_arch: tcx.sess.target.arch.to_string(),
1308 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1309 target_is_like_aix: tcx.sess.target.is_like_aix,
1310 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1311 split_debuginfo: tcx.sess.split_debuginfo(),
1312 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1313parallel,
1314 pointer_size: tcx.data_layout.pointer_size(),
1315 };
13161317// This is the "main loop" of parallel work happening for parallel codegen.
1318 // It's here that we manage parallelism, schedule work, and work with
1319 // messages coming from clients.
1320 //
1321 // There are a few environmental pre-conditions that shape how the system
1322 // is set up:
1323 //
1324 // - Error reporting can only happen on the main thread because that's the
1325 // only place where we have access to the compiler `Session`.
1326 // - LLVM work can be done on any thread.
1327 // - Codegen can only happen on the main thread.
1328 // - Each thread doing substantial work must be in possession of a `Token`
1329 // from the `Jobserver`.
1330 // - The compiler process always holds one `Token`. Any additional `Tokens`
1331 // have to be requested from the `Jobserver`.
1332 //
1333 // Error Reporting
1334 // ===============
1335 // The error reporting restriction is handled separately from the rest: We
1336 // set up a `SharedEmitter` that holds an open channel to the main thread.
1337 // When an error occurs on any thread, the shared emitter will send the
1338 // error message to the receiver main thread (`SharedEmitterMain`). The
1339 // main thread will periodically query this error message queue and emit
1340 // any error messages it has received. It might even abort compilation if
1341 // it has received a fatal error. In this case we rely on all other threads
1342 // being torn down automatically with the main thread.
1343 // Since the main thread will often be busy doing codegen work, error
1344 // reporting will be somewhat delayed, since the message queue can only be
1345 // checked in between two work packages.
1346 //
1347 // Work Processing Infrastructure
1348 // ==============================
1349 // The work processing infrastructure knows three major actors:
1350 //
1351 // - the coordinator thread,
1352 // - the main thread, and
1353 // - LLVM worker threads
1354 //
1355 // The coordinator thread is running a message loop. It instructs the main
1356 // thread about what work to do when, and it will spawn off LLVM worker
1357 // threads as open LLVM WorkItems become available.
1358 //
1359 // The job of the main thread is to codegen CGUs into LLVM work packages
1360 // (since the main thread is the only thread that can do this). The main
1361 // thread will block until it receives a message from the coordinator, upon
1362 // which it will codegen one CGU, send it to the coordinator and block
1363 // again. This way the coordinator can control what the main thread is
1364 // doing.
1365 //
1366 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1367 // available, it will spawn off a new LLVM worker thread and let it process
1368 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1369 // it will just shut down, which also frees all resources associated with
1370 // the given LLVM module, and sends a message to the coordinator that the
1371 // WorkItem has been completed.
1372 //
1373 // Work Scheduling
1374 // ===============
1375 // The scheduler's goal is to minimize the time it takes to complete all
1376 // work there is, however, we also want to keep memory consumption low
1377 // if possible. These two goals are at odds with each other: If memory
1378 // consumption were not an issue, we could just let the main thread produce
1379 // LLVM WorkItems at full speed, assuring maximal utilization of
1380 // Tokens/LLVM worker threads. However, since codegen is usually faster
1381 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1382 // WorkItem potentially holds on to a substantial amount of memory.
1383 //
1384 // So the actual goal is to always produce just enough LLVM WorkItems as
1385 // not to starve our LLVM worker threads. That means, once we have enough
1386 // WorkItems in our queue, we can block the main thread, so it does not
1387 // produce more until we need them.
1388 //
1389 // Doing LLVM Work on the Main Thread
1390 // ----------------------------------
1391 // Since the main thread owns the compiler process's implicit `Token`, it is
1392 // wasteful to keep it blocked without doing any work. Therefore, what we do
1393 // in this case is: We spawn off an additional LLVM worker thread that helps
1394 // reduce the queue. The work it is doing corresponds to the implicit
1395 // `Token`. The coordinator will mark the main thread as being busy with
1396 // LLVM work. (The actual work happens on another OS thread but we just care
1397 // about `Tokens`, not actual threads).
1398 //
1399 // When any LLVM worker thread finishes while the main thread is marked as
1400 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1401 // of the just finished thread to the LLVM worker thread that is working on
1402 // behalf of the main thread's implicit Token, thus freeing up the main
1403 // thread again. The coordinator can then again decide what the main thread
1404 // should do. This allows the coordinator to make decisions at more points
1405 // in time.
1406 //
1407 // Striking a Balance between Throughput and Memory Consumption
1408 // ------------------------------------------------------------
1409 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1410 // memory consumption as low as possible, are in conflict with each other,
1411 // we have to find a trade off between them. Right now, the goal is to keep
1412 // all workers busy, which means that no worker should find the queue empty
1413 // when it is ready to start.
1414 // How do we do achieve this? Good question :) We actually never know how
1415 // many `Tokens` are potentially available so it's hard to say how much to
1416 // fill up the queue before switching the main thread to LLVM work. Also we
1417 // currently don't have a means to estimate how long a running LLVM worker
1418 // will still be busy with it's current WorkItem. However, we know the
1419 // maximal count of available Tokens that makes sense (=the number of CPU
1420 // cores), so we can take a conservative guess. The heuristic we use here
1421 // is implemented in the `queue_full_enough()` function.
1422 //
1423 // Some Background on Jobservers
1424 // -----------------------------
1425 // It's worth also touching on the management of parallelism here. We don't
1426 // want to just spawn a thread per work item because while that's optimal
1427 // parallelism it may overload a system with too many threads or violate our
1428 // configuration for the maximum amount of cpu to use for this process. To
1429 // manage this we use the `jobserver` crate.
1430 //
1431 // Job servers are an artifact of GNU make and are used to manage
1432 // parallelism between processes. A jobserver is a glorified IPC semaphore
1433 // basically. Whenever we want to run some work we acquire the semaphore,
1434 // and whenever we're done with that work we release the semaphore. In this
1435 // manner we can ensure that the maximum number of parallel workers is
1436 // capped at any one point in time.
1437 //
1438 // LTO and the coordinator thread
1439 // ------------------------------
1440 //
1441 // The final job the coordinator thread is responsible for is managing LTO
1442 // and how that works. When LTO is requested what we'll do is collect all
1443 // optimized LLVM modules into a local vector on the coordinator. Once all
1444 // modules have been codegened and optimized we hand this to the `lto`
1445 // module for further optimization. The `lto` module will return back a list
1446 // of more modules to work on, which the coordinator will continue to spawn
1447 // work for.
1448 //
1449 // Each LLVM module is automatically sent back to the coordinator for LTO if
1450 // necessary. There's already optimizations in place to avoid sending work
1451 // back to the coordinator if LTO isn't requested.
1452let f = move || {
1453let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14541455// This is where we collect codegen units that have gone all the way
1456 // through codegen and LLVM.
1457let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1458let mut needs_fat_lto = Vec::new();
1459let mut needs_thin_lto = Vec::new();
1460let mut lto_import_only_modules = Vec::new();
14611462/// Possible state transitions:
1463 /// - Ongoing -> Completed
1464 /// - Ongoing -> Aborted
1465 /// - Completed -> Aborted
1466#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
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: &CodegenState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1467enum CodegenState {
1468 Ongoing,
1469 Completed,
1470 Aborted,
1471 }
1472use CodegenState::*;
1473let mut codegen_state = Ongoing;
14741475// This is the queue of LLVM work items that still need processing.
1476let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14771478// This are the Jobserver Tokens we currently hold. Does not include
1479 // the implicit Token the compiler process owns no matter what.
1480let mut tokens = Vec::new();
14811482let mut main_thread_state = MainThreadState::Idle;
14831484// How many LLVM worker threads are running while holding a Token. This
1485 // *excludes* any that the main thread is lending a Token to.
1486let mut running_with_own_token = 0;
14871488// How many LLVM worker threads are running in total. This *includes*
1489 // any that the main thread is lending a Token to.
1490let running_with_any_token = |main_thread_state, running_with_own_token| {
1491running_with_own_token1492 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1493 };
14941495let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14961497if let Some(allocator_module) = &mut allocator_module {
1498 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1499 }
15001501// Run the message loop while there's still anything that needs message
1502 // processing. Note that as soon as codegen is aborted we simply want to
1503 // wait for all existing work to finish, so many of the conditions here
1504 // only apply if codegen hasn't been aborted as they represent pending
1505 // work to be done.
1506loop {
1507// While there are still CGUs to be codegened, the coordinator has
1508 // to decide how to utilize the compiler processes implicit Token:
1509 // For codegenning more CGU or for running them through LLVM.
1510if codegen_state == Ongoing {
1511if main_thread_state == MainThreadState::Idle {
1512// Compute the number of workers that will be running once we've taken as many
1513 // items from the work queue as we can, plus one for the main thread. It's not
1514 // critically important that we use this instead of just
1515 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1516 // from fluctuating just because a worker finished up and we decreased the
1517 // `running_with_own_token` count, even though we're just going to increase it
1518 // right after this when we put a new worker to work.
1519let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1520let additional_running = std::cmp::min(extra_tokens, work_items.len());
1521let anticipated_running = running_with_own_token + additional_running + 1;
15221523if !queue_full_enough(work_items.len(), anticipated_running) {
1524// The queue is not full enough, process more codegen units:
1525if codegen_worker_send.send(CguMessage).is_err() {
1526{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1527 }
1528main_thread_state = MainThreadState::Codegenning;
1529 } else {
1530// The queue is full enough to not let the worker
1531 // threads starve. Use the implicit Token to do some
1532 // LLVM work too.
1533let (item, _) =
1534work_items.pop().expect("queue empty - queue_full_enough() broken?");
1535main_thread_state = MainThreadState::Lending;
1536spawn_work(
1537&cgcx,
1538&prof,
1539shared_emitter.clone(),
1540coordinator_send.clone(),
1541&mut llvm_start_time,
1542item,
1543 );
1544 }
1545 }
1546 } else if codegen_state == Completed {
1547if running_with_any_token(main_thread_state, running_with_own_token) == 0
1548&& work_items.is_empty()
1549 {
1550// All codegen work is done.
1551break;
1552 }
15531554// In this branch, we know that everything has been codegened,
1555 // so it's just a matter of determining whether the implicit
1556 // Token is free to use for LLVM work.
1557match main_thread_state {
1558 MainThreadState::Idle => {
1559if let Some((item, _)) = work_items.pop() {
1560main_thread_state = MainThreadState::Lending;
1561spawn_work(
1562&cgcx,
1563&prof,
1564shared_emitter.clone(),
1565coordinator_send.clone(),
1566&mut llvm_start_time,
1567item,
1568 );
1569 } else {
1570// There is no unstarted work, so let the main thread
1571 // take over for a running worker. Otherwise the
1572 // implicit token would just go to waste.
1573 // We reduce the `running` counter by one. The
1574 // `tokens.truncate()` below will take care of
1575 // giving the Token back.
1576if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1577running_with_own_token -= 1;
1578main_thread_state = MainThreadState::Lending;
1579 }
1580 }
1581 MainThreadState::Codegenning => bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1582"codegen worker should not be codegenning after \
1583 codegen was already completed"
1584),
1585 MainThreadState::Lending => {
1586// Already making good use of that token
1587}
1588 }
1589 } else {
1590// Don't queue up any more work if codegen was aborted, we're
1591 // just waiting for our existing children to finish.
1592if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1593if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1594break;
1595 }
1596 }
15971598// Spin up what work we can, only doing this while we've got available
1599 // parallelism slots and work left to spawn.
1600if codegen_state != Aborted {
1601while running_with_own_token < tokens.len()
1602 && let Some((item, _)) = work_items.pop()
1603 {
1604 spawn_work(
1605&cgcx,
1606&prof,
1607 shared_emitter.clone(),
1608 coordinator_send.clone(),
1609&mut llvm_start_time,
1610 item,
1611 );
1612 running_with_own_token += 1;
1613 }
1614 }
16151616// Relinquish accidentally acquired extra tokens.
1617tokens.truncate(running_with_own_token);
16181619match coordinator_receive.recv().unwrap() {
1620// Save the token locally and the next turn of the loop will use
1621 // this to spawn a new unit of work, or it may get dropped
1622 // immediately if we have no more work to spawn.
1623Message::Token(token) => {
1624match token {
1625Ok(token) => {
1626tokens.push(token);
16271628if main_thread_state == MainThreadState::Lending {
1629// If the main thread token is used for LLVM work
1630 // at the moment, we turn that thread into a regular
1631 // LLVM worker thread, so the main thread is free
1632 // to react to codegen demand.
1633main_thread_state = MainThreadState::Idle;
1634running_with_own_token += 1;
1635 }
1636 }
1637Err(e) => {
1638let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1639shared_emitter.fatal(msg);
1640codegen_state = Aborted;
1641 }
1642 }
1643 }
16441645 Message::CodegenDone { llvm_work_item, cost } => {
1646// We keep the queue sorted by estimated processing cost,
1647 // so that more expensive items are processed earlier. This
1648 // is good for throughput as it gives the main thread more
1649 // time to fill up the queue and it avoids scheduling
1650 // expensive items to the end.
1651 // Note, however, that this is not ideal for memory
1652 // consumption, as LLVM module sizes are not evenly
1653 // distributed.
1654let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1655let insertion_index = match insertion_index {
1656Ok(idx) | Err(idx) => idx,
1657 };
1658work_items.insert(insertion_index, (llvm_work_item, cost));
16591660if let Some(helper) = &jobserver_helper1661 && running_with_any_token(main_thread_state, running_with_own_token)
1662 < cgcx.parallel.unwrap().get()
1663 {
1664helper.request_token();
1665 }
1666{
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);
1667main_thread_state = MainThreadState::Idle;
1668 }
16691670 Message::CodegenComplete => {
1671if codegen_state != Aborted {
1672codegen_state = Completed;
1673 }
1674{
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);
1675main_thread_state = MainThreadState::Idle;
1676 }
16771678// If codegen is aborted that means translation was aborted due
1679 // to some normal-ish compiler error. In this situation we want
1680 // to exit as soon as possible, but we want to make sure all
1681 // existing work has finished. Flag codegen as being done, and
1682 // then conditions above will ensure no more work is spawned but
1683 // we'll keep executing this loop until `running_with_own_token`
1684 // hits 0.
1685Message::CodegenAborted => {
1686codegen_state = Aborted;
1687 }
16881689 Message::WorkItem { result } => {
1690// If a thread exits successfully then we drop a token associated
1691 // with that worker and update our `running_with_own_token` count.
1692 // We may later re-acquire a token to continue running more work.
1693 // We may also not actually drop a token here if the worker was
1694 // running with an "ephemeral token".
1695if main_thread_state == MainThreadState::Lending {
1696main_thread_state = MainThreadState::Idle;
1697 } else {
1698running_with_own_token -= 1;
1699 }
17001701match result {
1702Ok(WorkItemResult::Finished(compiled_module)) => {
1703compiled_modules.push(compiled_module);
1704 }
1705Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1706if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1707needs_fat_lto.push(fat_lto_input);
1708 }
1709Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1710if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1711needs_thin_lto.push(ThinLtoInput::Red {
1712name,
1713 buffer: SerializedModule::Local(thin_buffer),
1714 });
1715 }
1716Err(Some(WorkerFatalError)) => {
1717// Like `CodegenAborted`, wait for remaining work to finish.
1718codegen_state = Aborted;
1719 }
1720Err(None) => {
1721// If the thread failed that means it panicked, so
1722 // we abort immediately.
1723bug_impl(None, format_args!("worker thread panicked"), Location::caller());bug!("worker thread panicked");
1724 }
1725 }
1726 }
17271728 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1729{
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);
1730{
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);
1731lto_import_only_modules.push((bitcode_path, work_product));
1732main_thread_state = MainThreadState::Idle;
1733 }
1734 }
1735 }
17361737// Drop to print timings
1738drop(llvm_start_time);
17391740if codegen_state == Aborted {
1741return Err(());
1742 }
17431744drop(codegen_state);
1745drop(tokens);
1746drop(jobserver_helper);
1747if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17481749if !needs_fat_lto.is_empty() {
1750if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1751if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17521753if let Some(allocator_module) = allocator_module.take() {
1754needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1755 }
17561757for (bitcode_path, wp) in lto_import_only_modules {
1758 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1759 }
17601761return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1762 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1763if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1764if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17651766for (bitcode_path, wp) in lto_import_only_modules {
1767 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1768 }
17691770if cgcx.lto == Lto::ThinLocal {
1771compiled_modules.extend(do_thin_lto::<B>(
1772&cgcx,
1773&prof,
1774shared_emitter.clone(),
1775tm_factory,
1776&exported_symbols_for_lto,
1777&[],
1778needs_thin_lto,
1779 ));
1780 } else {
1781if let Some(allocator_module) = allocator_module.take() {
1782let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1783needs_thin_lto.push(ThinLtoInput::Red {
1784 name: allocator_module.name,
1785 buffer: SerializedModule::Local(thin_buffer),
1786 });
1787 }
17881789return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1790 }
1791 }
17921793Ok(MaybeLtoModules::NoLto(CompiledModules {
1794 modules: compiled_modules,
1795 allocator_module: allocator_module.map(|allocator_module| {
1796 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1797 }),
1798 }))
1799 };
1800return std::thread::Builder::new()
1801 .name("coordinator".to_owned())
1802 .spawn(f)
1803 .expect("failed to spawn coordinator thread");
18041805// A heuristic that determines if we have enough LLVM WorkItems in the
1806 // queue so that the main thread can do LLVM work instead of codegen
1807fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1808// This heuristic scales ahead-of-time codegen according to available
1809 // concurrency, as measured by `workers_running`. The idea is that the
1810 // more concurrency we have available, the more demand there will be for
1811 // work items, and the fuller the queue should be kept to meet demand.
1812 // An important property of this approach is that we codegen ahead of
1813 // time only as much as necessary, so as to keep fewer LLVM modules in
1814 // memory at once, thereby reducing memory consumption.
1815 //
1816 // When the number of workers running is less than the max concurrency
1817 // available to us, this heuristic can cause us to instruct the main
1818 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1819 // of codegen, even though it seems like it *should* be codegenning so
1820 // that we can create more work items and spawn more LLVM workers.
1821 //
1822 // But this is not a problem. When the main thread is told to LLVM,
1823 // according to this heuristic and how work is scheduled, there is
1824 // always at least one item in the queue, and therefore at least one
1825 // pending jobserver token request. If there *is* more concurrency
1826 // available, we will immediately receive a token, which will upgrade
1827 // the main thread's LLVM worker to a real one (conceptually), and free
1828 // up the main thread to codegen if necessary. On the other hand, if
1829 // there isn't more concurrency, then the main thread working on an LLVM
1830 // item is appropriate, as long as the queue is full enough for demand.
1831 //
1832 // Speaking of which, how full should we keep the queue? Probably less
1833 // full than you'd think. A lot has to go wrong for the queue not to be
1834 // full enough and for that to have a negative effect on compile times.
1835 //
1836 // Workers are unlikely to finish at exactly the same time, so when one
1837 // finishes and takes another work item off the queue, we often have
1838 // ample time to codegen at that point before the next worker finishes.
1839 // But suppose that codegen takes so long that the workers exhaust the
1840 // queue, and we have one or more workers that have nothing to work on.
1841 // Well, it might not be so bad. Of all the LLVM modules we create and
1842 // optimize, one has to finish last. It's not necessarily the case that
1843 // by losing some concurrency for a moment, we delay the point at which
1844 // that last LLVM module is finished and the rest of compilation can
1845 // proceed. Also, when we can't take advantage of some concurrency, we
1846 // give tokens back to the job server. That enables some other rustc to
1847 // potentially make use of the available concurrency. That could even
1848 // *decrease* overall compile time if we're lucky. But yes, if no other
1849 // rustc can make use of the concurrency, then we've squandered it.
1850 //
1851 // However, keeping the queue full is also beneficial when we have a
1852 // surge in available concurrency. Then items can be taken from the
1853 // queue immediately, without having to wait for codegen.
1854 //
1855 // So, the heuristic below tries to keep one item in the queue for every
1856 // four running workers. Based on limited benchmarking, this appears to
1857 // be more than sufficient to avoid increasing compilation times.
1858let quarter_of_workers = workers_running - 3 * workers_running / 4;
1859items_in_queue > 0 && items_in_queue >= quarter_of_workers1860 }
1861}
18621863/// `FatalError` is explicitly not `Send`.
1864#[must_use]
1865pub(crate) struct WorkerFatalError;
18661867fn spawn_work<'a, B: WriteBackendMethods>(
1868 cgcx: &CodegenContext,
1869 prof: &'a SelfProfilerRef,
1870 shared_emitter: SharedEmitter,
1871 coordinator_send: Sender<Message<B>>,
1872 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1873 work: WorkItem<B>,
1874) {
1875if llvm_start_time.is_none() {
1876*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1877 }
18781879let cgcx = cgcx.clone();
1880let prof = prof.clone();
18811882let name = work.short_description();
1883let f = move || {
1884let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18851886let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1887 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1888 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1889execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1890 ),
1891 }));
18921893let msg = match result {
1894Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18951896// We ignore any `FatalError` coming out of `execute_work_item`, as a
1897 // diagnostic was already sent off to the main thread - just surface
1898 // that there was an error in this worker.
1899Err(err) if err.is::<FatalErrorMarker>() => {
1900 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1901 }
19021903Err(_) => Message::WorkItem::<B> { result: Err(None) },
1904 };
1905drop(coordinator_send.send(msg));
1906 };
1907 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1908}
19091910fn spawn_thin_lto_work<B: WriteBackendMethods>(
1911 cgcx: &CodegenContext,
1912 prof: &SelfProfilerRef,
1913 shared_emitter: SharedEmitter,
1914 tm_factory: TargetMachineFactoryFn<B>,
1915 coordinator_send: Sender<ThinLtoMessage>,
1916 work: ThinLtoWorkItem<B>,
1917) {
1918let cgcx = cgcx.clone();
1919let prof = prof.clone();
19201921let name = work.short_description();
1922let f = move || {
1923let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19241925let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1926 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1927execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1928 }
1929 ThinLtoWorkItem::ThinLto(m) => {
1930let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1931 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1932 }
1933 }));
19341935let msg = match result {
1936Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19371938// We ignore any `FatalError` coming out of `execute_work_item`, as a
1939 // diagnostic was already sent off to the main thread - just surface
1940 // that there was an error in this worker.
1941Err(err) if err.is::<FatalErrorMarker>() => {
1942 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1943 }
19441945Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1946 };
1947drop(coordinator_send.send(msg));
1948 };
1949 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1950}
19511952enum SharedEmitterMessage {
1953 Diagnostic(Diagnostic),
1954 InlineAsmError(InlineAsmError),
1955 Fatal(String),
1956}
19571958pub struct InlineAsmError {
1959pub span: SpanData,
1960pub msg: String,
1961pub level: Level,
1962pub source: Option<(String, Vec<InnerSpan>)>,
1963}
19641965#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1966pub struct SharedEmitter {
1967 sender: Sender<SharedEmitterMessage>,
1968}
19691970pub struct SharedEmitterMain {
1971 receiver: Receiver<SharedEmitterMessage>,
1972}
19731974impl SharedEmitter {
1975fn new() -> (SharedEmitter, SharedEmitterMain) {
1976let (sender, receiver) = channel();
19771978 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1979 }
19801981pub fn inline_asm_error(&self, err: InlineAsmError) {
1982drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1983 }
19841985fn fatal(&self, msg: &str) {
1986drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1987 }
1988}
19891990impl Emitterfor SharedEmitter {
1991fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
1992// Check that we aren't missing anything interesting when converting to
1993 // the cut-down local `DiagInner`.
1994if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1995{
match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new()))
{
(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!(diag.suggestions, Suggestions::Enabled(vec![]));
1996{
match (&diag.sort_span, &rustc_span::DUMMY_SP) {
(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!(diag.sort_span, rustc_span::DUMMY_SP);
1997{
match (&diag.is_lint, &None) {
(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!(diag.is_lint, None);
1998// No sensible check for `diag.emitted_at`.
19992000let args = mem::take(&mut diag.args);
2001drop(
2002self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2003 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2004 level: diag.level(),
2005 messages: diag.messages,
2006 code: diag.code,
2007 children: diag2008 .children
2009 .into_iter()
2010 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2011 .collect(),
2012args,
2013 })),
2014 );
2015 }
20162017fn source_map(&self) -> Option<&SourceMap> {
2018None2019 }
2020}
20212022impl SharedEmitterMain {
2023fn check(&self, sess: &Session, blocking: bool) {
2024loop {
2025let message = if blocking {
2026match self.receiver.recv() {
2027Ok(message) => Ok(message),
2028Err(_) => Err(()),
2029 }
2030 } else {
2031match self.receiver.try_recv() {
2032Ok(message) => Ok(message),
2033Err(_) => Err(()),
2034 }
2035 };
20362037match message {
2038Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2039// The diagnostic has been received on the main thread.
2040 // Convert it back to a full `Diagnostic` and emit.
2041let dcx = sess.dcx();
2042let mut d =
2043 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2044d.span = MultiSpan::from_spans(
2045diag.span.into_iter().map(|span| span.span()).collect(),
2046 );
2047d.code = diag.code; // may be `None`, that's ok
2048d.children = diag2049 .children
2050 .into_iter()
2051 .map(|sub| rustc_errors::Subdiag {
2052 level: sub.level,
2053 messages: sub.messages,
2054 span: MultiSpan::new(),
2055 })
2056 .collect();
2057d.args = diag.args;
2058dcx.emit_diagnostic(d);
2059sess.dcx().abort_if_errors();
2060 }
2061Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2062{
match inner.level {
Level::Error | Level::Warning | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning | Level::Note",
::core::option::Option::None);
}
}
};assert_matches!(inner.level, Level::Error | Level::Warning | Level::Note);
2063let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2064if !inner.span.is_dummy() {
2065err.span(inner.span.span());
2066 }
20672068// Point to the generated assembly if it is available.
2069if let Some((buffer, spans)) = inner.source {
2070let source = sess2071 .source_map()
2072 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2073let spans: Vec<_> = spans2074 .iter()
2075 .map(|sp| {
2076Span::with_root_ctxt(
2077source.normalized_byte_pos(sp.start as u32),
2078source.normalized_byte_pos(sp.end as u32),
2079 )
2080 })
2081 .collect();
2082err.span_note(spans, "instantiated into assembly here");
2083 }
20842085err.emit();
2086 }
2087Ok(SharedEmitterMessage::Fatal(msg)) => {
2088sess.dcx().fatal(msg);
2089 }
2090Err(_) => {
2091break;
2092 }
2093 }
2094 }
2095 }
2096}
20972098pub struct Coordinator<B: WriteBackendMethods> {
2099 sender: Sender<Message<B>>,
2100 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2101// Only used for the Message type.
2102phantom: PhantomData<B>,
2103}
21042105impl<B: WriteBackendMethods> Coordinator<B> {
2106fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2107self.future.take().unwrap().join()
2108 }
2109}
21102111impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2112fn drop(&mut self) {
2113if let Some(future) = self.future.take() {
2114// If we haven't joined yet, signal to the coordinator that it should spawn no more
2115 // work, and wait for worker threads to finish.
2116drop(self.sender.send(Message::CodegenAborted::<B>));
2117drop(future.join());
2118 }
2119 }
2120}
21212122pub struct OngoingCodegen<B: WriteBackendMethods> {
2123 backend: B,
2124 output_filenames: Arc<OutputFilenames>,
2125// Field order below is intended to terminate the coordinator thread before two fields below
2126 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2127 // `Drop` implementation for more info.
2128pub(crate) coordinator: Coordinator<B>,
2129 codegen_worker_receive: Receiver<CguMessage>,
2130 shared_emitter_main: SharedEmitterMain,
2131}
21322133impl<B: WriteBackendMethods> OngoingCodegen<B> {
2134pub fn join(
2135self,
2136 sess: &Session,
2137 incr_comp_session: Option<&IncrCompSession>,
2138 crate_info: &CrateInfo,
2139 ) -> (CompiledModules, WorkProductMap) {
2140self.shared_emitter_main.check(sess, true);
21412142let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2143Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2144Ok(Err(())) => {
2145sess.dcx().abort_if_errors();
2146{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2147 }
2148Err(_) => {
2149bug_impl(None, format_args!("panic during codegen/LLVM phase"),
Location::caller());bug!("panic during codegen/LLVM phase");
2150 }
2151 });
21522153sess.dcx().abort_if_errors();
21542155let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21562157// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2158let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2159 MaybeLtoModules::NoLto(compiled_modules) => {
2160drop(shared_emitter);
2161compiled_modules2162 }
2163 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2164let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21652166CompiledModules {
2167 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(
2168 sess,
2169&cgcx,
2170 shared_emitter,
2171 tm_factory,
2172&crate_info.exported_symbols_for_lto,
2173&crate_info.each_linked_rlib_file_for_lto,
2174 needs_fat_lto,
2175 )],
2176 allocator_module: None,
2177 }
2178 }
2179 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2180let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21812182CompiledModules {
2183 modules: do_thin_lto::<B>(
2184&cgcx,
2185&sess.prof,
2186shared_emitter,
2187tm_factory,
2188&crate_info.exported_symbols_for_lto,
2189&crate_info.each_linked_rlib_file_for_lto,
2190needs_thin_lto,
2191 ),
2192 allocator_module: None,
2193 }
2194 }
2195 });
21962197shared_emitter_main.check(sess, true);
21982199sess.dcx().abort_if_errors();
22002201let mut compiled_modules =
2202compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
22032204// Regardless of what order these modules completed in, report them to
2205 // the backend in the same order every time to ensure that we're handing
2206 // out deterministic results.
2207compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22082209let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2210sess,
2211incr_comp_session,
2212&compiled_modules,
2213 );
2214produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22152216 (compiled_modules, work_products)
2217 }
22182219pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2220self.wait_for_signal_to_codegen_item();
2221self.check_for_errors(tcx.sess);
2222drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2223 }
22242225pub(crate) fn check_for_errors(&self, sess: &Session) {
2226self.shared_emitter_main.check(sess, false);
2227 }
22282229pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2230match self.codegen_worker_receive.recv() {
2231Ok(CguMessage) => {
2232// Ok to proceed.
2233}
2234Err(_) => {
2235// One of the LLVM threads must have panicked, fall through so
2236 // error handling can be reached.
2237}
2238 }
2239 }
2240}
22412242pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2243 coordinator: &Coordinator<B>,
2244 module: ModuleCodegen<B::Module>,
2245 cost: u64,
2246) {
2247let llvm_work_item = WorkItem::Optimize(module);
2248drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2249}
22502251pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2252 coordinator: &Coordinator<B>,
2253 module: CachedModuleCodegen,
2254) {
2255let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2256drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2257}
22582259pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2260 tcx: TyCtxt<'_>,
2261 coordinator: &Coordinator<B>,
2262 module: CachedModuleCodegen,
2263) {
2264let filename = pre_lto_bitcode_filename(&module.name);
2265let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename);
2266// Schedule the module to be loaded
2267drop(
2268coordinator2269 .sender
2270 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2271 );
2272}
22732274fn pre_lto_bitcode_filename(module_name: &str) -> String {
2275::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2276}
22772278fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2279// This should never be true (because it's not supported). If it is true,
2280 // something is wrong with commandline arg validation.
2281if !!(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!(
2282 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2283 && tcx.sess.target.is_like_windows
2284 && tcx.sess.opts.cg.prefer_dynamic)
2285 );
22862287// We need to generate _imp__ symbol if we are generating an rlib or we include one
2288 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2289 // these, but it currently does not do so.
2290let can_have_static_objects =
2291tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
22922293tcx.sess.target.is_like_windows &&
2294can_have_static_objects &&
2295// ThinLTO can't handle this workaround in all cases, so we don't
2296 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2297 // dynamic linking when linker plugin LTO is enabled.
2298!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2299}