1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{fs, io, mem, str, thread};
78use rustc_abi::Size;
9use rustc_data_structures::assert_matches;
10use rustc_data_structures::fx::FxIndexMap;
11use rustc_data_structures::jobserver::{self, Acquired};
12use rustc_data_structures::memmap::Mmap;
13use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
14use rustc_errors::emitter::Emitter;
15use rustc_errors::{
16Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
17Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
18};
19use rustc_fs_util::link_or_copy;
20use rustc_hir::find_attr;
21use rustc_incremental::{
22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
23};
24use rustc_macros::{Decodable, Encodable};
25use rustc_metadata::fs::copy_to_stdout;
26use rustc_middle::bug;
27use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
28use rustc_middle::ty::TyCtxt;
29use rustc_session::Session;
30use rustc_session::config::{
31self, CrateType, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes,
32SwitchWithOptPath,
33};
34use rustc_span::source_map::SourceMap;
35use rustc_span::{FileName, InnerSpan, Span, SpanData};
36use rustc_target::spec::{MergeFunctions, SanitizerSet};
37use tracing::debug;
3839use super::link::{self, ensure_removed};
40use super::lto::{self, SerializedModule};
41use crate::back::lto::check_lto_allowed;
42use crate::errors::ErrorCreatingRemarkDir;
43use crate::traits::*;
44use crate::{
45CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
46errors,
47};
4849const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
5051/// What kind of object file to emit.
52#[derive(#[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::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)]
53pub enum EmitObj {
54// No object file.
55None,
5657// Just uncompressed llvm bitcode. Provides easy compatibility with
58 // emscripten's ecc compiler, when used as the linker.
59Bitcode,
6061// Object code, possibly augmented with a bitcode section.
62ObjectCode(BitcodeSection),
63}
6465/// What kind of llvm bitcode section to embed in an object file.
66#[derive(#[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::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);
match *self {
BitcodeSection::None => {}
BitcodeSection::Full => {}
}
}
}
};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)]
67pub enum BitcodeSection {
68// No bitcode section.
69None,
7071// A full, uncompressed bitcode section.
72Full,
73}
7475/// Module-specific configuration for `optimize_and_codegen`.
76#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
match *self {
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_recover: ref __binding_8,
sanitizer_dataflow_abilist: ref __binding_9,
sanitizer_memory_track_origins: ref __binding_10,
emit_pre_lto_bc: ref __binding_11,
emit_bc: ref __binding_12,
emit_ir: ref __binding_13,
emit_asm: ref __binding_14,
emit_obj: ref __binding_15,
emit_thin_lto_summary: ref __binding_16,
verify_llvm_ir: ref __binding_17,
lint_llvm_ir: ref __binding_18,
no_prepopulate_passes: ref __binding_19,
no_builtins: ref __binding_20,
vectorize_loop: ref __binding_21,
vectorize_slp: ref __binding_22,
merge_functions: ref __binding_23,
emit_lifetime_markers: ref __binding_24,
llvm_plugins: ref __binding_25,
autodiff: ref __binding_26,
offload: ref __binding_27 } => {
::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);
}
}
}
}
};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_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),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
77pub struct ModuleConfig {
78/// Names of additional optimization passes to run.
79pub passes: Vec<String>,
80/// Some(level) to optimize at a certain level, or None to run
81 /// absolutely no optimizations (used for the allocator module).
82pub opt_level: Option<config::OptLevel>,
8384pub pgo_gen: SwitchWithOptPath,
85pub pgo_use: Option<PathBuf>,
86pub pgo_sample_use: Option<PathBuf>,
87pub debug_info_for_profiling: bool,
88pub instrument_coverage: bool,
8990pub sanitizer: SanitizerSet,
91pub sanitizer_recover: SanitizerSet,
92pub sanitizer_dataflow_abilist: Vec<String>,
93pub sanitizer_memory_track_origins: usize,
9495// Flags indicating which outputs to produce.
96pub emit_pre_lto_bc: bool,
97pub emit_bc: bool,
98pub emit_ir: bool,
99pub emit_asm: bool,
100pub emit_obj: EmitObj,
101pub emit_thin_lto_summary: bool,
102103// Miscellaneous flags. These are mostly copied from command-line
104 // options.
105pub verify_llvm_ir: bool,
106pub lint_llvm_ir: bool,
107pub no_prepopulate_passes: bool,
108pub no_builtins: bool,
109pub vectorize_loop: bool,
110pub vectorize_slp: bool,
111pub merge_functions: bool,
112pub emit_lifetime_markers: bool,
113pub llvm_plugins: Vec<String>,
114pub autodiff: Vec<config::AutoDiff>,
115pub offload: Vec<config::Offload>,
116}
117118impl ModuleConfig {
119fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120// If it's a regular module, use `$regular`, otherwise use `$other`.
121 // `$regular` and `$other` are evaluated lazily.
122macro_rules! if_regular {
123 ($regular: expr, $other: expr) => {
124if let ModuleKind::Regular = kind { $regular } else { $other }
125 };
126 }
127128let sess = tcx.sess;
129let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
130131let save_temps = sess.opts.cg.save_temps;
132133let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 };
138139let emit_obj = if !should_emit_obj {
140 EmitObj::None141 } else if sess.target.obj_is_bitcode
142 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
143 {
144// This case is selected if the target uses objects as bitcode, or
145 // if linker plugin LTO is enabled. In the linker plugin LTO case
146 // the assumption is that the final link-step will read the bitcode
147 // and convert it to object code. This may be done by either the
148 // native linker or rustc itself.
149 //
150 // Note, however, that the linker-plugin-lto requested here is
151 // explicitly ignored for `#![no_builtins]` crates. These crates are
152 // specifically ignored by rustc's LTO passes and wouldn't work if
153 // loaded into the linker. These crates define symbols that LLVM
154 // lowers intrinsics to, and these symbol dependencies aren't known
155 // until after codegen. As a result any crate marked
156 // `#![no_builtins]` is assumed to not participate in LTO and
157 // instead goes on to generate object code.
158EmitObj::Bitcode159 } else if need_bitcode_in_object(tcx) {
160 EmitObj::ObjectCode(BitcodeSection::Full)
161 } else {
162 EmitObj::ObjectCode(BitcodeSection::None)
163 };
164165ModuleConfig {
166 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
167168 opt_level: opt_level_and_size,
169170 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
171 sess.opts.cg.profile_generate.clone(),
172 SwitchWithOptPath::Disabled
173 ),
174 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
175 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
176 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
177 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
178179 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
180 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
181 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182 Vec::new()
183 ),
184 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
185 sess.opts.unstable_opts.sanitizer_recover,
186 SanitizerSet::empty()
187 ),
188 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
189 sess.opts.unstable_opts.sanitizer_memory_track_origins,
1900
191),
192193 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
194 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195false
196),
197 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
198 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
199 save_temps
200 ),
201 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
202 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
203false
204),
205 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
206 sess.opts.output_types.contains_key(&OutputType::Assembly),
207false
208),
209emit_obj,
210 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
211 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
212false
213),
214215 verify_llvm_ir: sess.verify_llvm_ir(),
216 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
217 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
218 no_builtins: no_builtins || sess.target.no_builtins,
219220// Copy what clang does by turning on loop vectorization at O2 and
221 // slp vectorization at O3.
222vectorize_loop: !sess.opts.cg.no_vectorize_loops
223 && (sess.opts.optimize == config::OptLevel::More224 || sess.opts.optimize == config::OptLevel::Aggressive),
225 vectorize_slp: !sess.opts.cg.no_vectorize_slp
226 && sess.opts.optimize == config::OptLevel::Aggressive,
227228// Some targets (namely, NVPTX) interact badly with the
229 // MergeFunctions pass. This is because MergeFunctions can generate
230 // new function calls which may interfere with the target calling
231 // convention; e.g. for the NVPTX target, PTX kernels should not
232 // call other PTX kernels. MergeFunctions can also be configured to
233 // generate aliases instead, but aliases are not supported by some
234 // backends (again, NVPTX). Therefore, allow targets to opt out of
235 // the MergeFunctions pass, but otherwise keep the pass enabled (at
236 // O2 and O3) since it can be useful for reducing code size.
237merge_functions: match sess238 .opts
239 .unstable_opts
240 .merge_functions
241 .unwrap_or(sess.target.merge_functions)
242 {
243 MergeFunctions::Disabled => false,
244 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
245use config::OptLevel::*;
246match sess.opts.optimize {
247Aggressive | More | SizeMin | Size => true,
248Less | No => false,
249 }
250 }
251 },
252253 emit_lifetime_markers: sess.emit_lifetime_markers(),
254 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![]),
255 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![]),
256 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![]),
257 }
258 }
259260pub fn bitcode_needed(&self) -> bool {
261self.emit_bc
262 || self.emit_thin_lto_summary
263 || self.emit_obj == EmitObj::Bitcode264 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
265 }
266267pub fn embed_bitcode(&self) -> bool {
268self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
269 }
270}
271272/// Configuration passed to the function returned by the `target_machine_factory`.
273pub struct TargetMachineFactoryConfig {
274/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
275 /// so the path to the dwarf object has to be provided when we create the target machine.
276 /// This can be ignored by backends which do not need it for their Split DWARF support.
277pub split_dwarf_file: Option<PathBuf>,
278279/// The name of the output object file. Used for setting OutputFilenames in target options
280 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
281pub output_obj_file: Option<PathBuf>,
282}
283284impl TargetMachineFactoryConfig {
285pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
286let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
287cgcx.output_filenames.split_dwarf_path(
288cgcx.split_debuginfo,
289cgcx.split_dwarf_kind,
290module_name,
291cgcx.invocation_temp.as_deref(),
292 )
293 } else {
294None295 };
296297let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
298 OutputType::Object,
299module_name,
300cgcx.invocation_temp.as_deref(),
301 ));
302TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
303 }
304}
305306pub type TargetMachineFactoryFn<B> = Arc<
307dyn Fn(
308DiagCtxtHandle<'_>,
309TargetMachineFactoryConfig,
310 ) -> <B as WriteBackendMethods>::TargetMachine311 + Send312 + Sync,
313>;
314315/// Additional resources used by optimize_and_codegen (not module specific)
316#[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),
invocation_temp: ::core::clone::Clone::clone(&self.invocation_temp),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
backend_features: ::core::clone::Clone::clone(&self.backend_features),
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) {
match *self {
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,
invocation_temp: ref __binding_9,
module_config: ref __binding_10,
opt_level: ref __binding_11,
backend_features: ref __binding_12,
msvc_imps_needed: ref __binding_13,
is_pe_coff: ref __binding_14,
target_can_use_split_dwarf: ref __binding_15,
target_arch: ref __binding_16,
target_is_like_darwin: ref __binding_17,
target_is_like_aix: ref __binding_18,
target_is_like_gpu: ref __binding_19,
split_debuginfo: ref __binding_20,
split_dwarf_kind: ref __binding_21,
pointer_size: ref __binding_22,
remark: ref __binding_23,
remark_dir: ref __binding_24,
incr_comp_session_dir: ref __binding_25,
parallel: ref __binding_26 } => {
::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);
}
}
}
}
};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),
invocation_temp: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
backend_features: ::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)]
317pub struct CodegenContext {
318// Resources needed when running LTO
319pub lto: Lto,
320pub use_linker_plugin_lto: bool,
321pub dylib_lto: bool,
322pub prefer_dynamic: bool,
323pub save_temps: bool,
324pub fewer_names: bool,
325pub time_trace: bool,
326pub crate_types: Vec<CrateType>,
327pub output_filenames: Arc<OutputFilenames>,
328pub invocation_temp: Option<String>,
329pub module_config: Arc<ModuleConfig>,
330pub opt_level: OptLevel,
331pub backend_features: Vec<String>,
332pub msvc_imps_needed: bool,
333pub is_pe_coff: bool,
334pub target_can_use_split_dwarf: bool,
335pub target_arch: String,
336pub target_is_like_darwin: bool,
337pub target_is_like_aix: bool,
338pub target_is_like_gpu: bool,
339pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
340pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
341pub pointer_size: Size,
342343/// LLVM optimizations for which we want to print remarks.
344pub remark: Passes,
345/// Directory into which should the LLVM optimization remarks be written.
346 /// If `None`, they will be written to stderr.
347pub remark_dir: Option<PathBuf>,
348/// The incremental compilation session directory, or None if we are not
349 /// compiling incrementally
350pub incr_comp_session_dir: Option<PathBuf>,
351/// `true` if the codegen should be run in parallel.
352 ///
353 /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
354pub parallel: bool,
355}
356357fn generate_thin_lto_work<B: WriteBackendMethods>(
358 cgcx: &CodegenContext,
359 prof: &SelfProfilerRef,
360 dcx: DiagCtxtHandle<'_>,
361 exported_symbols_for_lto: &[String],
362 each_linked_rlib_for_lto: &[PathBuf],
363 needs_thin_lto: Vec<(String, B::ModuleBuffer)>,
364 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
365) -> Vec<(ThinLtoWorkItem<B>, u64)> {
366let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
367368let (lto_modules, copy_jobs) = B::run_thin_lto(
369cgcx,
370prof,
371dcx,
372exported_symbols_for_lto,
373each_linked_rlib_for_lto,
374needs_thin_lto,
375import_only_modules,
376 );
377lto_modules378 .into_iter()
379 .map(|module| {
380let cost = module.cost();
381 (ThinLtoWorkItem::ThinLto(module), cost)
382 })
383 .chain(copy_jobs.into_iter().map(|wp| {
384 (
385 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
386 name: wp.cgu_name.clone(),
387 source: wp,
388 }),
3890, // copying is very cheap
390)
391 }))
392 .collect()
393}
394395enum MaybeLtoModules<B: WriteBackendMethods> {
396 NoLto(CompiledModules),
397 FatLto {
398 cgcx: CodegenContext,
399 exported_symbols_for_lto: Arc<Vec<String>>,
400 each_linked_rlib_file_for_lto: Vec<PathBuf>,
401 needs_fat_lto: Vec<FatLtoInput<B>>,
402 lto_import_only_modules:
403Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
404 },
405 ThinLto {
406 cgcx: CodegenContext,
407 exported_symbols_for_lto: Arc<Vec<String>>,
408 each_linked_rlib_file_for_lto: Vec<PathBuf>,
409 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ModuleBuffer)>,
410 lto_import_only_modules:
411Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
412 },
413}
414415fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
416let sess = tcx.sess;
417sess.opts.cg.embed_bitcode
418 && tcx.crate_types().contains(&CrateType::Rlib)
419 && sess.opts.output_types.contains_key(&OutputType::Exe)
420}
421422fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
423if sess.opts.incremental.is_none() {
424return false;
425 }
426427match sess.lto() {
428 Lto::No => false,
429 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
430 }
431}
432433pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
434 backend: B,
435 tcx: TyCtxt<'_>,
436 crate_info: &CrateInfo,
437 allocator_module: Option<ModuleCodegen<B::Module>>,
438) -> OngoingCodegen<B> {
439let (coordinator_send, coordinator_receive) = channel();
440441let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
442443let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
444let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
445446let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
447let (codegen_worker_send, codegen_worker_receive) = channel();
448449let coordinator_thread = start_executing_work(
450backend.clone(),
451tcx,
452crate_info,
453shared_emitter,
454codegen_worker_send,
455coordinator_receive,
456Arc::new(regular_config),
457Arc::new(allocator_config),
458allocator_module,
459coordinator_send.clone(),
460 );
461462OngoingCodegen {
463backend,
464465codegen_worker_receive,
466shared_emitter_main,
467 coordinator: Coordinator {
468 sender: coordinator_send,
469 future: Some(coordinator_thread),
470 phantom: PhantomData,
471 },
472 output_filenames: Arc::clone(tcx.output_filenames(())),
473 }
474}
475476fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
477 sess: &Session,
478 compiled_modules: &CompiledModules,
479) -> FxIndexMap<WorkProductId, WorkProduct> {
480let mut work_products = FxIndexMap::default();
481482if sess.opts.incremental.is_none() {
483return work_products;
484 }
485486let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
487488for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
489let mut files = Vec::new();
490if let Some(object_file_path) = &module.object {
491 files.push((OutputType::Object.extension(), object_file_path.as_path()));
492 }
493if let Some(dwarf_object_file_path) = &module.dwarf_object {
494 files.push(("dwo", dwarf_object_file_path.as_path()));
495 }
496if let Some(path) = &module.assembly {
497 files.push((OutputType::Assembly.extension(), path.as_path()));
498 }
499if let Some(path) = &module.llvm_ir {
500 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
501 }
502if let Some(path) = &module.bytecode {
503 files.push((OutputType::Bitcode.extension(), path.as_path()));
504 }
505if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
506 sess,
507&module.name,
508 files.as_slice(),
509&module.links_from_incr_cache,
510 ) {
511 work_products.insert(id, product);
512 }
513 }
514515work_products516}
517518pub fn produce_final_output_artifacts(
519 sess: &Session,
520 compiled_modules: &CompiledModules,
521 crate_output: &OutputFilenames,
522) {
523let mut user_wants_bitcode = false;
524let mut user_wants_objects = false;
525526// Produce final compile outputs.
527let copy_gracefully = |from: &Path, to: &OutFileName| match to {
528 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
529sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
530 }
531 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
532sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
533 }
534_ => {}
535 };
536537let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
538if let [module] = &compiled_modules.modules[..] {
539// 1) Only one codegen unit. In this case it's no difficulty
540 // to copy `foo.0.x` to `foo.x`.
541let path = crate_output.temp_path_for_cgu(
542output_type,
543&module.name,
544sess.invocation_temp.as_deref(),
545 );
546let output = crate_output.path(output_type);
547if !output_type.is_text_output() && output.is_tty() {
548sess.dcx()
549 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
550 } else {
551copy_gracefully(&path, &output);
552 }
553if !sess.opts.cg.save_temps && !keep_numbered {
554// The user just wants `foo.x`, not `foo.#module-name#.x`.
555ensure_removed(sess.dcx(), &path);
556 }
557 } else {
558if crate_output.outputs.contains_explicit_name(&output_type) {
559// 2) Multiple codegen units, with `--emit foo=some_name`. We have
560 // no good solution for this case, so warn the user.
561sess.dcx()
562 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
563 } else if crate_output.single_output_file.is_some() {
564// 3) Multiple codegen units, with `-o some_name`. We have
565 // no good solution for this case, so warn the user.
566sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
567 } else {
568// 4) Multiple codegen units, but no explicit name. We
569 // just leave the `foo.0.x` files in place.
570 // (We don't have to do any work in this case.)
571}
572 }
573 };
574575// Flag to indicate whether the user explicitly requested bitcode.
576 // Otherwise, we produced it only as a temporary output, and will need
577 // to get rid of it.
578for output_type in crate_output.outputs.keys() {
579match *output_type {
580 OutputType::Bitcode => {
581 user_wants_bitcode = true;
582// Copy to .bc, but always keep the .0.bc. There is a later
583 // check to figure out if we should delete .0.bc files, or keep
584 // them for making an rlib.
585copy_if_one_unit(OutputType::Bitcode, true);
586 }
587 OutputType::ThinLinkBitcode => {
588 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
589 }
590 OutputType::LlvmAssembly => {
591 copy_if_one_unit(OutputType::LlvmAssembly, false);
592 }
593 OutputType::Assembly => {
594 copy_if_one_unit(OutputType::Assembly, false);
595 }
596 OutputType::Object => {
597 user_wants_objects = true;
598 copy_if_one_unit(OutputType::Object, true);
599 }
600 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
601 }
602 }
603604// Clean up unwanted temporary files.
605606 // We create the following files by default:
607 // - #crate#.#module-name#.bc
608 // - #crate#.#module-name#.o
609 // - #crate#.crate.metadata.bc
610 // - #crate#.crate.metadata.o
611 // - #crate#.o (linked from crate.##.o)
612 // - #crate#.bc (copied from crate.##.bc)
613 // We may create additional files if requested by the user (through
614 // `-C save-temps` or `--emit=` flags).
615616if !sess.opts.cg.save_temps {
617// Remove the temporary .#module-name#.o objects. If the user didn't
618 // explicitly request bitcode (with --emit=bc), and the bitcode is not
619 // needed for building an rlib, then we must remove .#module-name#.bc as
620 // well.
621622 // Specific rules for keeping .#module-name#.bc:
623 // - If the user requested bitcode (`user_wants_bitcode`), and
624 // codegen_units > 1, then keep it.
625 // - If the user requested bitcode but codegen_units == 1, then we
626 // can toss .#module-name#.bc because we copied it to .bc earlier.
627 // - If we're not building an rlib and the user didn't request
628 // bitcode, then delete .#module-name#.bc.
629 // If you change how this works, also update back::link::link_rlib,
630 // where .#module-name#.bc files are (maybe) deleted after making an
631 // rlib.
632let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
633634let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
635636let keep_numbered_objects =
637needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
638639for module in compiled_modules.modules.iter() {
640if !keep_numbered_objects {
641if let Some(ref path) = module.object {
642 ensure_removed(sess.dcx(), path);
643 }
644645if let Some(ref path) = module.dwarf_object {
646 ensure_removed(sess.dcx(), path);
647 }
648 }
649650if let Some(ref path) = module.bytecode {
651if !keep_numbered_bitcode {
652 ensure_removed(sess.dcx(), path);
653 }
654 }
655 }
656657if !user_wants_bitcode658 && let Some(ref allocator_module) = compiled_modules.allocator_module
659 && let Some(ref path) = allocator_module.bytecode
660 {
661ensure_removed(sess.dcx(), path);
662 }
663 }
664665if sess.opts.json_artifact_notifications {
666if let [module] = &compiled_modules.modules[..] {
667module.for_each_output(|_path, ty| {
668if sess.opts.output_types.contains_key(&ty) {
669let descr = ty.shorthand();
670// for single cgu file is renamed to drop cgu specific suffix
671 // so we regenerate it the same way
672let path = crate_output.path(ty);
673sess.dcx().emit_artifact_notification(path.as_path(), descr);
674 }
675 });
676 } else {
677for module in &compiled_modules.modules {
678 module.for_each_output(|path, ty| {
679if sess.opts.output_types.contains_key(&ty) {
680let descr = ty.shorthand();
681 sess.dcx().emit_artifact_notification(&path, descr);
682 }
683 });
684 }
685 }
686 }
687688// We leave the following files around by default:
689 // - #crate#.o
690 // - #crate#.crate.metadata.o
691 // - #crate#.bc
692 // These are used in linking steps and will be cleaned up afterward.
693}
694695pub(crate) enum WorkItem<B: WriteBackendMethods> {
696/// Optimize a newly codegened, totally unoptimized module.
697Optimize(ModuleCodegen<B::Module>),
698/// Copy the post-LTO artifacts from the incremental cache to the output
699 /// directory.
700CopyPostLtoArtifacts(CachedModuleCodegen),
701}
702703enum ThinLtoWorkItem<B: WriteBackendMethods> {
704/// Copy the post-LTO artifacts from the incremental cache to the output
705 /// directory.
706CopyPostLtoArtifacts(CachedModuleCodegen),
707/// Performs thin-LTO on the given module.
708ThinLto(lto::ThinModule<B>),
709}
710711// `pthread_setname()` on *nix ignores anything beyond the first 15
712// bytes. Use short descriptions to maximize the space available for
713// the module name.
714#[cfg(not(windows))]
715fn desc(short: &str, _long: &str, name: &str) -> String {
716// The short label is three bytes, and is followed by a space. That
717 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
718 // depends on the CGU name form.
719 //
720 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
721 // before the `-cgu.0` is the same for every CGU, so use the
722 // `cgu.0` part. The number suffix will be different for each
723 // CGU.
724 //
725 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
726 // name because each CGU will have a unique ASCII hash, and the
727 // first 11 bytes will be enough to identify it.
728 //
729 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
730 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
731 // name. The first 11 bytes won't be enough to uniquely identify
732 // it, but no obvious substring will, and this is a rarely used
733 // option so it doesn't matter much.
734 //
735match (&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);
736let name = if let Some(index) = name.find("-cgu.") {
737&name[index + 1..] // +1 skips the leading '-'.
738} else {
739name740 };
741::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")742}
743744// Windows has no thread name length limit, so use more descriptive names.
745#[cfg(windows)]
746fn desc(_short: &str, long: &str, name: &str) -> String {
747format!("{long} {name}")
748}
749750impl<B: WriteBackendMethods> WorkItem<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 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
755 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
756 }
757 }
758}
759760impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
761/// Generate a short description of this work item suitable for use as a thread name.
762fn short_description(&self) -> String {
763match self {
764 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
765desc("cpy", "copy LTO artifacts for", &m.name)
766 }
767 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
768 }
769 }
770}
771772/// A result produced by the backend.
773pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
774/// The backend has finished compiling a CGU, nothing more required.
775Finished(CompiledModule),
776777/// The backend has finished compiling a CGU, which now needs to go through
778 /// fat LTO.
779NeedsFatLto(FatLtoInput<B>),
780781/// The backend has finished compiling a CGU, which now needs to go through
782 /// thin LTO.
783NeedsThinLto(String, B::ModuleBuffer),
784}
785786pub enum FatLtoInput<B: WriteBackendMethods> {
787 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
788 InMemory(ModuleCodegen<B::Module>),
789}
790791/// Actual LTO type we end up choosing based on multiple factors.
792pub(crate) enum ComputedLtoType {
793 No,
794 Thin,
795 Fat,
796}
797798pub(crate) fn compute_per_cgu_lto_type(
799 sess_lto: &Lto,
800 linker_does_lto: bool,
801 sess_crate_types: &[CrateType],
802) -> ComputedLtoType {
803// If the linker does LTO, we don't have to do it. Note that we
804 // keep doing full LTO, if it is requested, as not to break the
805 // assumption that the output will be a single module.
806807 // We ignore a request for full crate graph LTO if the crate type
808 // is only an rlib, as there is no full crate graph to process,
809 // that'll happen later.
810 //
811 // This use case currently comes up primarily for targets that
812 // require LTO so the request for LTO is always unconditionally
813 // passed down to the backend, but we don't actually want to do
814 // anything about it yet until we've got a final product.
815let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
816817match sess_lto {
818 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
819 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
820 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
821_ => ComputedLtoType::No,
822 }
823}
824825fn execute_optimize_work_item<B: WriteBackendMethods>(
826 cgcx: &CodegenContext,
827 prof: &SelfProfilerRef,
828 shared_emitter: SharedEmitter,
829mut module: ModuleCodegen<B::Module>,
830) -> WorkItemResult<B> {
831let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
832833 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
834835// After we've done the initial round of optimizations we need to
836 // decide whether to synchronously codegen this module or ship it
837 // back to the coordinator thread for further LTO processing (which
838 // has to wait for all the initial modules to be optimized).
839840let lto_type =
841compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
842843// If we're doing some form of incremental LTO then we need to be sure to
844 // save our module to disk first.
845let bitcode = if cgcx.module_config.emit_pre_lto_bc {
846let filename = pre_lto_bitcode_filename(&module.name);
847cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
848 } else {
849None850 };
851852match lto_type {
853 ComputedLtoType::No => {
854let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
855 WorkItemResult::Finished(module)
856 }
857 ComputedLtoType::Thin => {
858let thin_buffer = B::serialize_module(module.module_llvm, true);
859if let Some(path) = bitcode {
860 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
861{
::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);
862 });
863 }
864 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
865 }
866 ComputedLtoType::Fat => match bitcode {
867Some(path) => {
868let buffer = B::serialize_module(module.module_llvm, false);
869 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
870{
::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);
871 });
872 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
873 name: module.name,
874 buffer: SerializedModule::Local(buffer),
875 })
876 }
877None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
878 },
879 }
880}
881882fn execute_copy_from_cache_work_item(
883 cgcx: &CodegenContext,
884 prof: &SelfProfilerRef,
885 shared_emitter: SharedEmitter,
886 module: CachedModuleCodegen,
887) -> CompiledModule {
888let _timer =
889prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
890891let dcx = DiagCtxt::new(Box::new(shared_emitter));
892let dcx = dcx.handle();
893894let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
895896let mut links_from_incr_cache = Vec::new();
897898let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
899let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
900{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:900",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(900u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file, output_path.display()) as
&dyn Value))])
});
} else { ; }
};debug!(
901"copying preexisting module `{}` from {:?} to {}",
902 module.name,
903 source_file,
904 output_path.display()
905 );
906match link_or_copy(&source_file, &output_path) {
907Ok(_) => {
908links_from_incr_cache.push(source_file);
909Some(output_path)
910 }
911Err(error) => {
912dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
913None914 }
915 }
916 };
917918let dwarf_object =
919module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
920let dwarf_obj_out = cgcx921 .output_filenames
922 .split_dwarf_path(
923cgcx.split_debuginfo,
924cgcx.split_dwarf_kind,
925&module.name,
926cgcx.invocation_temp.as_deref(),
927 )
928 .expect(
929"saved dwarf object in work product but `split_dwarf_path` returned `None`",
930 );
931load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
932 });
933934let mut load_from_incr_cache = |perform, output_type: OutputType| {
935if perform {
936let saved_file = module.source.saved_files.get(output_type.extension())?;
937let output_path = cgcx.output_filenames.temp_path_for_cgu(
938output_type,
939&module.name,
940cgcx.invocation_temp.as_deref(),
941 );
942load_from_incr_comp_dir(output_path, &saved_file)
943 } else {
944None945 }
946 };
947948let module_config = &cgcx.module_config;
949let should_emit_obj = module_config.emit_obj != EmitObj::None;
950let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
951let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
952let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
953let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
954if should_emit_obj && object.is_none() {
955dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
956 }
957958CompiledModule {
959links_from_incr_cache,
960 kind: ModuleKind::Regular,
961 name: module.name,
962object,
963dwarf_object,
964bytecode,
965assembly,
966llvm_ir,
967 }
968}
969970fn do_fat_lto<B: WriteBackendMethods>(
971 cgcx: &CodegenContext,
972 prof: &SelfProfilerRef,
973 shared_emitter: SharedEmitter,
974 tm_factory: TargetMachineFactoryFn<B>,
975 exported_symbols_for_lto: &[String],
976 each_linked_rlib_for_lto: &[PathBuf],
977mut needs_fat_lto: Vec<FatLtoInput<B>>,
978 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
979) -> CompiledModule {
980let _timer = prof.verbose_generic_activity("LLVM_fatlto");
981982let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
983let dcx = dcx.handle();
984985check_lto_allowed(&cgcx, dcx);
986987for (module, wp) in import_only_modules {
988 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
989 }
990991 B::optimize_and_codegen_fat_lto(
992cgcx,
993prof,
994&shared_emitter,
995tm_factory,
996exported_symbols_for_lto,
997each_linked_rlib_for_lto,
998needs_fat_lto,
999 )
1000}
10011002fn do_thin_lto<B: WriteBackendMethods>(
1003 cgcx: &CodegenContext,
1004 prof: &SelfProfilerRef,
1005 shared_emitter: SharedEmitter,
1006 tm_factory: TargetMachineFactoryFn<B>,
1007 exported_symbols_for_lto: Arc<Vec<String>>,
1008 each_linked_rlib_for_lto: Vec<PathBuf>,
1009 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ModuleBuffer)>,
1010 lto_import_only_modules: Vec<(
1011SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1012WorkProduct,
1013 )>,
1014) -> Vec<CompiledModule> {
1015let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10161017let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1018let dcx = dcx.handle();
10191020check_lto_allowed(&cgcx, dcx);
10211022let (coordinator_send, coordinator_receive) = channel();
10231024// First up, convert our jobserver into a helper thread so we can use normal
1025 // mpsc channels to manage our messages and such.
1026 // After we've requested tokens then we'll, when we can,
1027 // get tokens on `coordinator_receive` which will
1028 // get managed in the main loop below.
1029let coordinator_send2 = coordinator_send.clone();
1030let helper = jobserver::client()
1031 .into_helper_thread(move |token| {
1032drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1033 })
1034 .expect("failed to spawn helper thread");
10351036let mut work_items = ::alloc::vec::Vec::new()vec![];
10371038// We have LTO work to do. Perform the serial work here of
1039 // figuring out what we're going to LTO and then push a
1040 // bunch of work items onto our queue to do LTO. This all
1041 // happens on the coordinator thread but it's very quick so
1042 // we don't worry about tokens.
1043for (work, cost) in generate_thin_lto_work::<B>(
1044 cgcx,
1045 prof,
1046 dcx,
1047&exported_symbols_for_lto,
1048&each_linked_rlib_for_lto,
1049 needs_thin_lto,
1050 lto_import_only_modules,
1051 ) {
1052let insertion_index =
1053 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1054 work_items.insert(insertion_index, (work, cost));
1055if cgcx.parallel {
1056 helper.request_token();
1057 }
1058 }
10591060let mut codegen_aborted = None;
10611062// These are the Jobserver Tokens we currently hold. Does not include
1063 // the implicit Token the compiler process owns no matter what.
1064let mut tokens = ::alloc::vec::Vec::new()vec![];
10651066// Amount of tokens that are used (including the implicit token).
1067let mut used_token_count = 0;
10681069let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10701071// Run the message loop while there's still anything that needs message
1072 // processing. Note that as soon as codegen is aborted we simply want to
1073 // wait for all existing work to finish, so many of the conditions here
1074 // only apply if codegen hasn't been aborted as they represent pending
1075 // work to be done.
1076loop {
1077if codegen_aborted.is_none() {
1078if used_token_count == 0 && work_items.is_empty() {
1079// All codegen work is done.
1080break;
1081 }
10821083// Spin up what work we can, only doing this while we've got available
1084 // parallelism slots and work left to spawn.
1085while used_token_count < tokens.len() + 1
1086&& let Some((item, _)) = work_items.pop()
1087 {
1088 spawn_thin_lto_work(
1089&cgcx,
1090 prof,
1091 shared_emitter.clone(),
1092 Arc::clone(&tm_factory),
1093 coordinator_send.clone(),
1094 item,
1095 );
1096 used_token_count += 1;
1097 }
1098 } else {
1099// Don't queue up any more work if codegen was aborted, we're
1100 // just waiting for our existing children to finish.
1101if used_token_count == 0 {
1102break;
1103 }
1104 }
11051106// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1107tokens.truncate(used_token_count.saturating_sub(1));
11081109match coordinator_receive.recv().unwrap() {
1110// Save the token locally and the next turn of the loop will use
1111 // this to spawn a new unit of work, or it may get dropped
1112 // immediately if we have no more work to spawn.
1113ThinLtoMessage::Token(token) => match token {
1114Ok(token) => {
1115tokens.push(token);
1116 }
1117Err(e) => {
1118let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1119shared_emitter.fatal(msg);
1120codegen_aborted = Some(FatalError);
1121 }
1122 },
11231124 ThinLtoMessage::WorkItem { result } => {
1125// If a thread exits successfully then we drop a token associated
1126 // with that worker and update our `used_token_count` count.
1127 // We may later re-acquire a token to continue running more work.
1128 // We may also not actually drop a token here if the worker was
1129 // running with an "ephemeral token".
1130used_token_count -= 1;
11311132match result {
1133Ok(compiled_module) => compiled_modules.push(compiled_module),
1134Err(Some(WorkerFatalError)) => {
1135// Like `CodegenAborted`, wait for remaining work to finish.
1136codegen_aborted = Some(FatalError);
1137 }
1138Err(None) => {
1139// If the thread failed that means it panicked, so
1140 // we abort immediately.
1141::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1142 }
1143 }
1144 }
1145 }
1146 }
11471148if let Some(codegen_aborted) = codegen_aborted {
1149codegen_aborted.raise();
1150 }
11511152compiled_modules1153}
11541155fn execute_thin_lto_work_item<B: WriteBackendMethods>(
1156 cgcx: &CodegenContext,
1157 prof: &SelfProfilerRef,
1158 shared_emitter: SharedEmitter,
1159 tm_factory: TargetMachineFactoryFn<B>,
1160 module: lto::ThinModule<B>,
1161) -> CompiledModule {
1162let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
11631164 B::optimize_and_codegen_thin(cgcx, prof, &shared_emitter, tm_factory, module)
1165}
11661167/// Messages sent to the coordinator.
1168pub(crate) enum Message<B: WriteBackendMethods> {
1169/// A jobserver token has become available. Sent from the jobserver helper
1170 /// thread.
1171Token(io::Result<Acquired>),
11721173/// The backend has finished processing a work item for a codegen unit.
1174 /// Sent from a backend worker thread.
1175WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11761177/// The frontend has finished generating something (backend IR or a
1178 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1179 /// backend. Sent from the main thread.
1180CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11811182/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1183 /// Sent from the main thread.
1184AddImportOnlyModule {
1185 module_data: SerializedModule<B::ModuleBuffer>,
1186 work_product: WorkProduct,
1187 },
11881189/// The frontend has finished generating everything for all codegen units.
1190 /// Sent from the main thread.
1191CodegenComplete,
11921193/// Some normal-ish compiler error occurred, and codegen should be wound
1194 /// down. Sent from the main thread.
1195CodegenAborted,
1196}
11971198/// Messages sent to the coordinator.
1199pub(crate) enum ThinLtoMessage {
1200/// A jobserver token has become available. Sent from the jobserver helper
1201 /// thread.
1202Token(io::Result<Acquired>),
12031204/// The backend has finished processing a work item for a codegen unit.
1205 /// Sent from a backend worker thread.
1206WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1207}
12081209/// A message sent from the coordinator thread to the main thread telling it to
1210/// process another codegen unit.
1211pub struct CguMessage;
12121213// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1214// can be used to send diagnostics from codegen threads to the main thread.
1215// It's missing the following fields from `rustc_errors::DiagInner`.
1216// - `span`: it doesn't impl `Send`.
1217// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1218// diagnostics.
1219// - `sort_span`: it doesn't impl `Send`.
1220// - `is_lint`: lints aren't relevant during codegen.
1221// - `emitted_at`: not used for codegen diagnostics.
1222struct Diagnostic {
1223 span: Vec<SpanData>,
1224 level: Level,
1225 messages: Vec<(DiagMessage, Style)>,
1226 code: Option<ErrCode>,
1227 children: Vec<Subdiagnostic>,
1228 args: DiagArgMap,
1229}
12301231// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1232// missing the following fields from `rustc_errors::Subdiag`.
1233// - `span`: it doesn't impl `Send`.
1234struct Subdiagnostic {
1235 level: Level,
1236 messages: Vec<(DiagMessage, Style)>,
1237}
12381239#[derive(#[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]
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)]
1240enum MainThreadState {
1241/// Doing nothing.
1242Idle,
12431244/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1245Codegenning,
12461247/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1248Lending,
1249}
12501251fn start_executing_work<B: ExtraBackendMethods>(
1252 backend: B,
1253 tcx: TyCtxt<'_>,
1254 crate_info: &CrateInfo,
1255 shared_emitter: SharedEmitter,
1256 codegen_worker_send: Sender<CguMessage>,
1257 coordinator_receive: Receiver<Message<B>>,
1258 regular_config: Arc<ModuleConfig>,
1259 allocator_config: Arc<ModuleConfig>,
1260mut allocator_module: Option<ModuleCodegen<B::Module>>,
1261 coordinator_send: Sender<Message<B>>,
1262) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1263let sess = tcx.sess;
1264let prof = sess.prof.clone();
12651266let mut each_linked_rlib_for_lto = Vec::new();
1267let mut each_linked_rlib_file_for_lto = Vec::new();
1268drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1269if link::ignored_for_lto(sess, crate_info, cnum) {
1270return;
1271 }
1272each_linked_rlib_for_lto.push(cnum);
1273each_linked_rlib_file_for_lto.push(path.to_path_buf());
1274 }));
12751276// Compute the set of symbols we need to retain when doing LTO (if we need to)
1277let exported_symbols_for_lto =
1278Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
12791280// First up, convert our jobserver into a helper thread so we can use normal
1281 // mpsc channels to manage our messages and such.
1282 // After we've requested tokens then we'll, when we can,
1283 // get tokens on `coordinator_receive` which will
1284 // get managed in the main loop below.
1285let coordinator_send2 = coordinator_send.clone();
1286let helper = jobserver::client()
1287 .into_helper_thread(move |token| {
1288drop(coordinator_send2.send(Message::Token::<B>(token)));
1289 })
1290 .expect("failed to spawn helper thread");
12911292let opt_level = tcx.backend_optimization_level(());
1293let backend_features = tcx.global_backend_features(()).clone();
1294let tm_factory = backend.target_machine_factory(tcx.sess, opt_level, &backend_features);
12951296let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1297let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1298match result {
1299Ok(dir) => Some(dir),
1300Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1301 }
1302 } else {
1303None1304 };
13051306let cgcx = CodegenContext {
1307 crate_types: tcx.crate_types().to_vec(),
1308 lto: sess.lto(),
1309 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1310 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1311 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1312 fewer_names: sess.fewer_names(),
1313 save_temps: sess.opts.cg.save_temps,
1314 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1315 remark: sess.opts.cg.remark.clone(),
1316remark_dir,
1317 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1318 output_filenames: Arc::clone(tcx.output_filenames(())),
1319 module_config: regular_config,
1320opt_level,
1321backend_features,
1322 msvc_imps_needed: msvc_imps_needed(tcx),
1323 is_pe_coff: tcx.sess.target.is_like_windows,
1324 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1325 target_arch: tcx.sess.target.arch.to_string(),
1326 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1327 target_is_like_aix: tcx.sess.target.is_like_aix,
1328 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1329 split_debuginfo: tcx.sess.split_debuginfo(),
1330 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1331 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1332 pointer_size: tcx.data_layout.pointer_size(),
1333 invocation_temp: sess.invocation_temp.clone(),
1334 };
13351336// This is the "main loop" of parallel work happening for parallel codegen.
1337 // It's here that we manage parallelism, schedule work, and work with
1338 // messages coming from clients.
1339 //
1340 // There are a few environmental pre-conditions that shape how the system
1341 // is set up:
1342 //
1343 // - Error reporting can only happen on the main thread because that's the
1344 // only place where we have access to the compiler `Session`.
1345 // - LLVM work can be done on any thread.
1346 // - Codegen can only happen on the main thread.
1347 // - Each thread doing substantial work must be in possession of a `Token`
1348 // from the `Jobserver`.
1349 // - The compiler process always holds one `Token`. Any additional `Tokens`
1350 // have to be requested from the `Jobserver`.
1351 //
1352 // Error Reporting
1353 // ===============
1354 // The error reporting restriction is handled separately from the rest: We
1355 // set up a `SharedEmitter` that holds an open channel to the main thread.
1356 // When an error occurs on any thread, the shared emitter will send the
1357 // error message to the receiver main thread (`SharedEmitterMain`). The
1358 // main thread will periodically query this error message queue and emit
1359 // any error messages it has received. It might even abort compilation if
1360 // it has received a fatal error. In this case we rely on all other threads
1361 // being torn down automatically with the main thread.
1362 // Since the main thread will often be busy doing codegen work, error
1363 // reporting will be somewhat delayed, since the message queue can only be
1364 // checked in between two work packages.
1365 //
1366 // Work Processing Infrastructure
1367 // ==============================
1368 // The work processing infrastructure knows three major actors:
1369 //
1370 // - the coordinator thread,
1371 // - the main thread, and
1372 // - LLVM worker threads
1373 //
1374 // The coordinator thread is running a message loop. It instructs the main
1375 // thread about what work to do when, and it will spawn off LLVM worker
1376 // threads as open LLVM WorkItems become available.
1377 //
1378 // The job of the main thread is to codegen CGUs into LLVM work packages
1379 // (since the main thread is the only thread that can do this). The main
1380 // thread will block until it receives a message from the coordinator, upon
1381 // which it will codegen one CGU, send it to the coordinator and block
1382 // again. This way the coordinator can control what the main thread is
1383 // doing.
1384 //
1385 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1386 // available, it will spawn off a new LLVM worker thread and let it process
1387 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1388 // it will just shut down, which also frees all resources associated with
1389 // the given LLVM module, and sends a message to the coordinator that the
1390 // WorkItem has been completed.
1391 //
1392 // Work Scheduling
1393 // ===============
1394 // The scheduler's goal is to minimize the time it takes to complete all
1395 // work there is, however, we also want to keep memory consumption low
1396 // if possible. These two goals are at odds with each other: If memory
1397 // consumption were not an issue, we could just let the main thread produce
1398 // LLVM WorkItems at full speed, assuring maximal utilization of
1399 // Tokens/LLVM worker threads. However, since codegen is usually faster
1400 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1401 // WorkItem potentially holds on to a substantial amount of memory.
1402 //
1403 // So the actual goal is to always produce just enough LLVM WorkItems as
1404 // not to starve our LLVM worker threads. That means, once we have enough
1405 // WorkItems in our queue, we can block the main thread, so it does not
1406 // produce more until we need them.
1407 //
1408 // Doing LLVM Work on the Main Thread
1409 // ----------------------------------
1410 // Since the main thread owns the compiler process's implicit `Token`, it is
1411 // wasteful to keep it blocked without doing any work. Therefore, what we do
1412 // in this case is: We spawn off an additional LLVM worker thread that helps
1413 // reduce the queue. The work it is doing corresponds to the implicit
1414 // `Token`. The coordinator will mark the main thread as being busy with
1415 // LLVM work. (The actual work happens on another OS thread but we just care
1416 // about `Tokens`, not actual threads).
1417 //
1418 // When any LLVM worker thread finishes while the main thread is marked as
1419 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1420 // of the just finished thread to the LLVM worker thread that is working on
1421 // behalf of the main thread's implicit Token, thus freeing up the main
1422 // thread again. The coordinator can then again decide what the main thread
1423 // should do. This allows the coordinator to make decisions at more points
1424 // in time.
1425 //
1426 // Striking a Balance between Throughput and Memory Consumption
1427 // ------------------------------------------------------------
1428 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1429 // memory consumption as low as possible, are in conflict with each other,
1430 // we have to find a trade off between them. Right now, the goal is to keep
1431 // all workers busy, which means that no worker should find the queue empty
1432 // when it is ready to start.
1433 // How do we do achieve this? Good question :) We actually never know how
1434 // many `Tokens` are potentially available so it's hard to say how much to
1435 // fill up the queue before switching the main thread to LLVM work. Also we
1436 // currently don't have a means to estimate how long a running LLVM worker
1437 // will still be busy with it's current WorkItem. However, we know the
1438 // maximal count of available Tokens that makes sense (=the number of CPU
1439 // cores), so we can take a conservative guess. The heuristic we use here
1440 // is implemented in the `queue_full_enough()` function.
1441 //
1442 // Some Background on Jobservers
1443 // -----------------------------
1444 // It's worth also touching on the management of parallelism here. We don't
1445 // want to just spawn a thread per work item because while that's optimal
1446 // parallelism it may overload a system with too many threads or violate our
1447 // configuration for the maximum amount of cpu to use for this process. To
1448 // manage this we use the `jobserver` crate.
1449 //
1450 // Job servers are an artifact of GNU make and are used to manage
1451 // parallelism between processes. A jobserver is a glorified IPC semaphore
1452 // basically. Whenever we want to run some work we acquire the semaphore,
1453 // and whenever we're done with that work we release the semaphore. In this
1454 // manner we can ensure that the maximum number of parallel workers is
1455 // capped at any one point in time.
1456 //
1457 // LTO and the coordinator thread
1458 // ------------------------------
1459 //
1460 // The final job the coordinator thread is responsible for is managing LTO
1461 // and how that works. When LTO is requested what we'll do is collect all
1462 // optimized LLVM modules into a local vector on the coordinator. Once all
1463 // modules have been codegened and optimized we hand this to the `lto`
1464 // module for further optimization. The `lto` module will return back a list
1465 // of more modules to work on, which the coordinator will continue to spawn
1466 // work for.
1467 //
1468 // Each LLVM module is automatically sent back to the coordinator for LTO if
1469 // necessary. There's already optimizations in place to avoid sending work
1470 // back to the coordinator if LTO isn't requested.
1471let f = move || {
1472let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14731474// This is where we collect codegen units that have gone all the way
1475 // through codegen and LLVM.
1476let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1477let mut needs_fat_lto = Vec::new();
1478let mut needs_thin_lto = Vec::new();
1479let mut lto_import_only_modules = Vec::new();
14801481/// Possible state transitions:
1482 /// - Ongoing -> Completed
1483 /// - Ongoing -> Aborted
1484 /// - Completed -> Aborted
1485#[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::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)]
1486enum CodegenState {
1487 Ongoing,
1488 Completed,
1489 Aborted,
1490 }
1491use CodegenState::*;
1492let mut codegen_state = Ongoing;
14931494// This is the queue of LLVM work items that still need processing.
1495let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14961497// This are the Jobserver Tokens we currently hold. Does not include
1498 // the implicit Token the compiler process owns no matter what.
1499let mut tokens = Vec::new();
15001501let mut main_thread_state = MainThreadState::Idle;
15021503// How many LLVM worker threads are running while holding a Token. This
1504 // *excludes* any that the main thread is lending a Token to.
1505let mut running_with_own_token = 0;
15061507// How many LLVM worker threads are running in total. This *includes*
1508 // any that the main thread is lending a Token to.
1509let running_with_any_token = |main_thread_state, running_with_own_token| {
1510running_with_own_token1511 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1512 };
15131514let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
15151516if let Some(allocator_module) = &mut allocator_module {
1517 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1518 }
15191520// Run the message loop while there's still anything that needs message
1521 // processing. Note that as soon as codegen is aborted we simply want to
1522 // wait for all existing work to finish, so many of the conditions here
1523 // only apply if codegen hasn't been aborted as they represent pending
1524 // work to be done.
1525loop {
1526// While there are still CGUs to be codegened, the coordinator has
1527 // to decide how to utilize the compiler processes implicit Token:
1528 // For codegenning more CGU or for running them through LLVM.
1529if codegen_state == Ongoing {
1530if main_thread_state == MainThreadState::Idle {
1531// Compute the number of workers that will be running once we've taken as many
1532 // items from the work queue as we can, plus one for the main thread. It's not
1533 // critically important that we use this instead of just
1534 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1535 // from fluctuating just because a worker finished up and we decreased the
1536 // `running_with_own_token` count, even though we're just going to increase it
1537 // right after this when we put a new worker to work.
1538let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1539let additional_running = std::cmp::min(extra_tokens, work_items.len());
1540let anticipated_running = running_with_own_token + additional_running + 1;
15411542if !queue_full_enough(work_items.len(), anticipated_running) {
1543// The queue is not full enough, process more codegen units:
1544if codegen_worker_send.send(CguMessage).is_err() {
1545{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1546 }
1547main_thread_state = MainThreadState::Codegenning;
1548 } else {
1549// The queue is full enough to not let the worker
1550 // threads starve. Use the implicit Token to do some
1551 // LLVM work too.
1552let (item, _) =
1553work_items.pop().expect("queue empty - queue_full_enough() broken?");
1554main_thread_state = MainThreadState::Lending;
1555spawn_work(
1556&cgcx,
1557&prof,
1558shared_emitter.clone(),
1559coordinator_send.clone(),
1560&mut llvm_start_time,
1561item,
1562 );
1563 }
1564 }
1565 } else if codegen_state == Completed {
1566if running_with_any_token(main_thread_state, running_with_own_token) == 0
1567&& work_items.is_empty()
1568 {
1569// All codegen work is done.
1570break;
1571 }
15721573// In this branch, we know that everything has been codegened,
1574 // so it's just a matter of determining whether the implicit
1575 // Token is free to use for LLVM work.
1576match main_thread_state {
1577 MainThreadState::Idle => {
1578if let Some((item, _)) = work_items.pop() {
1579main_thread_state = MainThreadState::Lending;
1580spawn_work(
1581&cgcx,
1582&prof,
1583shared_emitter.clone(),
1584coordinator_send.clone(),
1585&mut llvm_start_time,
1586item,
1587 );
1588 } else {
1589// There is no unstarted work, so let the main thread
1590 // take over for a running worker. Otherwise the
1591 // implicit token would just go to waste.
1592 // We reduce the `running` counter by one. The
1593 // `tokens.truncate()` below will take care of
1594 // giving the Token back.
1595if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1596running_with_own_token -= 1;
1597main_thread_state = MainThreadState::Lending;
1598 }
1599 }
1600 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1601"codegen worker should not be codegenning after \
1602 codegen was already completed"
1603),
1604 MainThreadState::Lending => {
1605// Already making good use of that token
1606}
1607 }
1608 } else {
1609// Don't queue up any more work if codegen was aborted, we're
1610 // just waiting for our existing children to finish.
1611if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1612if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1613break;
1614 }
1615 }
16161617// Spin up what work we can, only doing this while we've got available
1618 // parallelism slots and work left to spawn.
1619if codegen_state != Aborted {
1620while running_with_own_token < tokens.len()
1621 && let Some((item, _)) = work_items.pop()
1622 {
1623 spawn_work(
1624&cgcx,
1625&prof,
1626 shared_emitter.clone(),
1627 coordinator_send.clone(),
1628&mut llvm_start_time,
1629 item,
1630 );
1631 running_with_own_token += 1;
1632 }
1633 }
16341635// Relinquish accidentally acquired extra tokens.
1636tokens.truncate(running_with_own_token);
16371638match coordinator_receive.recv().unwrap() {
1639// Save the token locally and the next turn of the loop will use
1640 // this to spawn a new unit of work, or it may get dropped
1641 // immediately if we have no more work to spawn.
1642Message::Token(token) => {
1643match token {
1644Ok(token) => {
1645tokens.push(token);
16461647if main_thread_state == MainThreadState::Lending {
1648// If the main thread token is used for LLVM work
1649 // at the moment, we turn that thread into a regular
1650 // LLVM worker thread, so the main thread is free
1651 // to react to codegen demand.
1652main_thread_state = MainThreadState::Idle;
1653running_with_own_token += 1;
1654 }
1655 }
1656Err(e) => {
1657let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1658shared_emitter.fatal(msg);
1659codegen_state = Aborted;
1660 }
1661 }
1662 }
16631664 Message::CodegenDone { llvm_work_item, cost } => {
1665// We keep the queue sorted by estimated processing cost,
1666 // so that more expensive items are processed earlier. This
1667 // is good for throughput as it gives the main thread more
1668 // time to fill up the queue and it avoids scheduling
1669 // expensive items to the end.
1670 // Note, however, that this is not ideal for memory
1671 // consumption, as LLVM module sizes are not evenly
1672 // distributed.
1673let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1674let insertion_index = match insertion_index {
1675Ok(idx) | Err(idx) => idx,
1676 };
1677work_items.insert(insertion_index, (llvm_work_item, cost));
16781679if cgcx.parallel {
1680helper.request_token();
1681 }
1682match (&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);
1683main_thread_state = MainThreadState::Idle;
1684 }
16851686 Message::CodegenComplete => {
1687if codegen_state != Aborted {
1688codegen_state = Completed;
1689 }
1690match (&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);
1691main_thread_state = MainThreadState::Idle;
1692 }
16931694// If codegen is aborted that means translation was aborted due
1695 // to some normal-ish compiler error. In this situation we want
1696 // to exit as soon as possible, but we want to make sure all
1697 // existing work has finished. Flag codegen as being done, and
1698 // then conditions above will ensure no more work is spawned but
1699 // we'll keep executing this loop until `running_with_own_token`
1700 // hits 0.
1701Message::CodegenAborted => {
1702codegen_state = Aborted;
1703 }
17041705 Message::WorkItem { result } => {
1706// If a thread exits successfully then we drop a token associated
1707 // with that worker and update our `running_with_own_token` count.
1708 // We may later re-acquire a token to continue running more work.
1709 // We may also not actually drop a token here if the worker was
1710 // running with an "ephemeral token".
1711if main_thread_state == MainThreadState::Lending {
1712main_thread_state = MainThreadState::Idle;
1713 } else {
1714running_with_own_token -= 1;
1715 }
17161717match result {
1718Ok(WorkItemResult::Finished(compiled_module)) => {
1719compiled_modules.push(compiled_module);
1720 }
1721Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1722if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1723needs_fat_lto.push(fat_lto_input);
1724 }
1725Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1726if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1727needs_thin_lto.push((name, thin_buffer));
1728 }
1729Err(Some(WorkerFatalError)) => {
1730// Like `CodegenAborted`, wait for remaining work to finish.
1731codegen_state = Aborted;
1732 }
1733Err(None) => {
1734// If the thread failed that means it panicked, so
1735 // we abort immediately.
1736::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1737 }
1738 }
1739 }
17401741 Message::AddImportOnlyModule { module_data, work_product } => {
1742match (&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);
1743match (&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);
1744lto_import_only_modules.push((module_data, work_product));
1745main_thread_state = MainThreadState::Idle;
1746 }
1747 }
1748 }
17491750// Drop to print timings
1751drop(llvm_start_time);
17521753if codegen_state == Aborted {
1754return Err(());
1755 }
17561757drop(codegen_state);
1758drop(tokens);
1759drop(helper);
1760if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17611762if !needs_fat_lto.is_empty() {
1763if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1764if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17651766if let Some(allocator_module) = allocator_module.take() {
1767needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1768 }
17691770return Ok(MaybeLtoModules::FatLto {
1771cgcx,
1772exported_symbols_for_lto,
1773each_linked_rlib_file_for_lto,
1774needs_fat_lto,
1775lto_import_only_modules,
1776 });
1777 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1778if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1779if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17801781if cgcx.lto == Lto::ThinLocal {
1782compiled_modules.extend(do_thin_lto::<B>(
1783&cgcx,
1784&prof,
1785shared_emitter.clone(),
1786tm_factory,
1787exported_symbols_for_lto,
1788each_linked_rlib_file_for_lto,
1789needs_thin_lto,
1790lto_import_only_modules,
1791 ));
1792 } else {
1793if let Some(allocator_module) = allocator_module.take() {
1794let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1795needs_thin_lto.push((allocator_module.name, thin_buffer));
1796 }
17971798return Ok(MaybeLtoModules::ThinLto {
1799cgcx,
1800exported_symbols_for_lto,
1801each_linked_rlib_file_for_lto,
1802needs_thin_lto,
1803lto_import_only_modules,
1804 });
1805 }
1806 }
18071808Ok(MaybeLtoModules::NoLto(CompiledModules {
1809 modules: compiled_modules,
1810 allocator_module: allocator_module.map(|allocator_module| {
1811 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1812 }),
1813 }))
1814 };
1815return std::thread::Builder::new()
1816 .name("coordinator".to_owned())
1817 .spawn(f)
1818 .expect("failed to spawn coordinator thread");
18191820// A heuristic that determines if we have enough LLVM WorkItems in the
1821 // queue so that the main thread can do LLVM work instead of codegen
1822fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1823// This heuristic scales ahead-of-time codegen according to available
1824 // concurrency, as measured by `workers_running`. The idea is that the
1825 // more concurrency we have available, the more demand there will be for
1826 // work items, and the fuller the queue should be kept to meet demand.
1827 // An important property of this approach is that we codegen ahead of
1828 // time only as much as necessary, so as to keep fewer LLVM modules in
1829 // memory at once, thereby reducing memory consumption.
1830 //
1831 // When the number of workers running is less than the max concurrency
1832 // available to us, this heuristic can cause us to instruct the main
1833 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1834 // of codegen, even though it seems like it *should* be codegenning so
1835 // that we can create more work items and spawn more LLVM workers.
1836 //
1837 // But this is not a problem. When the main thread is told to LLVM,
1838 // according to this heuristic and how work is scheduled, there is
1839 // always at least one item in the queue, and therefore at least one
1840 // pending jobserver token request. If there *is* more concurrency
1841 // available, we will immediately receive a token, which will upgrade
1842 // the main thread's LLVM worker to a real one (conceptually), and free
1843 // up the main thread to codegen if necessary. On the other hand, if
1844 // there isn't more concurrency, then the main thread working on an LLVM
1845 // item is appropriate, as long as the queue is full enough for demand.
1846 //
1847 // Speaking of which, how full should we keep the queue? Probably less
1848 // full than you'd think. A lot has to go wrong for the queue not to be
1849 // full enough and for that to have a negative effect on compile times.
1850 //
1851 // Workers are unlikely to finish at exactly the same time, so when one
1852 // finishes and takes another work item off the queue, we often have
1853 // ample time to codegen at that point before the next worker finishes.
1854 // But suppose that codegen takes so long that the workers exhaust the
1855 // queue, and we have one or more workers that have nothing to work on.
1856 // Well, it might not be so bad. Of all the LLVM modules we create and
1857 // optimize, one has to finish last. It's not necessarily the case that
1858 // by losing some concurrency for a moment, we delay the point at which
1859 // that last LLVM module is finished and the rest of compilation can
1860 // proceed. Also, when we can't take advantage of some concurrency, we
1861 // give tokens back to the job server. That enables some other rustc to
1862 // potentially make use of the available concurrency. That could even
1863 // *decrease* overall compile time if we're lucky. But yes, if no other
1864 // rustc can make use of the concurrency, then we've squandered it.
1865 //
1866 // However, keeping the queue full is also beneficial when we have a
1867 // surge in available concurrency. Then items can be taken from the
1868 // queue immediately, without having to wait for codegen.
1869 //
1870 // So, the heuristic below tries to keep one item in the queue for every
1871 // four running workers. Based on limited benchmarking, this appears to
1872 // be more than sufficient to avoid increasing compilation times.
1873let quarter_of_workers = workers_running - 3 * workers_running / 4;
1874items_in_queue > 0 && items_in_queue >= quarter_of_workers1875 }
1876}
18771878/// `FatalError` is explicitly not `Send`.
1879#[must_use]
1880pub(crate) struct WorkerFatalError;
18811882fn spawn_work<'a, B: WriteBackendMethods>(
1883 cgcx: &CodegenContext,
1884 prof: &'a SelfProfilerRef,
1885 shared_emitter: SharedEmitter,
1886 coordinator_send: Sender<Message<B>>,
1887 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1888 work: WorkItem<B>,
1889) {
1890if llvm_start_time.is_none() {
1891*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1892 }
18931894let cgcx = cgcx.clone();
1895let prof = prof.clone();
18961897let name = work.short_description();
1898let f = move || {
1899let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19001901let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1902 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1903 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1904execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1905 ),
1906 }));
19071908let msg = match result {
1909Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
19101911// We ignore any `FatalError` coming out of `execute_work_item`, as a
1912 // diagnostic was already sent off to the main thread - just surface
1913 // that there was an error in this worker.
1914Err(err) if err.is::<FatalErrorMarker>() => {
1915 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1916 }
19171918Err(_) => Message::WorkItem::<B> { result: Err(None) },
1919 };
1920drop(coordinator_send.send(msg));
1921 };
1922 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1923}
19241925fn spawn_thin_lto_work<B: WriteBackendMethods>(
1926 cgcx: &CodegenContext,
1927 prof: &SelfProfilerRef,
1928 shared_emitter: SharedEmitter,
1929 tm_factory: TargetMachineFactoryFn<B>,
1930 coordinator_send: Sender<ThinLtoMessage>,
1931 work: ThinLtoWorkItem<B>,
1932) {
1933let cgcx = cgcx.clone();
1934let prof = prof.clone();
19351936let name = work.short_description();
1937let f = move || {
1938let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19391940let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1941 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1942execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1943 }
1944 ThinLtoWorkItem::ThinLto(m) => {
1945execute_thin_lto_work_item(&cgcx, &prof, shared_emitter, tm_factory, m)
1946 }
1947 }));
19481949let msg = match result {
1950Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19511952// We ignore any `FatalError` coming out of `execute_work_item`, as a
1953 // diagnostic was already sent off to the main thread - just surface
1954 // that there was an error in this worker.
1955Err(err) if err.is::<FatalErrorMarker>() => {
1956 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1957 }
19581959Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1960 };
1961drop(coordinator_send.send(msg));
1962 };
1963 std::thread::Builder::new().name(name).spawn(f).expect("failed to spawn work thread");
1964}
19651966enum SharedEmitterMessage {
1967 Diagnostic(Diagnostic),
1968 InlineAsmError(InlineAsmError),
1969 Fatal(String),
1970}
19711972pub struct InlineAsmError {
1973pub span: SpanData,
1974pub msg: String,
1975pub level: Level,
1976pub source: Option<(String, Vec<InnerSpan>)>,
1977}
19781979#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1980pub struct SharedEmitter {
1981 sender: Sender<SharedEmitterMessage>,
1982}
19831984pub struct SharedEmitterMain {
1985 receiver: Receiver<SharedEmitterMessage>,
1986}
19871988impl SharedEmitter {
1989fn new() -> (SharedEmitter, SharedEmitterMain) {
1990let (sender, receiver) = channel();
19911992 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1993 }
19941995pub fn inline_asm_error(&self, err: InlineAsmError) {
1996drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1997 }
19981999fn fatal(&self, msg: &str) {
2000drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2001 }
2002}
20032004impl Emitterfor SharedEmitter {
2005fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
2006// Check that we aren't missing anything interesting when converting to
2007 // the cut-down local `DiagInner`.
2008if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
2009match (&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![]));
2010match (&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);
2011match (&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);
2012// No sensible check for `diag.emitted_at`.
20132014let args = mem::replace(&mut diag.args, DiagArgMap::default());
2015drop(
2016self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2017 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2018 level: diag.level(),
2019 messages: diag.messages,
2020 code: diag.code,
2021 children: diag2022 .children
2023 .into_iter()
2024 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2025 .collect(),
2026args,
2027 })),
2028 );
2029 }
20302031fn source_map(&self) -> Option<&SourceMap> {
2032None2033 }
2034}
20352036impl SharedEmitterMain {
2037fn check(&self, sess: &Session, blocking: bool) {
2038loop {
2039let message = if blocking {
2040match self.receiver.recv() {
2041Ok(message) => Ok(message),
2042Err(_) => Err(()),
2043 }
2044 } else {
2045match self.receiver.try_recv() {
2046Ok(message) => Ok(message),
2047Err(_) => Err(()),
2048 }
2049 };
20502051match message {
2052Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2053// The diagnostic has been received on the main thread.
2054 // Convert it back to a full `Diagnostic` and emit.
2055let dcx = sess.dcx();
2056let mut d =
2057 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2058d.span = MultiSpan::from_spans(
2059diag.span.into_iter().map(|span| span.span()).collect(),
2060 );
2061d.code = diag.code; // may be `None`, that's ok
2062d.children = diag2063 .children
2064 .into_iter()
2065 .map(|sub| rustc_errors::Subdiag {
2066 level: sub.level,
2067 messages: sub.messages,
2068 span: MultiSpan::new(),
2069 })
2070 .collect();
2071d.args = diag.args;
2072dcx.emit_diagnostic(d);
2073sess.dcx().abort_if_errors();
2074 }
2075Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2076match 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);
2077let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2078if !inner.span.is_dummy() {
2079err.span(inner.span.span());
2080 }
20812082// Point to the generated assembly if it is available.
2083if let Some((buffer, spans)) = inner.source {
2084let source = sess2085 .source_map()
2086 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2087let spans: Vec<_> = spans2088 .iter()
2089 .map(|sp| {
2090Span::with_root_ctxt(
2091source.normalized_byte_pos(sp.start as u32),
2092source.normalized_byte_pos(sp.end as u32),
2093 )
2094 })
2095 .collect();
2096err.span_note(spans, "instantiated into assembly here");
2097 }
20982099err.emit();
2100 }
2101Ok(SharedEmitterMessage::Fatal(msg)) => {
2102sess.dcx().fatal(msg);
2103 }
2104Err(_) => {
2105break;
2106 }
2107 }
2108 }
2109 }
2110}
21112112pub struct Coordinator<B: WriteBackendMethods> {
2113 sender: Sender<Message<B>>,
2114 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2115// Only used for the Message type.
2116phantom: PhantomData<B>,
2117}
21182119impl<B: WriteBackendMethods> Coordinator<B> {
2120fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2121self.future.take().unwrap().join()
2122 }
2123}
21242125impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2126fn drop(&mut self) {
2127if let Some(future) = self.future.take() {
2128// If we haven't joined yet, signal to the coordinator that it should spawn no more
2129 // work, and wait for worker threads to finish.
2130drop(self.sender.send(Message::CodegenAborted::<B>));
2131drop(future.join());
2132 }
2133 }
2134}
21352136pub struct OngoingCodegen<B: WriteBackendMethods> {
2137pub backend: B,
2138pub output_filenames: Arc<OutputFilenames>,
2139// Field order below is intended to terminate the coordinator thread before two fields below
2140 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2141 // `Drop` implementation for more info.
2142pub coordinator: Coordinator<B>,
2143pub codegen_worker_receive: Receiver<CguMessage>,
2144pub shared_emitter_main: SharedEmitterMain,
2145}
21462147impl<B: WriteBackendMethods> OngoingCodegen<B> {
2148pub fn join(self, sess: &Session) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
2149self.shared_emitter_main.check(sess, true);
21502151let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2152Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2153Ok(Err(())) => {
2154sess.dcx().abort_if_errors();
2155{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2156 }
2157Err(_) => {
2158::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2159 }
2160 });
21612162sess.dcx().abort_if_errors();
21632164let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21652166// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2167let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2168 MaybeLtoModules::NoLto(compiled_modules) => {
2169drop(shared_emitter);
2170compiled_modules2171 }
2172 MaybeLtoModules::FatLto {
2173 cgcx,
2174 exported_symbols_for_lto,
2175 each_linked_rlib_file_for_lto,
2176 needs_fat_lto,
2177 lto_import_only_modules,
2178 } => {
2179let tm_factory = self.backend.target_machine_factory(
2180sess,
2181cgcx.opt_level,
2182&cgcx.backend_features,
2183 );
21842185CompiledModules {
2186 modules: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[do_fat_lto(&cgcx, &sess.prof, shared_emitter, tm_factory,
&exported_symbols_for_lto, &each_linked_rlib_file_for_lto,
needs_fat_lto, lto_import_only_modules)]))vec![do_fat_lto(
2187&cgcx,
2188&sess.prof,
2189 shared_emitter,
2190 tm_factory,
2191&exported_symbols_for_lto,
2192&each_linked_rlib_file_for_lto,
2193 needs_fat_lto,
2194 lto_import_only_modules,
2195 )],
2196 allocator_module: None,
2197 }
2198 }
2199 MaybeLtoModules::ThinLto {
2200 cgcx,
2201 exported_symbols_for_lto,
2202 each_linked_rlib_file_for_lto,
2203 needs_thin_lto,
2204 lto_import_only_modules,
2205 } => {
2206let tm_factory = self.backend.target_machine_factory(
2207sess,
2208cgcx.opt_level,
2209&cgcx.backend_features,
2210 );
22112212CompiledModules {
2213 modules: do_thin_lto::<B>(
2214&cgcx,
2215&sess.prof,
2216shared_emitter,
2217tm_factory,
2218exported_symbols_for_lto,
2219each_linked_rlib_file_for_lto,
2220needs_thin_lto,
2221lto_import_only_modules,
2222 ),
2223 allocator_module: None,
2224 }
2225 }
2226 });
22272228shared_emitter_main.check(sess, true);
22292230sess.dcx().abort_if_errors();
22312232let mut compiled_modules =
2233compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
22342235// Regardless of what order these modules completed in, report them to
2236 // the backend in the same order every time to ensure that we're handing
2237 // out deterministic results.
2238compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22392240let work_products =
2241copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2242produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22432244 (compiled_modules, work_products)
2245 }
22462247pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2248self.wait_for_signal_to_codegen_item();
2249self.check_for_errors(tcx.sess);
2250drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2251 }
22522253pub(crate) fn check_for_errors(&self, sess: &Session) {
2254self.shared_emitter_main.check(sess, false);
2255 }
22562257pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2258match self.codegen_worker_receive.recv() {
2259Ok(CguMessage) => {
2260// Ok to proceed.
2261}
2262Err(_) => {
2263// One of the LLVM threads must have panicked, fall through so
2264 // error handling can be reached.
2265}
2266 }
2267 }
2268}
22692270pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2271 coordinator: &Coordinator<B>,
2272 module: ModuleCodegen<B::Module>,
2273 cost: u64,
2274) {
2275let llvm_work_item = WorkItem::Optimize(module);
2276drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2277}
22782279pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2280 coordinator: &Coordinator<B>,
2281 module: CachedModuleCodegen,
2282) {
2283let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2284drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2285}
22862287pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2288 tcx: TyCtxt<'_>,
2289 coordinator: &Coordinator<B>,
2290 module: CachedModuleCodegen,
2291) {
2292let filename = pre_lto_bitcode_filename(&module.name);
2293let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2294let file = fs::File::open(&bc_path)
2295 .unwrap_or_else(|e| {
::core::panicking::panic_fmt(format_args!("failed to open bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
22962297let mmap = unsafe {
2298Mmap::map(file).unwrap_or_else(|e| {
2299{
::core::panicking::panic_fmt(format_args!("failed to mmap bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)2300 })
2301 };
2302// Schedule the module to be loaded
2303drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2304 module_data: SerializedModule::FromUncompressedFile(mmap),
2305 work_product: module.source,
2306 }));
2307}
23082309fn pre_lto_bitcode_filename(module_name: &str) -> String {
2310::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2311}
23122313fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2314// This should never be true (because it's not supported). If it is true,
2315 // something is wrong with commandline arg validation.
2316if !!(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!(
2317 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2318 && tcx.sess.target.is_like_windows
2319 && tcx.sess.opts.cg.prefer_dynamic)
2320 );
23212322// We need to generate _imp__ symbol if we are generating an rlib or we include one
2323 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2324 // these, but it currently does not do so.
2325let can_have_static_objects =
2326tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23272328tcx.sess.target.is_like_windows &&
2329can_have_static_objects &&
2330// ThinLTO can't handle this workaround in all cases, so we don't
2331 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2332 // dynamic linking when linker plugin LTO is enabled.
2333!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2334}